Kromek Radangel gamma spectrometer USB HID daemon and WebUI. https://git.unino.de/pvivell/radangel
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

plotly-cartesian-latest.js 2.6MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601
  1. /**
  2. * plotly.js (cartesian) v1.44.4
  3. * Copyright 2012-2019, Plotly, Inc.
  4. * All rights reserved.
  5. * Licensed under the MIT license
  6. */
  7. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.Plotly = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(_dereq_,module,exports){
  8. 'use strict';
  9. var Lib = _dereq_('../src/lib');
  10. var rules = {
  11. "X,X div": "direction:ltr;font-family:'Open Sans', verdana, arial, sans-serif;margin:0;padding:0;",
  12. "X input,X button": "font-family:'Open Sans', verdana, arial, sans-serif;",
  13. "X input:focus,X button:focus": "outline:none;",
  14. "X a": "text-decoration:none;",
  15. "X a:hover": "text-decoration:none;",
  16. "X .crisp": "shape-rendering:crispEdges;",
  17. "X .user-select-none": "-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;",
  18. "X svg": "overflow:hidden;",
  19. "X svg a": "fill:#447adb;",
  20. "X svg a:hover": "fill:#3c6dc5;",
  21. "X .main-svg": "position:absolute;top:0;left:0;pointer-events:none;",
  22. "X .main-svg .draglayer": "pointer-events:all;",
  23. "X .cursor-default": "cursor:default;",
  24. "X .cursor-pointer": "cursor:pointer;",
  25. "X .cursor-crosshair": "cursor:crosshair;",
  26. "X .cursor-move": "cursor:move;",
  27. "X .cursor-col-resize": "cursor:col-resize;",
  28. "X .cursor-row-resize": "cursor:row-resize;",
  29. "X .cursor-ns-resize": "cursor:ns-resize;",
  30. "X .cursor-ew-resize": "cursor:ew-resize;",
  31. "X .cursor-sw-resize": "cursor:sw-resize;",
  32. "X .cursor-s-resize": "cursor:s-resize;",
  33. "X .cursor-se-resize": "cursor:se-resize;",
  34. "X .cursor-w-resize": "cursor:w-resize;",
  35. "X .cursor-e-resize": "cursor:e-resize;",
  36. "X .cursor-nw-resize": "cursor:nw-resize;",
  37. "X .cursor-n-resize": "cursor:n-resize;",
  38. "X .cursor-ne-resize": "cursor:ne-resize;",
  39. "X .cursor-grab": "cursor:-webkit-grab;cursor:grab;",
  40. "X .modebar": "position:absolute;top:2px;right:2px;z-index:1001;",
  41. "X .ease-bg": "-webkit-transition:background-color 0.3s ease 0s;-moz-transition:background-color 0.3s ease 0s;-ms-transition:background-color 0.3s ease 0s;-o-transition:background-color 0.3s ease 0s;transition:background-color 0.3s ease 0s;",
  42. "X .modebar--hover>:not(.watermark)": "opacity:0;-webkit-transition:opacity 0.3s ease 0s;-moz-transition:opacity 0.3s ease 0s;-ms-transition:opacity 0.3s ease 0s;-o-transition:opacity 0.3s ease 0s;transition:opacity 0.3s ease 0s;",
  43. "X:hover .modebar--hover .modebar-group": "opacity:1;",
  44. "X .modebar-group": "float:left;display:inline-block;box-sizing:border-box;margin-left:8px;position:relative;vertical-align:middle;white-space:nowrap;",
  45. "X .modebar-btn": "position:relative;font-size:16px;padding:3px 4px;height:22px;cursor:pointer;line-height:normal;box-sizing:border-box;",
  46. "X .modebar-btn svg": "position:relative;top:2px;",
  47. "X .modebar.vertical": "display:flex;flex-direction:column;flex-wrap:wrap;align-content:flex-end;max-height:100%;",
  48. "X .modebar.vertical svg": "top:-1px;",
  49. "X .modebar.vertical .modebar-group": "display:block;float:none;margin-left:0px;margin-bottom:8px;",
  50. "X .modebar.vertical .modebar-group .modebar-btn": "display:block;text-align:center;",
  51. "X [data-title]:before,X [data-title]:after": "position:absolute;-webkit-transform:translate3d(0, 0, 0);-moz-transform:translate3d(0, 0, 0);-ms-transform:translate3d(0, 0, 0);-o-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0);display:none;opacity:0;z-index:1001;pointer-events:none;top:110%;right:50%;",
  52. "X [data-title]:hover:before,X [data-title]:hover:after": "display:block;opacity:1;",
  53. "X [data-title]:before": "content:'';position:absolute;background:transparent;border:6px solid transparent;z-index:1002;margin-top:-12px;border-bottom-color:#69738a;margin-right:-6px;",
  54. "X [data-title]:after": "content:attr(data-title);background:#69738a;color:white;padding:8px 10px;font-size:12px;line-height:12px;white-space:nowrap;margin-right:-18px;border-radius:2px;",
  55. "X .vertical [data-title]:before,X .vertical [data-title]:after": "top:0%;right:200%;",
  56. "X .vertical [data-title]:before": "border:6px solid transparent;border-left-color:#69738a;margin-top:8px;margin-right:-30px;",
  57. "X .select-outline": "fill:none;stroke-width:1;shape-rendering:crispEdges;",
  58. "X .select-outline-1": "stroke:white;",
  59. "X .select-outline-2": "stroke:black;stroke-dasharray:2px 2px;",
  60. Y: "font-family:'Open Sans';position:fixed;top:50px;right:20px;z-index:10000;font-size:10pt;max-width:180px;",
  61. "Y p": "margin:0;",
  62. "Y .notifier-note": "min-width:180px;max-width:250px;border:1px solid #fff;z-index:3000;margin:0;background-color:#8c97af;background-color:rgba(140,151,175,0.9);color:#fff;padding:10px;overflow-wrap:break-word;word-wrap:break-word;-ms-hyphens:auto;-webkit-hyphens:auto;hyphens:auto;",
  63. "Y .notifier-close": "color:#fff;opacity:0.8;float:right;padding:0 5px;background:none;border:none;font-size:20px;font-weight:bold;line-height:20px;",
  64. "Y .notifier-close:hover": "color:#444;text-decoration:none;cursor:pointer;"
  65. };
  66. for(var selector in rules) {
  67. var fullSelector = selector.replace(/^,/,' ,')
  68. .replace(/X/g, '.js-plotly-plot .plotly')
  69. .replace(/Y/g, '.plotly-notifier');
  70. Lib.addStyleRule(fullSelector, rules[selector]);
  71. }
  72. },{"../src/lib":168}],2:[function(_dereq_,module,exports){
  73. 'use strict';
  74. module.exports = {
  75. 'undo': {
  76. 'width': 857.1,
  77. 'height': 1000,
  78. 'path': 'm857 350q0-87-34-166t-91-137-137-92-166-34q-96 0-183 41t-147 114q-4 6-4 13t5 11l76 77q6 5 14 5 9-1 13-7 41-53 100-82t126-29q58 0 110 23t92 61 61 91 22 111-22 111-61 91-92 61-110 23q-55 0-105-20t-90-57l77-77q17-16 8-38-10-23-33-23h-250q-15 0-25 11t-11 25v250q0 24 22 33 22 10 39-8l72-72q60 57 137 88t159 31q87 0 166-34t137-92 91-137 34-166z',
  79. 'transform': 'matrix(1 0 0 -1 0 850)'
  80. },
  81. 'home': {
  82. 'width': 928.6,
  83. 'height': 1000,
  84. 'path': 'm786 296v-267q0-15-11-26t-25-10h-214v214h-143v-214h-214q-15 0-25 10t-11 26v267q0 1 0 2t0 2l321 264 321-264q1-1 1-4z m124 39l-34-41q-5-5-12-6h-2q-7 0-12 3l-386 322-386-322q-7-4-13-4-7 2-12 7l-35 41q-4 5-3 13t6 12l401 334q18 15 42 15t43-15l136-114v109q0 8 5 13t13 5h107q8 0 13-5t5-13v-227l122-102q5-5 6-12t-4-13z',
  85. 'transform': 'matrix(1 0 0 -1 0 850)'
  86. },
  87. 'camera-retro': {
  88. 'width': 1000,
  89. 'height': 1000,
  90. 'path': 'm518 386q0 8-5 13t-13 5q-37 0-63-27t-26-63q0-8 5-13t13-5 12 5 5 13q0 23 16 38t38 16q8 0 13 5t5 13z m125-73q0-59-42-101t-101-42-101 42-42 101 42 101 101 42 101-42 42-101z m-572-320h858v71h-858v-71z m643 320q0 89-62 152t-152 62-151-62-63-152 63-151 151-63 152 63 62 151z m-571 358h214v72h-214v-72z m-72-107h858v143h-462l-36-71h-360v-72z m929 143v-714q0-30-21-51t-50-21h-858q-29 0-50 21t-21 51v714q0 30 21 51t50 21h858q29 0 50-21t21-51z',
  91. 'transform': 'matrix(1 0 0 -1 0 850)'
  92. },
  93. 'zoombox': {
  94. 'width': 1000,
  95. 'height': 1000,
  96. 'path': 'm1000-25l-250 251c40 63 63 138 63 218 0 224-182 406-407 406-224 0-406-182-406-406s183-406 407-406c80 0 155 22 218 62l250-250 125 125z m-812 250l0 438 437 0 0-438-437 0z m62 375l313 0 0-312-313 0 0 312z',
  97. 'transform': 'matrix(1 0 0 -1 0 850)'
  98. },
  99. 'pan': {
  100. 'width': 1000,
  101. 'height': 1000,
  102. 'path': 'm1000 350l-187 188 0-125-250 0 0 250 125 0-188 187-187-187 125 0 0-250-250 0 0 125-188-188 186-187 0 125 252 0 0-250-125 0 187-188 188 188-125 0 0 250 250 0 0-126 187 188z',
  103. 'transform': 'matrix(1 0 0 -1 0 850)'
  104. },
  105. 'zoom_plus': {
  106. 'width': 875,
  107. 'height': 1000,
  108. 'path': 'm1 787l0-875 875 0 0 875-875 0z m687-500l-187 0 0-187-125 0 0 187-188 0 0 125 188 0 0 187 125 0 0-187 187 0 0-125z',
  109. 'transform': 'matrix(1 0 0 -1 0 850)'
  110. },
  111. 'zoom_minus': {
  112. 'width': 875,
  113. 'height': 1000,
  114. 'path': 'm0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z',
  115. 'transform': 'matrix(1 0 0 -1 0 850)'
  116. },
  117. 'autoscale': {
  118. 'width': 1000,
  119. 'height': 1000,
  120. 'path': 'm250 850l-187 0-63 0 0-62 0-188 63 0 0 188 187 0 0 62z m688 0l-188 0 0-62 188 0 0-188 62 0 0 188 0 62-62 0z m-875-938l0 188-63 0 0-188 0-62 63 0 187 0 0 62-187 0z m875 188l0-188-188 0 0-62 188 0 62 0 0 62 0 188-62 0z m-125 188l-1 0-93-94-156 156 156 156 92-93 2 0 0 250-250 0 0-2 93-92-156-156-156 156 94 92 0 2-250 0 0-250 0 0 93 93 157-156-157-156-93 94 0 0 0-250 250 0 0 0-94 93 156 157 156-157-93-93 0 0 250 0 0 250z',
  121. 'transform': 'matrix(1 0 0 -1 0 850)'
  122. },
  123. 'tooltip_basic': {
  124. 'width': 1500,
  125. 'height': 1000,
  126. 'path': 'm375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z',
  127. 'transform': 'matrix(1 0 0 -1 0 850)'
  128. },
  129. 'tooltip_compare': {
  130. 'width': 1125,
  131. 'height': 1000,
  132. 'path': 'm187 786l0 2-187-188 188-187 0 0 937 0 0 373-938 0z m0-499l0 1-187-188 188-188 0 0 937 0 0 376-938-1z',
  133. 'transform': 'matrix(1 0 0 -1 0 850)'
  134. },
  135. 'plotlylogo': {
  136. 'width': 1542,
  137. 'height': 1000,
  138. 'path': 'm0-10h182v-140h-182v140z m228 146h183v-286h-183v286z m225 714h182v-1000h-182v1000z m225-285h182v-715h-182v715z m225 142h183v-857h-183v857z m231-428h182v-429h-182v429z m225-291h183v-138h-183v138z',
  139. 'transform': 'matrix(1 0 0 -1 0 850)'
  140. },
  141. 'z-axis': {
  142. 'width': 1000,
  143. 'height': 1000,
  144. 'path': 'm833 5l-17 108v41l-130-65 130-66c0 0 0 38 0 39 0-1 36-14 39-25 4-15-6-22-16-30-15-12-39-16-56-20-90-22-187-23-279-23-261 0-341 34-353 59 3 60 228 110 228 110-140-8-351-35-351-116 0-120 293-142 474-142 155 0 477 22 477 142 0 50-74 79-163 96z m-374 94c-58-5-99-21-99-40 0-24 65-43 144-43 79 0 143 19 143 43 0 19-42 34-98 40v216h87l-132 135-133-135h88v-216z m167 515h-136v1c16 16 31 34 46 52l84 109v54h-230v-71h124v-1c-16-17-28-32-44-51l-89-114v-51h245v72z',
  145. 'transform': 'matrix(1 0 0 -1 0 850)'
  146. },
  147. '3d_rotate': {
  148. 'width': 1000,
  149. 'height': 1000,
  150. 'path': 'm922 660c-5 4-9 7-14 11-359 263-580-31-580-31l-102 28 58-400c0 1 1 1 2 2 118 108 351 249 351 249s-62 27-100 42c88 83 222 183 347 122 16-8 30-17 44-27-2 1-4 2-6 4z m36-329c0 0 64 229-88 296-62 27-124 14-175-11 157-78 225-208 249-266 8-19 11-31 11-31 2 5 6 15 11 32-5-13-8-20-8-20z m-775-239c70-31 117-50 198-32-121 80-199 346-199 346l-96-15-58-12c0 0 55-226 155-287z m603 133l-317-139c0 0 4-4 19-14 7-5 24-15 24-15s-177-147-389 4c235-287 536-112 536-112l31-22 100 299-4-1z m-298-153c6-4 14-9 24-15 0 0-17 10-24 15z',
  151. 'transform': 'matrix(1 0 0 -1 0 850)'
  152. },
  153. 'camera': {
  154. 'width': 1000,
  155. 'height': 1000,
  156. 'path': 'm500 450c-83 0-150-67-150-150 0-83 67-150 150-150 83 0 150 67 150 150 0 83-67 150-150 150z m400 150h-120c-16 0-34 13-39 29l-31 93c-6 15-23 28-40 28h-340c-16 0-34-13-39-28l-31-94c-6-15-23-28-40-28h-120c-55 0-100-45-100-100v-450c0-55 45-100 100-100h800c55 0 100 45 100 100v450c0 55-45 100-100 100z m-400-550c-138 0-250 112-250 250 0 138 112 250 250 250 138 0 250-112 250-250 0-138-112-250-250-250z m365 380c-19 0-35 16-35 35 0 19 16 35 35 35 19 0 35-16 35-35 0-19-16-35-35-35z',
  157. 'transform': 'matrix(1 0 0 -1 0 850)'
  158. },
  159. 'movie': {
  160. 'width': 1000,
  161. 'height': 1000,
  162. 'path': 'm938 413l-188-125c0 37-17 71-44 94 64 38 107 107 107 187 0 121-98 219-219 219-121 0-219-98-219-219 0-61 25-117 66-156h-115c30 33 49 76 49 125 0 103-84 187-187 187s-188-84-188-187c0-57 26-107 65-141-38-22-65-62-65-109v-250c0-70 56-126 125-126h500c69 0 125 56 125 126l188-126c34 0 62 28 62 63v375c0 35-28 63-62 63z m-750 0c-69 0-125 56-125 125s56 125 125 125 125-56 125-125-56-125-125-125z m406-1c-87 0-157 70-157 157 0 86 70 156 157 156s156-70 156-156-70-157-156-157z',
  163. 'transform': 'matrix(1 0 0 -1 0 850)'
  164. },
  165. 'question': {
  166. 'width': 857.1,
  167. 'height': 1000,
  168. 'path': 'm500 82v107q0 8-5 13t-13 5h-107q-8 0-13-5t-5-13v-107q0-8 5-13t13-5h107q8 0 13 5t5 13z m143 375q0 49-31 91t-77 65-95 23q-136 0-207-119-9-14 4-24l74-55q4-4 10-4 9 0 14 7 30 38 48 51 19 14 48 14 27 0 48-15t21-33q0-21-11-34t-38-25q-35-16-65-48t-29-70v-20q0-8 5-13t13-5h107q8 0 13 5t5 13q0 10 12 27t30 28q18 10 28 16t25 19 25 27 16 34 7 45z m214-107q0-117-57-215t-156-156-215-58-216 58-155 156-58 215 58 215 155 156 216 58 215-58 156-156 57-215z',
  169. 'transform': 'matrix(1 0 0 -1 0 850)'
  170. },
  171. 'disk': {
  172. 'width': 857.1,
  173. 'height': 1000,
  174. 'path': 'm214-7h429v214h-429v-214z m500 0h72v500q0 8-6 21t-11 20l-157 156q-5 6-19 12t-22 5v-232q0-22-15-38t-38-16h-322q-22 0-37 16t-16 38v232h-72v-714h72v232q0 22 16 38t37 16h465q22 0 38-16t15-38v-232z m-214 518v178q0 8-5 13t-13 5h-107q-7 0-13-5t-5-13v-178q0-8 5-13t13-5h107q7 0 13 5t5 13z m357-18v-518q0-22-15-38t-38-16h-750q-23 0-38 16t-16 38v750q0 22 16 38t38 16h517q23 0 50-12t42-26l156-157q16-15 27-42t11-49z',
  175. 'transform': 'matrix(1 0 0 -1 0 850)'
  176. },
  177. 'lasso': {
  178. 'width': 1031,
  179. 'height': 1000,
  180. 'path': 'm1018 538c-36 207-290 336-568 286-277-48-473-256-436-463 10-57 36-108 76-151-13-66 11-137 68-183 34-28 75-41 114-42l-55-70 0 0c-2-1-3-2-4-3-10-14-8-34 5-45 14-11 34-8 45 4 1 1 2 3 2 5l0 0 113 140c16 11 31 24 45 40 4 3 6 7 8 11 48-3 100 0 151 9 278 48 473 255 436 462z m-624-379c-80 14-149 48-197 96 42 42 109 47 156 9 33-26 47-66 41-105z m-187-74c-19 16-33 37-39 60 50-32 109-55 174-68-42-25-95-24-135 8z m360 75c-34-7-69-9-102-8 8 62-16 128-68 170-73 59-175 54-244-5-9 20-16 40-20 61-28 159 121 317 333 354s407-60 434-217c28-159-121-318-333-355z',
  181. 'transform': 'matrix(1 0 0 -1 0 850)'
  182. },
  183. 'selectbox': {
  184. 'width': 1000,
  185. 'height': 1000,
  186. 'path': 'm0 850l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-285l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z',
  187. 'transform': 'matrix(1 0 0 -1 0 850)'
  188. },
  189. 'spikeline': {
  190. 'width': 1000,
  191. 'height': 1000,
  192. 'path': 'M512 409c0-57-46-104-103-104-57 0-104 47-104 104 0 57 47 103 104 103 57 0 103-46 103-103z m-327-39l92 0 0 92-92 0z m-185 0l92 0 0 92-92 0z m370-186l92 0 0 93-92 0z m0-184l92 0 0 92-92 0z',
  193. 'transform': 'matrix(1.5 0 0 -1.5 0 850)'
  194. },
  195. 'newplotlylogo': {
  196. 'name': 'newplotlylogo',
  197. 'svg': '<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 132 132\'><defs><style>.cls-1 {fill: #119dff;} .cls-2 {fill: #25fefd;} .cls-3 {fill: #fff;}</style></defs><title>plotly-logomark</title><g id=\'symbol\'><rect class=\'cls-1\' width=\'132\' height=\'132\' rx=\'6\' ry=\'6\'/><circle class=\'cls-2\' cx=\'78\' cy=\'54\' r=\'6\'/><circle class=\'cls-2\' cx=\'102\' cy=\'30\' r=\'6\'/><circle class=\'cls-2\' cx=\'78\' cy=\'30\' r=\'6\'/><circle class=\'cls-2\' cx=\'54\' cy=\'30\' r=\'6\'/><circle class=\'cls-2\' cx=\'30\' cy=\'30\' r=\'6\'/><circle class=\'cls-2\' cx=\'30\' cy=\'54\' r=\'6\'/><path class=\'cls-3\' d=\'M30,72a6,6,0,0,0-6,6v24a6,6,0,0,0,12,0V78A6,6,0,0,0,30,72Z\'/><path class=\'cls-3\' d=\'M78,72a6,6,0,0,0-6,6v24a6,6,0,0,0,12,0V78A6,6,0,0,0,78,72Z\'/><path class=\'cls-3\' d=\'M54,48a6,6,0,0,0-6,6v48a6,6,0,0,0,12,0V54A6,6,0,0,0,54,48Z\'/><path class=\'cls-3\' d=\'M102,48a6,6,0,0,0-6,6v48a6,6,0,0,0,12,0V54A6,6,0,0,0,102,48Z\'/></g></svg>'
  198. }
  199. };
  200. },{}],3:[function(_dereq_,module,exports){
  201. /**
  202. * Copyright 2012-2019, Plotly, Inc.
  203. * All rights reserved.
  204. *
  205. * This source code is licensed under the MIT license found in the
  206. * LICENSE file in the root directory of this source tree.
  207. */
  208. 'use strict';
  209. module.exports = _dereq_('../src/traces/bar');
  210. },{"../src/traces/bar":274}],4:[function(_dereq_,module,exports){
  211. /**
  212. * Copyright 2012-2019, Plotly, Inc.
  213. * All rights reserved.
  214. *
  215. * This source code is licensed under the MIT license found in the
  216. * LICENSE file in the root directory of this source tree.
  217. */
  218. 'use strict';
  219. module.exports = _dereq_('../src/traces/box');
  220. },{"../src/traces/box":288}],5:[function(_dereq_,module,exports){
  221. /**
  222. * Copyright 2012-2019, Plotly, Inc.
  223. * All rights reserved.
  224. *
  225. * This source code is licensed under the MIT license found in the
  226. * LICENSE file in the root directory of this source tree.
  227. */
  228. 'use strict';
  229. module.exports = _dereq_('../src/traces/contour');
  230. },{"../src/traces/contour":308}],6:[function(_dereq_,module,exports){
  231. /**
  232. * Copyright 2012-2019, Plotly, Inc.
  233. * All rights reserved.
  234. *
  235. * This source code is licensed under the MIT license found in the
  236. * LICENSE file in the root directory of this source tree.
  237. */
  238. 'use strict';
  239. module.exports = _dereq_('../src/core');
  240. },{"../src/core":151}],7:[function(_dereq_,module,exports){
  241. /**
  242. * Copyright 2012-2019, Plotly, Inc.
  243. * All rights reserved.
  244. *
  245. * This source code is licensed under the MIT license found in the
  246. * LICENSE file in the root directory of this source tree.
  247. */
  248. 'use strict';
  249. module.exports = _dereq_('../src/traces/heatmap');
  250. },{"../src/traces/heatmap":324}],8:[function(_dereq_,module,exports){
  251. /**
  252. * Copyright 2012-2019, Plotly, Inc.
  253. * All rights reserved.
  254. *
  255. * This source code is licensed under the MIT license found in the
  256. * LICENSE file in the root directory of this source tree.
  257. */
  258. 'use strict';
  259. module.exports = _dereq_('../src/traces/histogram');
  260. },{"../src/traces/histogram":342}],9:[function(_dereq_,module,exports){
  261. /**
  262. * Copyright 2012-2019, Plotly, Inc.
  263. * All rights reserved.
  264. *
  265. * This source code is licensed under the MIT license found in the
  266. * LICENSE file in the root directory of this source tree.
  267. */
  268. 'use strict';
  269. module.exports = _dereq_('../src/traces/histogram2d');
  270. },{"../src/traces/histogram2d":349}],10:[function(_dereq_,module,exports){
  271. /**
  272. * Copyright 2012-2019, Plotly, Inc.
  273. * All rights reserved.
  274. *
  275. * This source code is licensed under the MIT license found in the
  276. * LICENSE file in the root directory of this source tree.
  277. */
  278. 'use strict';
  279. module.exports = _dereq_('../src/traces/histogram2dcontour');
  280. },{"../src/traces/histogram2dcontour":353}],11:[function(_dereq_,module,exports){
  281. /**
  282. * Copyright 2012-2019, Plotly, Inc.
  283. * All rights reserved.
  284. *
  285. * This source code is licensed under the MIT license found in the
  286. * LICENSE file in the root directory of this source tree.
  287. */
  288. 'use strict';
  289. var Plotly = _dereq_('./core');
  290. Plotly.register([
  291. _dereq_('./bar'),
  292. _dereq_('./box'),
  293. _dereq_('./heatmap'),
  294. _dereq_('./histogram'),
  295. _dereq_('./histogram2d'),
  296. _dereq_('./histogram2dcontour'),
  297. _dereq_('./pie'),
  298. _dereq_('./contour'),
  299. _dereq_('./scatterternary'),
  300. _dereq_('./violin')
  301. ]);
  302. module.exports = Plotly;
  303. },{"./bar":3,"./box":4,"./contour":5,"./core":6,"./heatmap":7,"./histogram":8,"./histogram2d":9,"./histogram2dcontour":10,"./pie":12,"./scatterternary":13,"./violin":14}],12:[function(_dereq_,module,exports){
  304. /**
  305. * Copyright 2012-2019, Plotly, Inc.
  306. * All rights reserved.
  307. *
  308. * This source code is licensed under the MIT license found in the
  309. * LICENSE file in the root directory of this source tree.
  310. */
  311. 'use strict';
  312. module.exports = _dereq_('../src/traces/pie');
  313. },{"../src/traces/pie":360}],13:[function(_dereq_,module,exports){
  314. /**
  315. * Copyright 2012-2019, Plotly, Inc.
  316. * All rights reserved.
  317. *
  318. * This source code is licensed under the MIT license found in the
  319. * LICENSE file in the root directory of this source tree.
  320. */
  321. 'use strict';
  322. module.exports = _dereq_('../src/traces/scatterternary');
  323. },{"../src/traces/scatterternary":399}],14:[function(_dereq_,module,exports){
  324. /**
  325. * Copyright 2012-2019, Plotly, Inc.
  326. * All rights reserved.
  327. *
  328. * This source code is licensed under the MIT license found in the
  329. * LICENSE file in the root directory of this source tree.
  330. */
  331. 'use strict';
  332. module.exports = _dereq_('../src/traces/violin');
  333. },{"../src/traces/violin":407}],15:[function(_dereq_,module,exports){
  334. // Copyright Joyent, Inc. and other Node contributors.
  335. //
  336. // Permission is hereby granted, free of charge, to any person obtaining a
  337. // copy of this software and associated documentation files (the
  338. // "Software"), to deal in the Software without restriction, including
  339. // without limitation the rights to use, copy, modify, merge, publish,
  340. // distribute, sublicense, and/or sell copies of the Software, and to permit
  341. // persons to whom the Software is furnished to do so, subject to the
  342. // following conditions:
  343. //
  344. // The above copyright notice and this permission notice shall be included
  345. // in all copies or substantial portions of the Software.
  346. //
  347. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  348. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  349. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  350. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  351. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  352. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  353. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  354. var objectCreate = Object.create || objectCreatePolyfill
  355. var objectKeys = Object.keys || objectKeysPolyfill
  356. var bind = Function.prototype.bind || functionBindPolyfill
  357. function EventEmitter() {
  358. if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
  359. this._events = objectCreate(null);
  360. this._eventsCount = 0;
  361. }
  362. this._maxListeners = this._maxListeners || undefined;
  363. }
  364. module.exports = EventEmitter;
  365. // Backwards-compat with node 0.10.x
  366. EventEmitter.EventEmitter = EventEmitter;
  367. EventEmitter.prototype._events = undefined;
  368. EventEmitter.prototype._maxListeners = undefined;
  369. // By default EventEmitters will print a warning if more than 10 listeners are
  370. // added to it. This is a useful default which helps finding memory leaks.
  371. var defaultMaxListeners = 10;
  372. var hasDefineProperty;
  373. try {
  374. var o = {};
  375. if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
  376. hasDefineProperty = o.x === 0;
  377. } catch (err) { hasDefineProperty = false }
  378. if (hasDefineProperty) {
  379. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  380. enumerable: true,
  381. get: function() {
  382. return defaultMaxListeners;
  383. },
  384. set: function(arg) {
  385. // check whether the input is a positive number (whose value is zero or
  386. // greater and not a NaN).
  387. if (typeof arg !== 'number' || arg < 0 || arg !== arg)
  388. throw new TypeError('"defaultMaxListeners" must be a positive number');
  389. defaultMaxListeners = arg;
  390. }
  391. });
  392. } else {
  393. EventEmitter.defaultMaxListeners = defaultMaxListeners;
  394. }
  395. // Obviously not all Emitters should be limited to 10. This function allows
  396. // that to be increased. Set to zero for unlimited.
  397. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  398. if (typeof n !== 'number' || n < 0 || isNaN(n))
  399. throw new TypeError('"n" argument must be a positive number');
  400. this._maxListeners = n;
  401. return this;
  402. };
  403. function $getMaxListeners(that) {
  404. if (that._maxListeners === undefined)
  405. return EventEmitter.defaultMaxListeners;
  406. return that._maxListeners;
  407. }
  408. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  409. return $getMaxListeners(this);
  410. };
  411. // These standalone emit* functions are used to optimize calling of event
  412. // handlers for fast cases because emit() itself often has a variable number of
  413. // arguments and can be deoptimized because of that. These functions always have
  414. // the same number of arguments and thus do not get deoptimized, so the code
  415. // inside them can execute faster.
  416. function emitNone(handler, isFn, self) {
  417. if (isFn)
  418. handler.call(self);
  419. else {
  420. var len = handler.length;
  421. var listeners = arrayClone(handler, len);
  422. for (var i = 0; i < len; ++i)
  423. listeners[i].call(self);
  424. }
  425. }
  426. function emitOne(handler, isFn, self, arg1) {
  427. if (isFn)
  428. handler.call(self, arg1);
  429. else {
  430. var len = handler.length;
  431. var listeners = arrayClone(handler, len);
  432. for (var i = 0; i < len; ++i)
  433. listeners[i].call(self, arg1);
  434. }
  435. }
  436. function emitTwo(handler, isFn, self, arg1, arg2) {
  437. if (isFn)
  438. handler.call(self, arg1, arg2);
  439. else {
  440. var len = handler.length;
  441. var listeners = arrayClone(handler, len);
  442. for (var i = 0; i < len; ++i)
  443. listeners[i].call(self, arg1, arg2);
  444. }
  445. }
  446. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  447. if (isFn)
  448. handler.call(self, arg1, arg2, arg3);
  449. else {
  450. var len = handler.length;
  451. var listeners = arrayClone(handler, len);
  452. for (var i = 0; i < len; ++i)
  453. listeners[i].call(self, arg1, arg2, arg3);
  454. }
  455. }
  456. function emitMany(handler, isFn, self, args) {
  457. if (isFn)
  458. handler.apply(self, args);
  459. else {
  460. var len = handler.length;
  461. var listeners = arrayClone(handler, len);
  462. for (var i = 0; i < len; ++i)
  463. listeners[i].apply(self, args);
  464. }
  465. }
  466. EventEmitter.prototype.emit = function emit(type) {
  467. var er, handler, len, args, i, events;
  468. var doError = (type === 'error');
  469. events = this._events;
  470. if (events)
  471. doError = (doError && events.error == null);
  472. else if (!doError)
  473. return false;
  474. // If there is no 'error' event listener then throw.
  475. if (doError) {
  476. if (arguments.length > 1)
  477. er = arguments[1];
  478. if (er instanceof Error) {
  479. throw er; // Unhandled 'error' event
  480. } else {
  481. // At least give some kind of context to the user
  482. var err = new Error('Unhandled "error" event. (' + er + ')');
  483. err.context = er;
  484. throw err;
  485. }
  486. return false;
  487. }
  488. handler = events[type];
  489. if (!handler)
  490. return false;
  491. var isFn = typeof handler === 'function';
  492. len = arguments.length;
  493. switch (len) {
  494. // fast cases
  495. case 1:
  496. emitNone(handler, isFn, this);
  497. break;
  498. case 2:
  499. emitOne(handler, isFn, this, arguments[1]);
  500. break;
  501. case 3:
  502. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  503. break;
  504. case 4:
  505. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  506. break;
  507. // slower
  508. default:
  509. args = new Array(len - 1);
  510. for (i = 1; i < len; i++)
  511. args[i - 1] = arguments[i];
  512. emitMany(handler, isFn, this, args);
  513. }
  514. return true;
  515. };
  516. function _addListener(target, type, listener, prepend) {
  517. var m;
  518. var events;
  519. var existing;
  520. if (typeof listener !== 'function')
  521. throw new TypeError('"listener" argument must be a function');
  522. events = target._events;
  523. if (!events) {
  524. events = target._events = objectCreate(null);
  525. target._eventsCount = 0;
  526. } else {
  527. // To avoid recursion in the case that type === "newListener"! Before
  528. // adding it to the listeners, first emit "newListener".
  529. if (events.newListener) {
  530. target.emit('newListener', type,
  531. listener.listener ? listener.listener : listener);
  532. // Re-assign `events` because a newListener handler could have caused the
  533. // this._events to be assigned to a new object
  534. events = target._events;
  535. }
  536. existing = events[type];
  537. }
  538. if (!existing) {
  539. // Optimize the case of one listener. Don't need the extra array object.
  540. existing = events[type] = listener;
  541. ++target._eventsCount;
  542. } else {
  543. if (typeof existing === 'function') {
  544. // Adding the second element, need to change to array.
  545. existing = events[type] =
  546. prepend ? [listener, existing] : [existing, listener];
  547. } else {
  548. // If we've already got an array, just append.
  549. if (prepend) {
  550. existing.unshift(listener);
  551. } else {
  552. existing.push(listener);
  553. }
  554. }
  555. // Check for listener leak
  556. if (!existing.warned) {
  557. m = $getMaxListeners(target);
  558. if (m && m > 0 && existing.length > m) {
  559. existing.warned = true;
  560. var w = new Error('Possible EventEmitter memory leak detected. ' +
  561. existing.length + ' "' + String(type) + '" listeners ' +
  562. 'added. Use emitter.setMaxListeners() to ' +
  563. 'increase limit.');
  564. w.name = 'MaxListenersExceededWarning';
  565. w.emitter = target;
  566. w.type = type;
  567. w.count = existing.length;
  568. if (typeof console === 'object' && console.warn) {
  569. console.warn('%s: %s', w.name, w.message);
  570. }
  571. }
  572. }
  573. }
  574. return target;
  575. }
  576. EventEmitter.prototype.addListener = function addListener(type, listener) {
  577. return _addListener(this, type, listener, false);
  578. };
  579. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  580. EventEmitter.prototype.prependListener =
  581. function prependListener(type, listener) {
  582. return _addListener(this, type, listener, true);
  583. };
  584. function onceWrapper() {
  585. if (!this.fired) {
  586. this.target.removeListener(this.type, this.wrapFn);
  587. this.fired = true;
  588. switch (arguments.length) {
  589. case 0:
  590. return this.listener.call(this.target);
  591. case 1:
  592. return this.listener.call(this.target, arguments[0]);
  593. case 2:
  594. return this.listener.call(this.target, arguments[0], arguments[1]);
  595. case 3:
  596. return this.listener.call(this.target, arguments[0], arguments[1],
  597. arguments[2]);
  598. default:
  599. var args = new Array(arguments.length);
  600. for (var i = 0; i < args.length; ++i)
  601. args[i] = arguments[i];
  602. this.listener.apply(this.target, args);
  603. }
  604. }
  605. }
  606. function _onceWrap(target, type, listener) {
  607. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  608. var wrapped = bind.call(onceWrapper, state);
  609. wrapped.listener = listener;
  610. state.wrapFn = wrapped;
  611. return wrapped;
  612. }
  613. EventEmitter.prototype.once = function once(type, listener) {
  614. if (typeof listener !== 'function')
  615. throw new TypeError('"listener" argument must be a function');
  616. this.on(type, _onceWrap(this, type, listener));
  617. return this;
  618. };
  619. EventEmitter.prototype.prependOnceListener =
  620. function prependOnceListener(type, listener) {
  621. if (typeof listener !== 'function')
  622. throw new TypeError('"listener" argument must be a function');
  623. this.prependListener(type, _onceWrap(this, type, listener));
  624. return this;
  625. };
  626. // Emits a 'removeListener' event if and only if the listener was removed.
  627. EventEmitter.prototype.removeListener =
  628. function removeListener(type, listener) {
  629. var list, events, position, i, originalListener;
  630. if (typeof listener !== 'function')
  631. throw new TypeError('"listener" argument must be a function');
  632. events = this._events;
  633. if (!events)
  634. return this;
  635. list = events[type];
  636. if (!list)
  637. return this;
  638. if (list === listener || list.listener === listener) {
  639. if (--this._eventsCount === 0)
  640. this._events = objectCreate(null);
  641. else {
  642. delete events[type];
  643. if (events.removeListener)
  644. this.emit('removeListener', type, list.listener || listener);
  645. }
  646. } else if (typeof list !== 'function') {
  647. position = -1;
  648. for (i = list.length - 1; i >= 0; i--) {
  649. if (list[i] === listener || list[i].listener === listener) {
  650. originalListener = list[i].listener;
  651. position = i;
  652. break;
  653. }
  654. }
  655. if (position < 0)
  656. return this;
  657. if (position === 0)
  658. list.shift();
  659. else
  660. spliceOne(list, position);
  661. if (list.length === 1)
  662. events[type] = list[0];
  663. if (events.removeListener)
  664. this.emit('removeListener', type, originalListener || listener);
  665. }
  666. return this;
  667. };
  668. EventEmitter.prototype.removeAllListeners =
  669. function removeAllListeners(type) {
  670. var listeners, events, i;
  671. events = this._events;
  672. if (!events)
  673. return this;
  674. // not listening for removeListener, no need to emit
  675. if (!events.removeListener) {
  676. if (arguments.length === 0) {
  677. this._events = objectCreate(null);
  678. this._eventsCount = 0;
  679. } else if (events[type]) {
  680. if (--this._eventsCount === 0)
  681. this._events = objectCreate(null);
  682. else
  683. delete events[type];
  684. }
  685. return this;
  686. }
  687. // emit removeListener for all listeners on all events
  688. if (arguments.length === 0) {
  689. var keys = objectKeys(events);
  690. var key;
  691. for (i = 0; i < keys.length; ++i) {
  692. key = keys[i];
  693. if (key === 'removeListener') continue;
  694. this.removeAllListeners(key);
  695. }
  696. this.removeAllListeners('removeListener');
  697. this._events = objectCreate(null);
  698. this._eventsCount = 0;
  699. return this;
  700. }
  701. listeners = events[type];
  702. if (typeof listeners === 'function') {
  703. this.removeListener(type, listeners);
  704. } else if (listeners) {
  705. // LIFO order
  706. for (i = listeners.length - 1; i >= 0; i--) {
  707. this.removeListener(type, listeners[i]);
  708. }
  709. }
  710. return this;
  711. };
  712. function _listeners(target, type, unwrap) {
  713. var events = target._events;
  714. if (!events)
  715. return [];
  716. var evlistener = events[type];
  717. if (!evlistener)
  718. return [];
  719. if (typeof evlistener === 'function')
  720. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  721. return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  722. }
  723. EventEmitter.prototype.listeners = function listeners(type) {
  724. return _listeners(this, type, true);
  725. };
  726. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  727. return _listeners(this, type, false);
  728. };
  729. EventEmitter.listenerCount = function(emitter, type) {
  730. if (typeof emitter.listenerCount === 'function') {
  731. return emitter.listenerCount(type);
  732. } else {
  733. return listenerCount.call(emitter, type);
  734. }
  735. };
  736. EventEmitter.prototype.listenerCount = listenerCount;
  737. function listenerCount(type) {
  738. var events = this._events;
  739. if (events) {
  740. var evlistener = events[type];
  741. if (typeof evlistener === 'function') {
  742. return 1;
  743. } else if (evlistener) {
  744. return evlistener.length;
  745. }
  746. }
  747. return 0;
  748. }
  749. EventEmitter.prototype.eventNames = function eventNames() {
  750. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  751. };
  752. // About 1.5x faster than the two-arg version of Array#splice().
  753. function spliceOne(list, index) {
  754. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  755. list[i] = list[k];
  756. list.pop();
  757. }
  758. function arrayClone(arr, n) {
  759. var copy = new Array(n);
  760. for (var i = 0; i < n; ++i)
  761. copy[i] = arr[i];
  762. return copy;
  763. }
  764. function unwrapListeners(arr) {
  765. var ret = new Array(arr.length);
  766. for (var i = 0; i < ret.length; ++i) {
  767. ret[i] = arr[i].listener || arr[i];
  768. }
  769. return ret;
  770. }
  771. function objectCreatePolyfill(proto) {
  772. var F = function() {};
  773. F.prototype = proto;
  774. return new F;
  775. }
  776. function objectKeysPolyfill(obj) {
  777. var keys = [];
  778. for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
  779. keys.push(k);
  780. }
  781. return k;
  782. }
  783. function functionBindPolyfill(context) {
  784. var fn = this;
  785. return function () {
  786. return fn.apply(context, arguments);
  787. };
  788. }
  789. },{}],16:[function(_dereq_,module,exports){
  790. !function() {
  791. var d3 = {
  792. version: "3.5.17"
  793. };
  794. var d3_arraySlice = [].slice, d3_array = function(list) {
  795. return d3_arraySlice.call(list);
  796. };
  797. var d3_document = this.document;
  798. function d3_documentElement(node) {
  799. return node && (node.ownerDocument || node.document || node).documentElement;
  800. }
  801. function d3_window(node) {
  802. return node && (node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView);
  803. }
  804. if (d3_document) {
  805. try {
  806. d3_array(d3_document.documentElement.childNodes)[0].nodeType;
  807. } catch (e) {
  808. d3_array = function(list) {
  809. var i = list.length, array = new Array(i);
  810. while (i--) array[i] = list[i];
  811. return array;
  812. };
  813. }
  814. }
  815. if (!Date.now) Date.now = function() {
  816. return +new Date();
  817. };
  818. if (d3_document) {
  819. try {
  820. d3_document.createElement("DIV").style.setProperty("opacity", 0, "");
  821. } catch (error) {
  822. var d3_element_prototype = this.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = this.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty;
  823. d3_element_prototype.setAttribute = function(name, value) {
  824. d3_element_setAttribute.call(this, name, value + "");
  825. };
  826. d3_element_prototype.setAttributeNS = function(space, local, value) {
  827. d3_element_setAttributeNS.call(this, space, local, value + "");
  828. };
  829. d3_style_prototype.setProperty = function(name, value, priority) {
  830. d3_style_setProperty.call(this, name, value + "", priority);
  831. };
  832. }
  833. }
  834. d3.ascending = d3_ascending;
  835. function d3_ascending(a, b) {
  836. return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN;
  837. }
  838. d3.descending = function(a, b) {
  839. return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN;
  840. };
  841. d3.min = function(array, f) {
  842. var i = -1, n = array.length, a, b;
  843. if (arguments.length === 1) {
  844. while (++i < n) if ((b = array[i]) != null && b >= b) {
  845. a = b;
  846. break;
  847. }
  848. while (++i < n) if ((b = array[i]) != null && a > b) a = b;
  849. } else {
  850. while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
  851. a = b;
  852. break;
  853. }
  854. while (++i < n) if ((b = f.call(array, array[i], i)) != null && a > b) a = b;
  855. }
  856. return a;
  857. };
  858. d3.max = function(array, f) {
  859. var i = -1, n = array.length, a, b;
  860. if (arguments.length === 1) {
  861. while (++i < n) if ((b = array[i]) != null && b >= b) {
  862. a = b;
  863. break;
  864. }
  865. while (++i < n) if ((b = array[i]) != null && b > a) a = b;
  866. } else {
  867. while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
  868. a = b;
  869. break;
  870. }
  871. while (++i < n) if ((b = f.call(array, array[i], i)) != null && b > a) a = b;
  872. }
  873. return a;
  874. };
  875. d3.extent = function(array, f) {
  876. var i = -1, n = array.length, a, b, c;
  877. if (arguments.length === 1) {
  878. while (++i < n) if ((b = array[i]) != null && b >= b) {
  879. a = c = b;
  880. break;
  881. }
  882. while (++i < n) if ((b = array[i]) != null) {
  883. if (a > b) a = b;
  884. if (c < b) c = b;
  885. }
  886. } else {
  887. while (++i < n) if ((b = f.call(array, array[i], i)) != null && b >= b) {
  888. a = c = b;
  889. break;
  890. }
  891. while (++i < n) if ((b = f.call(array, array[i], i)) != null) {
  892. if (a > b) a = b;
  893. if (c < b) c = b;
  894. }
  895. }
  896. return [ a, c ];
  897. };
  898. function d3_number(x) {
  899. return x === null ? NaN : +x;
  900. }
  901. function d3_numeric(x) {
  902. return !isNaN(x);
  903. }
  904. d3.sum = function(array, f) {
  905. var s = 0, n = array.length, a, i = -1;
  906. if (arguments.length === 1) {
  907. while (++i < n) if (d3_numeric(a = +array[i])) s += a;
  908. } else {
  909. while (++i < n) if (d3_numeric(a = +f.call(array, array[i], i))) s += a;
  910. }
  911. return s;
  912. };
  913. d3.mean = function(array, f) {
  914. var s = 0, n = array.length, a, i = -1, j = n;
  915. if (arguments.length === 1) {
  916. while (++i < n) if (d3_numeric(a = d3_number(array[i]))) s += a; else --j;
  917. } else {
  918. while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) s += a; else --j;
  919. }
  920. if (j) return s / j;
  921. };
  922. d3.quantile = function(values, p) {
  923. var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h;
  924. return e ? v + e * (values[h] - v) : v;
  925. };
  926. d3.median = function(array, f) {
  927. var numbers = [], n = array.length, a, i = -1;
  928. if (arguments.length === 1) {
  929. while (++i < n) if (d3_numeric(a = d3_number(array[i]))) numbers.push(a);
  930. } else {
  931. while (++i < n) if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) numbers.push(a);
  932. }
  933. if (numbers.length) return d3.quantile(numbers.sort(d3_ascending), .5);
  934. };
  935. d3.variance = function(array, f) {
  936. var n = array.length, m = 0, a, d, s = 0, i = -1, j = 0;
  937. if (arguments.length === 1) {
  938. while (++i < n) {
  939. if (d3_numeric(a = d3_number(array[i]))) {
  940. d = a - m;
  941. m += d / ++j;
  942. s += d * (a - m);
  943. }
  944. }
  945. } else {
  946. while (++i < n) {
  947. if (d3_numeric(a = d3_number(f.call(array, array[i], i)))) {
  948. d = a - m;
  949. m += d / ++j;
  950. s += d * (a - m);
  951. }
  952. }
  953. }
  954. if (j > 1) return s / (j - 1);
  955. };
  956. d3.deviation = function() {
  957. var v = d3.variance.apply(this, arguments);
  958. return v ? Math.sqrt(v) : v;
  959. };
  960. function d3_bisector(compare) {
  961. return {
  962. left: function(a, x, lo, hi) {
  963. if (arguments.length < 3) lo = 0;
  964. if (arguments.length < 4) hi = a.length;
  965. while (lo < hi) {
  966. var mid = lo + hi >>> 1;
  967. if (compare(a[mid], x) < 0) lo = mid + 1; else hi = mid;
  968. }
  969. return lo;
  970. },
  971. right: function(a, x, lo, hi) {
  972. if (arguments.length < 3) lo = 0;
  973. if (arguments.length < 4) hi = a.length;
  974. while (lo < hi) {
  975. var mid = lo + hi >>> 1;
  976. if (compare(a[mid], x) > 0) hi = mid; else lo = mid + 1;
  977. }
  978. return lo;
  979. }
  980. };
  981. }
  982. var d3_bisect = d3_bisector(d3_ascending);
  983. d3.bisectLeft = d3_bisect.left;
  984. d3.bisect = d3.bisectRight = d3_bisect.right;
  985. d3.bisector = function(f) {
  986. return d3_bisector(f.length === 1 ? function(d, x) {
  987. return d3_ascending(f(d), x);
  988. } : f);
  989. };
  990. d3.shuffle = function(array, i0, i1) {
  991. if ((m = arguments.length) < 3) {
  992. i1 = array.length;
  993. if (m < 2) i0 = 0;
  994. }
  995. var m = i1 - i0, t, i;
  996. while (m) {
  997. i = Math.random() * m-- | 0;
  998. t = array[m + i0], array[m + i0] = array[i + i0], array[i + i0] = t;
  999. }
  1000. return array;
  1001. };
  1002. d3.permute = function(array, indexes) {
  1003. var i = indexes.length, permutes = new Array(i);
  1004. while (i--) permutes[i] = array[indexes[i]];
  1005. return permutes;
  1006. };
  1007. d3.pairs = function(array) {
  1008. var i = 0, n = array.length - 1, p0, p1 = array[0], pairs = new Array(n < 0 ? 0 : n);
  1009. while (i < n) pairs[i] = [ p0 = p1, p1 = array[++i] ];
  1010. return pairs;
  1011. };
  1012. d3.transpose = function(matrix) {
  1013. if (!(n = matrix.length)) return [];
  1014. for (var i = -1, m = d3.min(matrix, d3_transposeLength), transpose = new Array(m); ++i < m; ) {
  1015. for (var j = -1, n, row = transpose[i] = new Array(n); ++j < n; ) {
  1016. row[j] = matrix[j][i];
  1017. }
  1018. }
  1019. return transpose;
  1020. };
  1021. function d3_transposeLength(d) {
  1022. return d.length;
  1023. }
  1024. d3.zip = function() {
  1025. return d3.transpose(arguments);
  1026. };
  1027. d3.keys = function(map) {
  1028. var keys = [];
  1029. for (var key in map) keys.push(key);
  1030. return keys;
  1031. };
  1032. d3.values = function(map) {
  1033. var values = [];
  1034. for (var key in map) values.push(map[key]);
  1035. return values;
  1036. };
  1037. d3.entries = function(map) {
  1038. var entries = [];
  1039. for (var key in map) entries.push({
  1040. key: key,
  1041. value: map[key]
  1042. });
  1043. return entries;
  1044. };
  1045. d3.merge = function(arrays) {
  1046. var n = arrays.length, m, i = -1, j = 0, merged, array;
  1047. while (++i < n) j += arrays[i].length;
  1048. merged = new Array(j);
  1049. while (--n >= 0) {
  1050. array = arrays[n];
  1051. m = array.length;
  1052. while (--m >= 0) {
  1053. merged[--j] = array[m];
  1054. }
  1055. }
  1056. return merged;
  1057. };
  1058. var abs = Math.abs;
  1059. d3.range = function(start, stop, step) {
  1060. if (arguments.length < 3) {
  1061. step = 1;
  1062. if (arguments.length < 2) {
  1063. stop = start;
  1064. start = 0;
  1065. }
  1066. }
  1067. if ((stop - start) / step === Infinity) throw new Error("infinite range");
  1068. var range = [], k = d3_range_integerScale(abs(step)), i = -1, j;
  1069. start *= k, stop *= k, step *= k;
  1070. if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); else while ((j = start + step * ++i) < stop) range.push(j / k);
  1071. return range;
  1072. };
  1073. function d3_range_integerScale(x) {
  1074. var k = 1;
  1075. while (x * k % 1) k *= 10;
  1076. return k;
  1077. }
  1078. function d3_class(ctor, properties) {
  1079. for (var key in properties) {
  1080. Object.defineProperty(ctor.prototype, key, {
  1081. value: properties[key],
  1082. enumerable: false
  1083. });
  1084. }
  1085. }
  1086. d3.map = function(object, f) {
  1087. var map = new d3_Map();
  1088. if (object instanceof d3_Map) {
  1089. object.forEach(function(key, value) {
  1090. map.set(key, value);
  1091. });
  1092. } else if (Array.isArray(object)) {
  1093. var i = -1, n = object.length, o;
  1094. if (arguments.length === 1) while (++i < n) map.set(i, object[i]); else while (++i < n) map.set(f.call(object, o = object[i], i), o);
  1095. } else {
  1096. for (var key in object) map.set(key, object[key]);
  1097. }
  1098. return map;
  1099. };
  1100. function d3_Map() {
  1101. this._ = Object.create(null);
  1102. }
  1103. var d3_map_proto = "__proto__", d3_map_zero = "\x00";
  1104. d3_class(d3_Map, {
  1105. has: d3_map_has,
  1106. get: function(key) {
  1107. return this._[d3_map_escape(key)];
  1108. },
  1109. set: function(key, value) {
  1110. return this._[d3_map_escape(key)] = value;
  1111. },
  1112. remove: d3_map_remove,
  1113. keys: d3_map_keys,
  1114. values: function() {
  1115. var values = [];
  1116. for (var key in this._) values.push(this._[key]);
  1117. return values;
  1118. },
  1119. entries: function() {
  1120. var entries = [];
  1121. for (var key in this._) entries.push({
  1122. key: d3_map_unescape(key),
  1123. value: this._[key]
  1124. });
  1125. return entries;
  1126. },
  1127. size: d3_map_size,
  1128. empty: d3_map_empty,
  1129. forEach: function(f) {
  1130. for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]);
  1131. }
  1132. });
  1133. function d3_map_escape(key) {
  1134. return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key;
  1135. }
  1136. function d3_map_unescape(key) {
  1137. return (key += "")[0] === d3_map_zero ? key.slice(1) : key;
  1138. }
  1139. function d3_map_has(key) {
  1140. return d3_map_escape(key) in this._;
  1141. }
  1142. function d3_map_remove(key) {
  1143. return (key = d3_map_escape(key)) in this._ && delete this._[key];
  1144. }
  1145. function d3_map_keys() {
  1146. var keys = [];
  1147. for (var key in this._) keys.push(d3_map_unescape(key));
  1148. return keys;
  1149. }
  1150. function d3_map_size() {
  1151. var size = 0;
  1152. for (var key in this._) ++size;
  1153. return size;
  1154. }
  1155. function d3_map_empty() {
  1156. for (var key in this._) return false;
  1157. return true;
  1158. }
  1159. d3.nest = function() {
  1160. var nest = {}, keys = [], sortKeys = [], sortValues, rollup;
  1161. function map(mapType, array, depth) {
  1162. if (depth >= keys.length) return rollup ? rollup.call(nest, array) : sortValues ? array.sort(sortValues) : array;
  1163. var i = -1, n = array.length, key = keys[depth++], keyValue, object, setter, valuesByKey = new d3_Map(), values;
  1164. while (++i < n) {
  1165. if (values = valuesByKey.get(keyValue = key(object = array[i]))) {
  1166. values.push(object);
  1167. } else {
  1168. valuesByKey.set(keyValue, [ object ]);
  1169. }
  1170. }
  1171. if (mapType) {
  1172. object = mapType();
  1173. setter = function(keyValue, values) {
  1174. object.set(keyValue, map(mapType, values, depth));
  1175. };
  1176. } else {
  1177. object = {};
  1178. setter = function(keyValue, values) {
  1179. object[keyValue] = map(mapType, values, depth);
  1180. };
  1181. }
  1182. valuesByKey.forEach(setter);
  1183. return object;
  1184. }
  1185. function entries(map, depth) {
  1186. if (depth >= keys.length) return map;
  1187. var array = [], sortKey = sortKeys[depth++];
  1188. map.forEach(function(key, keyMap) {
  1189. array.push({
  1190. key: key,
  1191. values: entries(keyMap, depth)
  1192. });
  1193. });
  1194. return sortKey ? array.sort(function(a, b) {
  1195. return sortKey(a.key, b.key);
  1196. }) : array;
  1197. }
  1198. nest.map = function(array, mapType) {
  1199. return map(mapType, array, 0);
  1200. };
  1201. nest.entries = function(array) {
  1202. return entries(map(d3.map, array, 0), 0);
  1203. };
  1204. nest.key = function(d) {
  1205. keys.push(d);
  1206. return nest;
  1207. };
  1208. nest.sortKeys = function(order) {
  1209. sortKeys[keys.length - 1] = order;
  1210. return nest;
  1211. };
  1212. nest.sortValues = function(order) {
  1213. sortValues = order;
  1214. return nest;
  1215. };
  1216. nest.rollup = function(f) {
  1217. rollup = f;
  1218. return nest;
  1219. };
  1220. return nest;
  1221. };
  1222. d3.set = function(array) {
  1223. var set = new d3_Set();
  1224. if (array) for (var i = 0, n = array.length; i < n; ++i) set.add(array[i]);
  1225. return set;
  1226. };
  1227. function d3_Set() {
  1228. this._ = Object.create(null);
  1229. }
  1230. d3_class(d3_Set, {
  1231. has: d3_map_has,
  1232. add: function(key) {
  1233. this._[d3_map_escape(key += "")] = true;
  1234. return key;
  1235. },
  1236. remove: d3_map_remove,
  1237. values: d3_map_keys,
  1238. size: d3_map_size,
  1239. empty: d3_map_empty,
  1240. forEach: function(f) {
  1241. for (var key in this._) f.call(this, d3_map_unescape(key));
  1242. }
  1243. });
  1244. d3.behavior = {};
  1245. function d3_identity(d) {
  1246. return d;
  1247. }
  1248. d3.rebind = function(target, source) {
  1249. var i = 1, n = arguments.length, method;
  1250. while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]);
  1251. return target;
  1252. };
  1253. function d3_rebind(target, source, method) {
  1254. return function() {
  1255. var value = method.apply(source, arguments);
  1256. return value === source ? target : value;
  1257. };
  1258. }
  1259. function d3_vendorSymbol(object, name) {
  1260. if (name in object) return name;
  1261. name = name.charAt(0).toUpperCase() + name.slice(1);
  1262. for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) {
  1263. var prefixName = d3_vendorPrefixes[i] + name;
  1264. if (prefixName in object) return prefixName;
  1265. }
  1266. }
  1267. var d3_vendorPrefixes = [ "webkit", "ms", "moz", "Moz", "o", "O" ];
  1268. function d3_noop() {}
  1269. d3.dispatch = function() {
  1270. var dispatch = new d3_dispatch(), i = -1, n = arguments.length;
  1271. while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
  1272. return dispatch;
  1273. };
  1274. function d3_dispatch() {}
  1275. d3_dispatch.prototype.on = function(type, listener) {
  1276. var i = type.indexOf("."), name = "";
  1277. if (i >= 0) {
  1278. name = type.slice(i + 1);
  1279. type = type.slice(0, i);
  1280. }
  1281. if (type) return arguments.length < 2 ? this[type].on(name) : this[type].on(name, listener);
  1282. if (arguments.length === 2) {
  1283. if (listener == null) for (type in this) {
  1284. if (this.hasOwnProperty(type)) this[type].on(name, null);
  1285. }
  1286. return this;
  1287. }
  1288. };
  1289. function d3_dispatch_event(dispatch) {
  1290. var listeners = [], listenerByName = new d3_Map();
  1291. function event() {
  1292. var z = listeners, i = -1, n = z.length, l;
  1293. while (++i < n) if (l = z[i].on) l.apply(this, arguments);
  1294. return dispatch;
  1295. }
  1296. event.on = function(name, listener) {
  1297. var l = listenerByName.get(name), i;
  1298. if (arguments.length < 2) return l && l.on;
  1299. if (l) {
  1300. l.on = null;
  1301. listeners = listeners.slice(0, i = listeners.indexOf(l)).concat(listeners.slice(i + 1));
  1302. listenerByName.remove(name);
  1303. }
  1304. if (listener) listeners.push(listenerByName.set(name, {
  1305. on: listener
  1306. }));
  1307. return dispatch;
  1308. };
  1309. return event;
  1310. }
  1311. d3.event = null;
  1312. function d3_eventPreventDefault() {
  1313. d3.event.preventDefault();
  1314. }
  1315. function d3_eventSource() {
  1316. var e = d3.event, s;
  1317. while (s = e.sourceEvent) e = s;
  1318. return e;
  1319. }
  1320. function d3_eventDispatch(target) {
  1321. var dispatch = new d3_dispatch(), i = 0, n = arguments.length;
  1322. while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch);
  1323. dispatch.of = function(thiz, argumentz) {
  1324. return function(e1) {
  1325. try {
  1326. var e0 = e1.sourceEvent = d3.event;
  1327. e1.target = target;
  1328. d3.event = e1;
  1329. dispatch[e1.type].apply(thiz, argumentz);
  1330. } finally {
  1331. d3.event = e0;
  1332. }
  1333. };
  1334. };
  1335. return dispatch;
  1336. }
  1337. d3.requote = function(s) {
  1338. return s.replace(d3_requote_re, "\\$&");
  1339. };
  1340. var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g;
  1341. var d3_subclass = {}.__proto__ ? function(object, prototype) {
  1342. object.__proto__ = prototype;
  1343. } : function(object, prototype) {
  1344. for (var property in prototype) object[property] = prototype[property];
  1345. };
  1346. function d3_selection(groups) {
  1347. d3_subclass(groups, d3_selectionPrototype);
  1348. return groups;
  1349. }
  1350. var d3_select = function(s, n) {
  1351. return n.querySelector(s);
  1352. }, d3_selectAll = function(s, n) {
  1353. return n.querySelectorAll(s);
  1354. }, d3_selectMatches = function(n, s) {
  1355. var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")];
  1356. d3_selectMatches = function(n, s) {
  1357. return d3_selectMatcher.call(n, s);
  1358. };
  1359. return d3_selectMatches(n, s);
  1360. };
  1361. if (typeof Sizzle === "function") {
  1362. d3_select = function(s, n) {
  1363. return Sizzle(s, n)[0] || null;
  1364. };
  1365. d3_selectAll = Sizzle;
  1366. d3_selectMatches = Sizzle.matchesSelector;
  1367. }
  1368. d3.selection = function() {
  1369. return d3.select(d3_document.documentElement);
  1370. };
  1371. var d3_selectionPrototype = d3.selection.prototype = [];
  1372. d3_selectionPrototype.select = function(selector) {
  1373. var subgroups = [], subgroup, subnode, group, node;
  1374. selector = d3_selection_selector(selector);
  1375. for (var j = -1, m = this.length; ++j < m; ) {
  1376. subgroups.push(subgroup = []);
  1377. subgroup.parentNode = (group = this[j]).parentNode;
  1378. for (var i = -1, n = group.length; ++i < n; ) {
  1379. if (node = group[i]) {
  1380. subgroup.push(subnode = selector.call(node, node.__data__, i, j));
  1381. if (subnode && "__data__" in node) subnode.__data__ = node.__data__;
  1382. } else {
  1383. subgroup.push(null);
  1384. }
  1385. }
  1386. }
  1387. return d3_selection(subgroups);
  1388. };
  1389. function d3_selection_selector(selector) {
  1390. return typeof selector === "function" ? selector : function() {
  1391. return d3_select(selector, this);
  1392. };
  1393. }
  1394. d3_selectionPrototype.selectAll = function(selector) {
  1395. var subgroups = [], subgroup, node;
  1396. selector = d3_selection_selectorAll(selector);
  1397. for (var j = -1, m = this.length; ++j < m; ) {
  1398. for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
  1399. if (node = group[i]) {
  1400. subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j)));
  1401. subgroup.parentNode = node;
  1402. }
  1403. }
  1404. }
  1405. return d3_selection(subgroups);
  1406. };
  1407. function d3_selection_selectorAll(selector) {
  1408. return typeof selector === "function" ? selector : function() {
  1409. return d3_selectAll(selector, this);
  1410. };
  1411. }
  1412. var d3_nsXhtml = "http://www.w3.org/1999/xhtml";
  1413. var d3_nsPrefix = {
  1414. svg: "http://www.w3.org/2000/svg",
  1415. xhtml: d3_nsXhtml,
  1416. xlink: "http://www.w3.org/1999/xlink",
  1417. xml: "http://www.w3.org/XML/1998/namespace",
  1418. xmlns: "http://www.w3.org/2000/xmlns/"
  1419. };
  1420. d3.ns = {
  1421. prefix: d3_nsPrefix,
  1422. qualify: function(name) {
  1423. var i = name.indexOf(":"), prefix = name;
  1424. if (i >= 0 && (prefix = name.slice(0, i)) !== "xmlns") name = name.slice(i + 1);
  1425. return d3_nsPrefix.hasOwnProperty(prefix) ? {
  1426. space: d3_nsPrefix[prefix],
  1427. local: name
  1428. } : name;
  1429. }
  1430. };
  1431. d3_selectionPrototype.attr = function(name, value) {
  1432. if (arguments.length < 2) {
  1433. if (typeof name === "string") {
  1434. var node = this.node();
  1435. name = d3.ns.qualify(name);
  1436. return name.local ? node.getAttributeNS(name.space, name.local) : node.getAttribute(name);
  1437. }
  1438. for (value in name) this.each(d3_selection_attr(value, name[value]));
  1439. return this;
  1440. }
  1441. return this.each(d3_selection_attr(name, value));
  1442. };
  1443. function d3_selection_attr(name, value) {
  1444. name = d3.ns.qualify(name);
  1445. function attrNull() {
  1446. this.removeAttribute(name);
  1447. }
  1448. function attrNullNS() {
  1449. this.removeAttributeNS(name.space, name.local);
  1450. }
  1451. function attrConstant() {
  1452. this.setAttribute(name, value);
  1453. }
  1454. function attrConstantNS() {
  1455. this.setAttributeNS(name.space, name.local, value);
  1456. }
  1457. function attrFunction() {
  1458. var x = value.apply(this, arguments);
  1459. if (x == null) this.removeAttribute(name); else this.setAttribute(name, x);
  1460. }
  1461. function attrFunctionNS() {
  1462. var x = value.apply(this, arguments);
  1463. if (x == null) this.removeAttributeNS(name.space, name.local); else this.setAttributeNS(name.space, name.local, x);
  1464. }
  1465. return value == null ? name.local ? attrNullNS : attrNull : typeof value === "function" ? name.local ? attrFunctionNS : attrFunction : name.local ? attrConstantNS : attrConstant;
  1466. }
  1467. function d3_collapse(s) {
  1468. return s.trim().replace(/\s+/g, " ");
  1469. }
  1470. d3_selectionPrototype.classed = function(name, value) {
  1471. if (arguments.length < 2) {
  1472. if (typeof name === "string") {
  1473. var node = this.node(), n = (name = d3_selection_classes(name)).length, i = -1;
  1474. if (value = node.classList) {
  1475. while (++i < n) if (!value.contains(name[i])) return false;
  1476. } else {
  1477. value = node.getAttribute("class");
  1478. while (++i < n) if (!d3_selection_classedRe(name[i]).test(value)) return false;
  1479. }
  1480. return true;
  1481. }
  1482. for (value in name) this.each(d3_selection_classed(value, name[value]));
  1483. return this;
  1484. }
  1485. return this.each(d3_selection_classed(name, value));
  1486. };
  1487. function d3_selection_classedRe(name) {
  1488. return new RegExp("(?:^|\\s+)" + d3.requote(name) + "(?:\\s+|$)", "g");
  1489. }
  1490. function d3_selection_classes(name) {
  1491. return (name + "").trim().split(/^|\s+/);
  1492. }
  1493. function d3_selection_classed(name, value) {
  1494. name = d3_selection_classes(name).map(d3_selection_classedName);
  1495. var n = name.length;
  1496. function classedConstant() {
  1497. var i = -1;
  1498. while (++i < n) name[i](this, value);
  1499. }
  1500. function classedFunction() {
  1501. var i = -1, x = value.apply(this, arguments);
  1502. while (++i < n) name[i](this, x);
  1503. }
  1504. return typeof value === "function" ? classedFunction : classedConstant;
  1505. }
  1506. function d3_selection_classedName(name) {
  1507. var re = d3_selection_classedRe(name);
  1508. return function(node, value) {
  1509. if (c = node.classList) return value ? c.add(name) : c.remove(name);
  1510. var c = node.getAttribute("class") || "";
  1511. if (value) {
  1512. re.lastIndex = 0;
  1513. if (!re.test(c)) node.setAttribute("class", d3_collapse(c + " " + name));
  1514. } else {
  1515. node.setAttribute("class", d3_collapse(c.replace(re, " ")));
  1516. }
  1517. };
  1518. }
  1519. d3_selectionPrototype.style = function(name, value, priority) {
  1520. var n = arguments.length;
  1521. if (n < 3) {
  1522. if (typeof name !== "string") {
  1523. if (n < 2) value = "";
  1524. for (priority in name) this.each(d3_selection_style(priority, name[priority], value));
  1525. return this;
  1526. }
  1527. if (n < 2) {
  1528. var node = this.node();
  1529. return d3_window(node).getComputedStyle(node, null).getPropertyValue(name);
  1530. }
  1531. priority = "";
  1532. }
  1533. return this.each(d3_selection_style(name, value, priority));
  1534. };
  1535. function d3_selection_style(name, value, priority) {
  1536. function styleNull() {
  1537. this.style.removeProperty(name);
  1538. }
  1539. function styleConstant() {
  1540. this.style.setProperty(name, value, priority);
  1541. }
  1542. function styleFunction() {
  1543. var x = value.apply(this, arguments);
  1544. if (x == null) this.style.removeProperty(name); else this.style.setProperty(name, x, priority);
  1545. }
  1546. return value == null ? styleNull : typeof value === "function" ? styleFunction : styleConstant;
  1547. }
  1548. d3_selectionPrototype.property = function(name, value) {
  1549. if (arguments.length < 2) {
  1550. if (typeof name === "string") return this.node()[name];
  1551. for (value in name) this.each(d3_selection_property(value, name[value]));
  1552. return this;
  1553. }
  1554. return this.each(d3_selection_property(name, value));
  1555. };
  1556. function d3_selection_property(name, value) {
  1557. function propertyNull() {
  1558. delete this[name];
  1559. }
  1560. function propertyConstant() {
  1561. this[name] = value;
  1562. }
  1563. function propertyFunction() {
  1564. var x = value.apply(this, arguments);
  1565. if (x == null) delete this[name]; else this[name] = x;
  1566. }
  1567. return value == null ? propertyNull : typeof value === "function" ? propertyFunction : propertyConstant;
  1568. }
  1569. d3_selectionPrototype.text = function(value) {
  1570. return arguments.length ? this.each(typeof value === "function" ? function() {
  1571. var v = value.apply(this, arguments);
  1572. this.textContent = v == null ? "" : v;
  1573. } : value == null ? function() {
  1574. this.textContent = "";
  1575. } : function() {
  1576. this.textContent = value;
  1577. }) : this.node().textContent;
  1578. };
  1579. d3_selectionPrototype.html = function(value) {
  1580. return arguments.length ? this.each(typeof value === "function" ? function() {
  1581. var v = value.apply(this, arguments);
  1582. this.innerHTML = v == null ? "" : v;
  1583. } : value == null ? function() {
  1584. this.innerHTML = "";
  1585. } : function() {
  1586. this.innerHTML = value;
  1587. }) : this.node().innerHTML;
  1588. };
  1589. d3_selectionPrototype.append = function(name) {
  1590. name = d3_selection_creator(name);
  1591. return this.select(function() {
  1592. return this.appendChild(name.apply(this, arguments));
  1593. });
  1594. };
  1595. function d3_selection_creator(name) {
  1596. function create() {
  1597. var document = this.ownerDocument, namespace = this.namespaceURI;
  1598. return namespace === d3_nsXhtml && document.documentElement.namespaceURI === d3_nsXhtml ? document.createElement(name) : document.createElementNS(namespace, name);
  1599. }
  1600. function createNS() {
  1601. return this.ownerDocument.createElementNS(name.space, name.local);
  1602. }
  1603. return typeof name === "function" ? name : (name = d3.ns.qualify(name)).local ? createNS : create;
  1604. }
  1605. d3_selectionPrototype.insert = function(name, before) {
  1606. name = d3_selection_creator(name);
  1607. before = d3_selection_selector(before);
  1608. return this.select(function() {
  1609. return this.insertBefore(name.apply(this, arguments), before.apply(this, arguments) || null);
  1610. });
  1611. };
  1612. d3_selectionPrototype.remove = function() {
  1613. return this.each(d3_selectionRemove);
  1614. };
  1615. function d3_selectionRemove() {
  1616. var parent = this.parentNode;
  1617. if (parent) parent.removeChild(this);
  1618. }
  1619. d3_selectionPrototype.data = function(value, key) {
  1620. var i = -1, n = this.length, group, node;
  1621. if (!arguments.length) {
  1622. value = new Array(n = (group = this[0]).length);
  1623. while (++i < n) {
  1624. if (node = group[i]) {
  1625. value[i] = node.__data__;
  1626. }
  1627. }
  1628. return value;
  1629. }
  1630. function bind(group, groupData) {
  1631. var i, n = group.length, m = groupData.length, n0 = Math.min(n, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n), node, nodeData;
  1632. if (key) {
  1633. var nodeByKeyValue = new d3_Map(), keyValues = new Array(n), keyValue;
  1634. for (i = -1; ++i < n; ) {
  1635. if (node = group[i]) {
  1636. if (nodeByKeyValue.has(keyValue = key.call(node, node.__data__, i))) {
  1637. exitNodes[i] = node;
  1638. } else {
  1639. nodeByKeyValue.set(keyValue, node);
  1640. }
  1641. keyValues[i] = keyValue;
  1642. }
  1643. }
  1644. for (i = -1; ++i < m; ) {
  1645. if (!(node = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i], i)))) {
  1646. enterNodes[i] = d3_selection_dataNode(nodeData);
  1647. } else if (node !== true) {
  1648. updateNodes[i] = node;
  1649. node.__data__ = nodeData;
  1650. }
  1651. nodeByKeyValue.set(keyValue, true);
  1652. }
  1653. for (i = -1; ++i < n; ) {
  1654. if (i in keyValues && nodeByKeyValue.get(keyValues[i]) !== true) {
  1655. exitNodes[i] = group[i];
  1656. }
  1657. }
  1658. } else {
  1659. for (i = -1; ++i < n0; ) {
  1660. node = group[i];
  1661. nodeData = groupData[i];
  1662. if (node) {
  1663. node.__data__ = nodeData;
  1664. updateNodes[i] = node;
  1665. } else {
  1666. enterNodes[i] = d3_selection_dataNode(nodeData);
  1667. }
  1668. }
  1669. for (;i < m; ++i) {
  1670. enterNodes[i] = d3_selection_dataNode(groupData[i]);
  1671. }
  1672. for (;i < n; ++i) {
  1673. exitNodes[i] = group[i];
  1674. }
  1675. }
  1676. enterNodes.update = updateNodes;
  1677. enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group.parentNode;
  1678. enter.push(enterNodes);
  1679. update.push(updateNodes);
  1680. exit.push(exitNodes);
  1681. }
  1682. var enter = d3_selection_enter([]), update = d3_selection([]), exit = d3_selection([]);
  1683. if (typeof value === "function") {
  1684. while (++i < n) {
  1685. bind(group = this[i], value.call(group, group.parentNode.__data__, i));
  1686. }
  1687. } else {
  1688. while (++i < n) {
  1689. bind(group = this[i], value);
  1690. }
  1691. }
  1692. update.enter = function() {
  1693. return enter;
  1694. };
  1695. update.exit = function() {
  1696. return exit;
  1697. };
  1698. return update;
  1699. };
  1700. function d3_selection_dataNode(data) {
  1701. return {
  1702. __data__: data
  1703. };
  1704. }
  1705. d3_selectionPrototype.datum = function(value) {
  1706. return arguments.length ? this.property("__data__", value) : this.property("__data__");
  1707. };
  1708. d3_selectionPrototype.filter = function(filter) {
  1709. var subgroups = [], subgroup, group, node;
  1710. if (typeof filter !== "function") filter = d3_selection_filter(filter);
  1711. for (var j = 0, m = this.length; j < m; j++) {
  1712. subgroups.push(subgroup = []);
  1713. subgroup.parentNode = (group = this[j]).parentNode;
  1714. for (var i = 0, n = group.length; i < n; i++) {
  1715. if ((node = group[i]) && filter.call(node, node.__data__, i, j)) {
  1716. subgroup.push(node);
  1717. }
  1718. }
  1719. }
  1720. return d3_selection(subgroups);
  1721. };
  1722. function d3_selection_filter(selector) {
  1723. return function() {
  1724. return d3_selectMatches(this, selector);
  1725. };
  1726. }
  1727. d3_selectionPrototype.order = function() {
  1728. for (var j = -1, m = this.length; ++j < m; ) {
  1729. for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) {
  1730. if (node = group[i]) {
  1731. if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next);
  1732. next = node;
  1733. }
  1734. }
  1735. }
  1736. return this;
  1737. };
  1738. d3_selectionPrototype.sort = function(comparator) {
  1739. comparator = d3_selection_sortComparator.apply(this, arguments);
  1740. for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator);
  1741. return this.order();
  1742. };
  1743. function d3_selection_sortComparator(comparator) {
  1744. if (!arguments.length) comparator = d3_ascending;
  1745. return function(a, b) {
  1746. return a && b ? comparator(a.__data__, b.__data__) : !a - !b;
  1747. };
  1748. }
  1749. d3_selectionPrototype.each = function(callback) {
  1750. return d3_selection_each(this, function(node, i, j) {
  1751. callback.call(node, node.__data__, i, j);
  1752. });
  1753. };
  1754. function d3_selection_each(groups, callback) {
  1755. for (var j = 0, m = groups.length; j < m; j++) {
  1756. for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) {
  1757. if (node = group[i]) callback(node, i, j);
  1758. }
  1759. }
  1760. return groups;
  1761. }
  1762. d3_selectionPrototype.call = function(callback) {
  1763. var args = d3_array(arguments);
  1764. callback.apply(args[0] = this, args);
  1765. return this;
  1766. };
  1767. d3_selectionPrototype.empty = function() {
  1768. return !this.node();
  1769. };
  1770. d3_selectionPrototype.node = function() {
  1771. for (var j = 0, m = this.length; j < m; j++) {
  1772. for (var group = this[j], i = 0, n = group.length; i < n; i++) {
  1773. var node = group[i];
  1774. if (node) return node;
  1775. }
  1776. }
  1777. return null;
  1778. };
  1779. d3_selectionPrototype.size = function() {
  1780. var n = 0;
  1781. d3_selection_each(this, function() {
  1782. ++n;
  1783. });
  1784. return n;
  1785. };
  1786. function d3_selection_enter(selection) {
  1787. d3_subclass(selection, d3_selection_enterPrototype);
  1788. return selection;
  1789. }
  1790. var d3_selection_enterPrototype = [];
  1791. d3.selection.enter = d3_selection_enter;
  1792. d3.selection.enter.prototype = d3_selection_enterPrototype;
  1793. d3_selection_enterPrototype.append = d3_selectionPrototype.append;
  1794. d3_selection_enterPrototype.empty = d3_selectionPrototype.empty;
  1795. d3_selection_enterPrototype.node = d3_selectionPrototype.node;
  1796. d3_selection_enterPrototype.call = d3_selectionPrototype.call;
  1797. d3_selection_enterPrototype.size = d3_selectionPrototype.size;
  1798. d3_selection_enterPrototype.select = function(selector) {
  1799. var subgroups = [], subgroup, subnode, upgroup, group, node;
  1800. for (var j = -1, m = this.length; ++j < m; ) {
  1801. upgroup = (group = this[j]).update;
  1802. subgroups.push(subgroup = []);
  1803. subgroup.parentNode = group.parentNode;
  1804. for (var i = -1, n = group.length; ++i < n; ) {
  1805. if (node = group[i]) {
  1806. subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j));
  1807. subnode.__data__ = node.__data__;
  1808. } else {
  1809. subgroup.push(null);
  1810. }
  1811. }
  1812. }
  1813. return d3_selection(subgroups);
  1814. };
  1815. d3_selection_enterPrototype.insert = function(name, before) {
  1816. if (arguments.length < 2) before = d3_selection_enterInsertBefore(this);
  1817. return d3_selectionPrototype.insert.call(this, name, before);
  1818. };
  1819. function d3_selection_enterInsertBefore(enter) {
  1820. var i0, j0;
  1821. return function(d, i, j) {
  1822. var group = enter[j].update, n = group.length, node;
  1823. if (j != j0) j0 = j, i0 = 0;
  1824. if (i >= i0) i0 = i + 1;
  1825. while (!(node = group[i0]) && ++i0 < n) ;
  1826. return node;
  1827. };
  1828. }
  1829. d3.select = function(node) {
  1830. var group;
  1831. if (typeof node === "string") {
  1832. group = [ d3_select(node, d3_document) ];
  1833. group.parentNode = d3_document.documentElement;
  1834. } else {
  1835. group = [ node ];
  1836. group.parentNode = d3_documentElement(node);
  1837. }
  1838. return d3_selection([ group ]);
  1839. };
  1840. d3.selectAll = function(nodes) {
  1841. var group;
  1842. if (typeof nodes === "string") {
  1843. group = d3_array(d3_selectAll(nodes, d3_document));
  1844. group.parentNode = d3_document.documentElement;
  1845. } else {
  1846. group = d3_array(nodes);
  1847. group.parentNode = null;
  1848. }
  1849. return d3_selection([ group ]);
  1850. };
  1851. d3_selectionPrototype.on = function(type, listener, capture) {
  1852. var n = arguments.length;
  1853. if (n < 3) {
  1854. if (typeof type !== "string") {
  1855. if (n < 2) listener = false;
  1856. for (capture in type) this.each(d3_selection_on(capture, type[capture], listener));
  1857. return this;
  1858. }
  1859. if (n < 2) return (n = this.node()["__on" + type]) && n._;
  1860. capture = false;
  1861. }
  1862. return this.each(d3_selection_on(type, listener, capture));
  1863. };
  1864. function d3_selection_on(type, listener, capture) {
  1865. var name = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener;
  1866. if (i > 0) type = type.slice(0, i);
  1867. var filter = d3_selection_onFilters.get(type);
  1868. if (filter) type = filter, wrap = d3_selection_onFilter;
  1869. function onRemove() {
  1870. var l = this[name];
  1871. if (l) {
  1872. this.removeEventListener(type, l, l.$);
  1873. delete this[name];
  1874. }
  1875. }
  1876. function onAdd() {
  1877. var l = wrap(listener, d3_array(arguments));
  1878. onRemove.call(this);
  1879. this.addEventListener(type, this[name] = l, l.$ = capture);
  1880. l._ = listener;
  1881. }
  1882. function removeAll() {
  1883. var re = new RegExp("^__on([^.]+)" + d3.requote(type) + "$"), match;
  1884. for (var name in this) {
  1885. if (match = name.match(re)) {
  1886. var l = this[name];
  1887. this.removeEventListener(match[1], l, l.$);
  1888. delete this[name];
  1889. }
  1890. }
  1891. }
  1892. return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll;
  1893. }
  1894. var d3_selection_onFilters = d3.map({
  1895. mouseenter: "mouseover",
  1896. mouseleave: "mouseout"
  1897. });
  1898. if (d3_document) {
  1899. d3_selection_onFilters.forEach(function(k) {
  1900. if ("on" + k in d3_document) d3_selection_onFilters.remove(k);
  1901. });
  1902. }
  1903. function d3_selection_onListener(listener, argumentz) {
  1904. return function(e) {
  1905. var o = d3.event;
  1906. d3.event = e;
  1907. argumentz[0] = this.__data__;
  1908. try {
  1909. listener.apply(this, argumentz);
  1910. } finally {
  1911. d3.event = o;
  1912. }
  1913. };
  1914. }
  1915. function d3_selection_onFilter(listener, argumentz) {
  1916. var l = d3_selection_onListener(listener, argumentz);
  1917. return function(e) {
  1918. var target = this, related = e.relatedTarget;
  1919. if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) {
  1920. l.call(target, e);
  1921. }
  1922. };
  1923. }
  1924. var d3_event_dragSelect, d3_event_dragId = 0;
  1925. function d3_event_dragSuppress(node) {
  1926. var name = ".dragsuppress-" + ++d3_event_dragId, click = "click" + name, w = d3.select(d3_window(node)).on("touchmove" + name, d3_eventPreventDefault).on("dragstart" + name, d3_eventPreventDefault).on("selectstart" + name, d3_eventPreventDefault);
  1927. if (d3_event_dragSelect == null) {
  1928. d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect");
  1929. }
  1930. if (d3_event_dragSelect) {
  1931. var style = d3_documentElement(node).style, select = style[d3_event_dragSelect];
  1932. style[d3_event_dragSelect] = "none";
  1933. }
  1934. return function(suppressClick) {
  1935. w.on(name, null);
  1936. if (d3_event_dragSelect) style[d3_event_dragSelect] = select;
  1937. if (suppressClick) {
  1938. var off = function() {
  1939. w.on(click, null);
  1940. };
  1941. w.on(click, function() {
  1942. d3_eventPreventDefault();
  1943. off();
  1944. }, true);
  1945. setTimeout(off, 0);
  1946. }
  1947. };
  1948. }
  1949. d3.mouse = function(container) {
  1950. return d3_mousePoint(container, d3_eventSource());
  1951. };
  1952. var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0;
  1953. function d3_mousePoint(container, e) {
  1954. if (e.changedTouches) e = e.changedTouches[0];
  1955. var svg = container.ownerSVGElement || container;
  1956. if (svg.createSVGPoint) {
  1957. var point = svg.createSVGPoint();
  1958. if (d3_mouse_bug44083 < 0) {
  1959. var window = d3_window(container);
  1960. if (window.scrollX || window.scrollY) {
  1961. svg = d3.select("body").append("svg").style({
  1962. position: "absolute",
  1963. top: 0,
  1964. left: 0,
  1965. margin: 0,
  1966. padding: 0,
  1967. border: "none"
  1968. }, "important");
  1969. var ctm = svg[0][0].getScreenCTM();
  1970. d3_mouse_bug44083 = !(ctm.f || ctm.e);
  1971. svg.remove();
  1972. }
  1973. }
  1974. if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; else point.x = e.clientX,
  1975. point.y = e.clientY;
  1976. point = point.matrixTransform(container.getScreenCTM().inverse());
  1977. return [ point.x, point.y ];
  1978. }
  1979. var rect = container.getBoundingClientRect();
  1980. return [ e.clientX - rect.left - container.clientLeft, e.clientY - rect.top - container.clientTop ];
  1981. }
  1982. d3.touch = function(container, touches, identifier) {
  1983. if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches;
  1984. if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) {
  1985. if ((touch = touches[i]).identifier === identifier) {
  1986. return d3_mousePoint(container, touch);
  1987. }
  1988. }
  1989. };
  1990. d3.behavior.drag = function() {
  1991. var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d3.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d3.touch, d3_identity, "touchmove", "touchend");
  1992. function drag() {
  1993. this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart);
  1994. }
  1995. function dragstart(id, position, subject, move, end) {
  1996. return function() {
  1997. var that = this, target = d3.event.target.correspondingElement || d3.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d3.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId);
  1998. if (origin) {
  1999. dragOffset = origin.apply(that, arguments);
  2000. dragOffset = [ dragOffset.x - position0[0], dragOffset.y - position0[1] ];
  2001. } else {
  2002. dragOffset = [ 0, 0 ];
  2003. }
  2004. dispatch({
  2005. type: "dragstart"
  2006. });
  2007. function moved() {
  2008. var position1 = position(parent, dragId), dx, dy;
  2009. if (!position1) return;
  2010. dx = position1[0] - position0[0];
  2011. dy = position1[1] - position0[1];
  2012. dragged |= dx | dy;
  2013. position0 = position1;
  2014. dispatch({
  2015. type: "drag",
  2016. x: position1[0] + dragOffset[0],
  2017. y: position1[1] + dragOffset[1],
  2018. dx: dx,
  2019. dy: dy
  2020. });
  2021. }
  2022. function ended() {
  2023. if (!position(parent, dragId)) return;
  2024. dragSubject.on(move + dragName, null).on(end + dragName, null);
  2025. dragRestore(dragged);
  2026. dispatch({
  2027. type: "dragend"
  2028. });
  2029. }
  2030. };
  2031. }
  2032. drag.origin = function(x) {
  2033. if (!arguments.length) return origin;
  2034. origin = x;
  2035. return drag;
  2036. };
  2037. return d3.rebind(drag, event, "on");
  2038. };
  2039. function d3_behavior_dragTouchId() {
  2040. return d3.event.changedTouches[0].identifier;
  2041. }
  2042. d3.touches = function(container, touches) {
  2043. if (arguments.length < 2) touches = d3_eventSource().touches;
  2044. return touches ? d3_array(touches).map(function(touch) {
  2045. var point = d3_mousePoint(container, touch);
  2046. point.identifier = touch.identifier;
  2047. return point;
  2048. }) : [];
  2049. };
  2050. var ε = 1e-6, ε2 = ε * ε, π = Math.PI, τ = 2 * π, τε = τ - ε, halfπ = π / 2, d3_radians = π / 180, d3_degrees = 180 / π;
  2051. function d3_sgn(x) {
  2052. return x > 0 ? 1 : x < 0 ? -1 : 0;
  2053. }
  2054. function d3_cross2d(a, b, c) {
  2055. return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]);
  2056. }
  2057. function d3_acos(x) {
  2058. return x > 1 ? 0 : x < -1 ? π : Math.acos(x);
  2059. }
  2060. function d3_asin(x) {
  2061. return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x);
  2062. }
  2063. function d3_sinh(x) {
  2064. return ((x = Math.exp(x)) - 1 / x) / 2;
  2065. }
  2066. function d3_cosh(x) {
  2067. return ((x = Math.exp(x)) + 1 / x) / 2;
  2068. }
  2069. function d3_tanh(x) {
  2070. return ((x = Math.exp(2 * x)) - 1) / (x + 1);
  2071. }
  2072. function d3_haversin(x) {
  2073. return (x = Math.sin(x / 2)) * x;
  2074. }
  2075. var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4;
  2076. d3.interpolateZoom = function(p0, p1) {
  2077. var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S;
  2078. if (d2 < ε2) {
  2079. S = Math.log(w1 / w0) / ρ;
  2080. i = function(t) {
  2081. return [ ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S) ];
  2082. };
  2083. } else {
  2084. var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1);
  2085. S = (r1 - r0) / ρ;
  2086. i = function(t) {
  2087. var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0));
  2088. return [ ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0) ];
  2089. };
  2090. }
  2091. i.duration = S * 1e3;
  2092. return i;
  2093. };
  2094. d3.behavior.zoom = function() {
  2095. var view = {
  2096. x: 0,
  2097. y: 0,
  2098. k: 1
  2099. }, translate0, center0, center, size = [ 960, 500 ], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1;
  2100. if (!d3_behavior_zoomWheel) {
  2101. d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() {
  2102. return -d3.event.deltaY * (d3.event.deltaMode ? 120 : 1);
  2103. }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() {
  2104. return d3.event.wheelDelta;
  2105. }, "mousewheel") : (d3_behavior_zoomDelta = function() {
  2106. return -d3.event.detail;
  2107. }, "MozMousePixelScroll");
  2108. }
  2109. function zoom(g) {
  2110. g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted);
  2111. }
  2112. zoom.event = function(g) {
  2113. g.each(function() {
  2114. var dispatch = event.of(this, arguments), view1 = view;
  2115. if (d3_transitionInheritId) {
  2116. d3.select(this).transition().each("start.zoom", function() {
  2117. view = this.__chart__ || {
  2118. x: 0,
  2119. y: 0,
  2120. k: 1
  2121. };
  2122. zoomstarted(dispatch);
  2123. }).tween("zoom:zoom", function() {
  2124. var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d3.interpolateZoom([ (cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k ], [ (cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k ]);
  2125. return function(t) {
  2126. var l = i(t), k = dx / l[2];
  2127. this.__chart__ = view = {
  2128. x: cx - l[0] * k,
  2129. y: cy - l[1] * k,
  2130. k: k
  2131. };
  2132. zoomed(dispatch);
  2133. };
  2134. }).each("interrupt.zoom", function() {
  2135. zoomended(dispatch);
  2136. }).each("end.zoom", function() {
  2137. zoomended(dispatch);
  2138. });
  2139. } else {
  2140. this.__chart__ = view;
  2141. zoomstarted(dispatch);
  2142. zoomed(dispatch);
  2143. zoomended(dispatch);
  2144. }
  2145. });
  2146. };
  2147. zoom.translate = function(_) {
  2148. if (!arguments.length) return [ view.x, view.y ];
  2149. view = {
  2150. x: +_[0],
  2151. y: +_[1],
  2152. k: view.k
  2153. };
  2154. rescale();
  2155. return zoom;
  2156. };
  2157. zoom.scale = function(_) {
  2158. if (!arguments.length) return view.k;
  2159. view = {
  2160. x: view.x,
  2161. y: view.y,
  2162. k: null
  2163. };
  2164. scaleTo(+_);
  2165. rescale();
  2166. return zoom;
  2167. };
  2168. zoom.scaleExtent = function(_) {
  2169. if (!arguments.length) return scaleExtent;
  2170. scaleExtent = _ == null ? d3_behavior_zoomInfinity : [ +_[0], +_[1] ];
  2171. return zoom;
  2172. };
  2173. zoom.center = function(_) {
  2174. if (!arguments.length) return center;
  2175. center = _ && [ +_[0], +_[1] ];
  2176. return zoom;
  2177. };
  2178. zoom.size = function(_) {
  2179. if (!arguments.length) return size;
  2180. size = _ && [ +_[0], +_[1] ];
  2181. return zoom;
  2182. };
  2183. zoom.duration = function(_) {
  2184. if (!arguments.length) return duration;
  2185. duration = +_;
  2186. return zoom;
  2187. };
  2188. zoom.x = function(z) {
  2189. if (!arguments.length) return x1;
  2190. x1 = z;
  2191. x0 = z.copy();
  2192. view = {
  2193. x: 0,
  2194. y: 0,
  2195. k: 1
  2196. };
  2197. return zoom;
  2198. };
  2199. zoom.y = function(z) {
  2200. if (!arguments.length) return y1;
  2201. y1 = z;
  2202. y0 = z.copy();
  2203. view = {
  2204. x: 0,
  2205. y: 0,
  2206. k: 1
  2207. };
  2208. return zoom;
  2209. };
  2210. function location(p) {
  2211. return [ (p[0] - view.x) / view.k, (p[1] - view.y) / view.k ];
  2212. }
  2213. function point(l) {
  2214. return [ l[0] * view.k + view.x, l[1] * view.k + view.y ];
  2215. }
  2216. function scaleTo(s) {
  2217. view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s));
  2218. }
  2219. function translateTo(p, l) {
  2220. l = point(l);
  2221. view.x += p[0] - l[0];
  2222. view.y += p[1] - l[1];
  2223. }
  2224. function zoomTo(that, p, l, k) {
  2225. that.__chart__ = {
  2226. x: view.x,
  2227. y: view.y,
  2228. k: view.k
  2229. };
  2230. scaleTo(Math.pow(2, k));
  2231. translateTo(center0 = p, l);
  2232. that = d3.select(that);
  2233. if (duration > 0) that = that.transition().duration(duration);
  2234. that.call(zoom.event);
  2235. }
  2236. function rescale() {
  2237. if (x1) x1.domain(x0.range().map(function(x) {
  2238. return (x - view.x) / view.k;
  2239. }).map(x0.invert));
  2240. if (y1) y1.domain(y0.range().map(function(y) {
  2241. return (y - view.y) / view.k;
  2242. }).map(y0.invert));
  2243. }
  2244. function zoomstarted(dispatch) {
  2245. if (!zooming++) dispatch({
  2246. type: "zoomstart"
  2247. });
  2248. }
  2249. function zoomed(dispatch) {
  2250. rescale();
  2251. dispatch({
  2252. type: "zoom",
  2253. scale: view.k,
  2254. translate: [ view.x, view.y ]
  2255. });
  2256. }
  2257. function zoomended(dispatch) {
  2258. if (!--zooming) dispatch({
  2259. type: "zoomend"
  2260. }), center0 = null;
  2261. }
  2262. function mousedowned() {
  2263. var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d3.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d3.mouse(that)), dragRestore = d3_event_dragSuppress(that);
  2264. d3_selection_interrupt.call(that);
  2265. zoomstarted(dispatch);
  2266. function moved() {
  2267. dragged = 1;
  2268. translateTo(d3.mouse(that), location0);
  2269. zoomed(dispatch);
  2270. }
  2271. function ended() {
  2272. subject.on(mousemove, null).on(mouseup, null);
  2273. dragRestore(dragged);
  2274. zoomended(dispatch);
  2275. }
  2276. }
  2277. function touchstarted() {
  2278. var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d3.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d3.select(that), dragRestore = d3_event_dragSuppress(that);
  2279. started();
  2280. zoomstarted(dispatch);
  2281. subject.on(mousedown, null).on(touchstart, started);
  2282. function relocate() {
  2283. var touches = d3.touches(that);
  2284. scale0 = view.k;
  2285. touches.forEach(function(t) {
  2286. if (t.identifier in locations0) locations0[t.identifier] = location(t);
  2287. });
  2288. return touches;
  2289. }
  2290. function started() {
  2291. var target = d3.event.target;
  2292. d3.select(target).on(touchmove, moved).on(touchend, ended);
  2293. targets.push(target);
  2294. var changed = d3.event.changedTouches;
  2295. for (var i = 0, n = changed.length; i < n; ++i) {
  2296. locations0[changed[i].identifier] = null;
  2297. }
  2298. var touches = relocate(), now = Date.now();
  2299. if (touches.length === 1) {
  2300. if (now - touchtime < 500) {
  2301. var p = touches[0];
  2302. zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1);
  2303. d3_eventPreventDefault();
  2304. }
  2305. touchtime = now;
  2306. } else if (touches.length > 1) {
  2307. var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1];
  2308. distance0 = dx * dx + dy * dy;
  2309. }
  2310. }
  2311. function moved() {
  2312. var touches = d3.touches(that), p0, l0, p1, l1;
  2313. d3_selection_interrupt.call(that);
  2314. for (var i = 0, n = touches.length; i < n; ++i, l1 = null) {
  2315. p1 = touches[i];
  2316. if (l1 = locations0[p1.identifier]) {
  2317. if (l0) break;
  2318. p0 = p1, l0 = l1;
  2319. }
  2320. }
  2321. if (l1) {
  2322. var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0);
  2323. p0 = [ (p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2 ];
  2324. l0 = [ (l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2 ];
  2325. scaleTo(scale1 * scale0);
  2326. }
  2327. touchtime = null;
  2328. translateTo(p0, l0);
  2329. zoomed(dispatch);
  2330. }
  2331. function ended() {
  2332. if (d3.event.touches.length) {
  2333. var changed = d3.event.changedTouches;
  2334. for (var i = 0, n = changed.length; i < n; ++i) {
  2335. delete locations0[changed[i].identifier];
  2336. }
  2337. for (var identifier in locations0) {
  2338. return void relocate();
  2339. }
  2340. }
  2341. d3.selectAll(targets).on(zoomName, null);
  2342. subject.on(mousedown, mousedowned).on(touchstart, touchstarted);
  2343. dragRestore();
  2344. zoomended(dispatch);
  2345. }
  2346. }
  2347. function mousewheeled() {
  2348. var dispatch = event.of(this, arguments);
  2349. if (mousewheelTimer) clearTimeout(mousewheelTimer); else d3_selection_interrupt.call(this),
  2350. translate0 = location(center0 = center || d3.mouse(this)), zoomstarted(dispatch);
  2351. mousewheelTimer = setTimeout(function() {
  2352. mousewheelTimer = null;
  2353. zoomended(dispatch);
  2354. }, 50);
  2355. d3_eventPreventDefault();
  2356. scaleTo(Math.pow(2, d3_behavior_zoomDelta() * .002) * view.k);
  2357. translateTo(center0, translate0);
  2358. zoomed(dispatch);
  2359. }
  2360. function dblclicked() {
  2361. var p = d3.mouse(this), k = Math.log(view.k) / Math.LN2;
  2362. zoomTo(this, p, location(p), d3.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1);
  2363. }
  2364. return d3.rebind(zoom, event, "on");
  2365. };
  2366. var d3_behavior_zoomInfinity = [ 0, Infinity ], d3_behavior_zoomDelta, d3_behavior_zoomWheel;
  2367. d3.color = d3_color;
  2368. function d3_color() {}
  2369. d3_color.prototype.toString = function() {
  2370. return this.rgb() + "";
  2371. };
  2372. d3.hsl = d3_hsl;
  2373. function d3_hsl(h, s, l) {
  2374. return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l);
  2375. }
  2376. var d3_hslPrototype = d3_hsl.prototype = new d3_color();
  2377. d3_hslPrototype.brighter = function(k) {
  2378. k = Math.pow(.7, arguments.length ? k : 1);
  2379. return new d3_hsl(this.h, this.s, this.l / k);
  2380. };
  2381. d3_hslPrototype.darker = function(k) {
  2382. k = Math.pow(.7, arguments.length ? k : 1);
  2383. return new d3_hsl(this.h, this.s, k * this.l);
  2384. };
  2385. d3_hslPrototype.rgb = function() {
  2386. return d3_hsl_rgb(this.h, this.s, this.l);
  2387. };
  2388. function d3_hsl_rgb(h, s, l) {
  2389. var m1, m2;
  2390. h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h;
  2391. s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s;
  2392. l = l < 0 ? 0 : l > 1 ? 1 : l;
  2393. m2 = l <= .5 ? l * (1 + s) : l + s - l * s;
  2394. m1 = 2 * l - m2;
  2395. function v(h) {
  2396. if (h > 360) h -= 360; else if (h < 0) h += 360;
  2397. if (h < 60) return m1 + (m2 - m1) * h / 60;
  2398. if (h < 180) return m2;
  2399. if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60;
  2400. return m1;
  2401. }
  2402. function vv(h) {
  2403. return Math.round(v(h) * 255);
  2404. }
  2405. return new d3_rgb(vv(h + 120), vv(h), vv(h - 120));
  2406. }
  2407. d3.hcl = d3_hcl;
  2408. function d3_hcl(h, c, l) {
  2409. return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d3.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l);
  2410. }
  2411. var d3_hclPrototype = d3_hcl.prototype = new d3_color();
  2412. d3_hclPrototype.brighter = function(k) {
  2413. return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)));
  2414. };
  2415. d3_hclPrototype.darker = function(k) {
  2416. return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)));
  2417. };
  2418. d3_hclPrototype.rgb = function() {
  2419. return d3_hcl_lab(this.h, this.c, this.l).rgb();
  2420. };
  2421. function d3_hcl_lab(h, c, l) {
  2422. if (isNaN(h)) h = 0;
  2423. if (isNaN(c)) c = 0;
  2424. return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c);
  2425. }
  2426. d3.lab = d3_lab;
  2427. function d3_lab(l, a, b) {
  2428. return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b);
  2429. }
  2430. var d3_lab_K = 18;
  2431. var d3_lab_X = .95047, d3_lab_Y = 1, d3_lab_Z = 1.08883;
  2432. var d3_labPrototype = d3_lab.prototype = new d3_color();
  2433. d3_labPrototype.brighter = function(k) {
  2434. return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
  2435. };
  2436. d3_labPrototype.darker = function(k) {
  2437. return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b);
  2438. };
  2439. d3_labPrototype.rgb = function() {
  2440. return d3_lab_rgb(this.l, this.a, this.b);
  2441. };
  2442. function d3_lab_rgb(l, a, b) {
  2443. var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200;
  2444. x = d3_lab_xyz(x) * d3_lab_X;
  2445. y = d3_lab_xyz(y) * d3_lab_Y;
  2446. z = d3_lab_xyz(z) * d3_lab_Z;
  2447. return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - .4985314 * z), d3_xyz_rgb(-.969266 * x + 1.8760108 * y + .041556 * z), d3_xyz_rgb(.0556434 * x - .2040259 * y + 1.0572252 * z));
  2448. }
  2449. function d3_lab_hcl(l, a, b) {
  2450. return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l);
  2451. }
  2452. function d3_lab_xyz(x) {
  2453. return x > .206893034 ? x * x * x : (x - 4 / 29) / 7.787037;
  2454. }
  2455. function d3_xyz_lab(x) {
  2456. return x > .008856 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29;
  2457. }
  2458. function d3_xyz_rgb(r) {
  2459. return Math.round(255 * (r <= .00304 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - .055));
  2460. }
  2461. d3.rgb = d3_rgb;
  2462. function d3_rgb(r, g, b) {
  2463. return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b);
  2464. }
  2465. function d3_rgbNumber(value) {
  2466. return new d3_rgb(value >> 16, value >> 8 & 255, value & 255);
  2467. }
  2468. function d3_rgbString(value) {
  2469. return d3_rgbNumber(value) + "";
  2470. }
  2471. var d3_rgbPrototype = d3_rgb.prototype = new d3_color();
  2472. d3_rgbPrototype.brighter = function(k) {
  2473. k = Math.pow(.7, arguments.length ? k : 1);
  2474. var r = this.r, g = this.g, b = this.b, i = 30;
  2475. if (!r && !g && !b) return new d3_rgb(i, i, i);
  2476. if (r && r < i) r = i;
  2477. if (g && g < i) g = i;
  2478. if (b && b < i) b = i;
  2479. return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k));
  2480. };
  2481. d3_rgbPrototype.darker = function(k) {
  2482. k = Math.pow(.7, arguments.length ? k : 1);
  2483. return new d3_rgb(k * this.r, k * this.g, k * this.b);
  2484. };
  2485. d3_rgbPrototype.hsl = function() {
  2486. return d3_rgb_hsl(this.r, this.g, this.b);
  2487. };
  2488. d3_rgbPrototype.toString = function() {
  2489. return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b);
  2490. };
  2491. function d3_rgb_hex(v) {
  2492. return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16);
  2493. }
  2494. function d3_rgb_parse(format, rgb, hsl) {
  2495. var r = 0, g = 0, b = 0, m1, m2, color;
  2496. m1 = /([a-z]+)\((.*)\)/.exec(format = format.toLowerCase());
  2497. if (m1) {
  2498. m2 = m1[2].split(",");
  2499. switch (m1[1]) {
  2500. case "hsl":
  2501. {
  2502. return hsl(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100);
  2503. }
  2504. case "rgb":
  2505. {
  2506. return rgb(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2]));
  2507. }
  2508. }
  2509. }
  2510. if (color = d3_rgb_names.get(format)) {
  2511. return rgb(color.r, color.g, color.b);
  2512. }
  2513. if (format != null && format.charAt(0) === "#" && !isNaN(color = parseInt(format.slice(1), 16))) {
  2514. if (format.length === 4) {
  2515. r = (color & 3840) >> 4;
  2516. r = r >> 4 | r;
  2517. g = color & 240;
  2518. g = g >> 4 | g;
  2519. b = color & 15;
  2520. b = b << 4 | b;
  2521. } else if (format.length === 7) {
  2522. r = (color & 16711680) >> 16;
  2523. g = (color & 65280) >> 8;
  2524. b = color & 255;
  2525. }
  2526. }
  2527. return rgb(r, g, b);
  2528. }
  2529. function d3_rgb_hsl(r, g, b) {
  2530. var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2;
  2531. if (d) {
  2532. s = l < .5 ? d / (max + min) : d / (2 - max - min);
  2533. if (r == max) h = (g - b) / d + (g < b ? 6 : 0); else if (g == max) h = (b - r) / d + 2; else h = (r - g) / d + 4;
  2534. h *= 60;
  2535. } else {
  2536. h = NaN;
  2537. s = l > 0 && l < 1 ? 0 : h;
  2538. }
  2539. return new d3_hsl(h, s, l);
  2540. }
  2541. function d3_rgb_lab(r, g, b) {
  2542. r = d3_rgb_xyz(r);
  2543. g = d3_rgb_xyz(g);
  2544. b = d3_rgb_xyz(b);
  2545. var x = d3_xyz_lab((.4124564 * r + .3575761 * g + .1804375 * b) / d3_lab_X), y = d3_xyz_lab((.2126729 * r + .7151522 * g + .072175 * b) / d3_lab_Y), z = d3_xyz_lab((.0193339 * r + .119192 * g + .9503041 * b) / d3_lab_Z);
  2546. return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z));
  2547. }
  2548. function d3_rgb_xyz(r) {
  2549. return (r /= 255) <= .04045 ? r / 12.92 : Math.pow((r + .055) / 1.055, 2.4);
  2550. }
  2551. function d3_rgb_parseNumber(c) {
  2552. var f = parseFloat(c);
  2553. return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f;
  2554. }
  2555. var d3_rgb_names = d3.map({
  2556. aliceblue: 15792383,
  2557. antiquewhite: 16444375,
  2558. aqua: 65535,
  2559. aquamarine: 8388564,
  2560. azure: 15794175,
  2561. beige: 16119260,
  2562. bisque: 16770244,
  2563. black: 0,
  2564. blanchedalmond: 16772045,
  2565. blue: 255,
  2566. blueviolet: 9055202,
  2567. brown: 10824234,
  2568. burlywood: 14596231,
  2569. cadetblue: 6266528,
  2570. chartreuse: 8388352,
  2571. chocolate: 13789470,
  2572. coral: 16744272,
  2573. cornflowerblue: 6591981,
  2574. cornsilk: 16775388,
  2575. crimson: 14423100,
  2576. cyan: 65535,
  2577. darkblue: 139,
  2578. darkcyan: 35723,
  2579. darkgoldenrod: 12092939,
  2580. darkgray: 11119017,
  2581. darkgreen: 25600,
  2582. darkgrey: 11119017,
  2583. darkkhaki: 12433259,
  2584. darkmagenta: 9109643,
  2585. darkolivegreen: 5597999,
  2586. darkorange: 16747520,
  2587. darkorchid: 10040012,
  2588. darkred: 9109504,
  2589. darksalmon: 15308410,
  2590. darkseagreen: 9419919,
  2591. darkslateblue: 4734347,
  2592. darkslategray: 3100495,
  2593. darkslategrey: 3100495,
  2594. darkturquoise: 52945,
  2595. darkviolet: 9699539,
  2596. deeppink: 16716947,
  2597. deepskyblue: 49151,
  2598. dimgray: 6908265,
  2599. dimgrey: 6908265,
  2600. dodgerblue: 2003199,
  2601. firebrick: 11674146,
  2602. floralwhite: 16775920,
  2603. forestgreen: 2263842,
  2604. fuchsia: 16711935,
  2605. gainsboro: 14474460,
  2606. ghostwhite: 16316671,
  2607. gold: 16766720,
  2608. goldenrod: 14329120,
  2609. gray: 8421504,
  2610. green: 32768,
  2611. greenyellow: 11403055,
  2612. grey: 8421504,
  2613. honeydew: 15794160,
  2614. hotpink: 16738740,
  2615. indianred: 13458524,
  2616. indigo: 4915330,
  2617. ivory: 16777200,
  2618. khaki: 15787660,
  2619. lavender: 15132410,
  2620. lavenderblush: 16773365,
  2621. lawngreen: 8190976,
  2622. lemonchiffon: 16775885,
  2623. lightblue: 11393254,
  2624. lightcoral: 15761536,
  2625. lightcyan: 14745599,
  2626. lightgoldenrodyellow: 16448210,
  2627. lightgray: 13882323,
  2628. lightgreen: 9498256,
  2629. lightgrey: 13882323,
  2630. lightpink: 16758465,
  2631. lightsalmon: 16752762,
  2632. lightseagreen: 2142890,
  2633. lightskyblue: 8900346,
  2634. lightslategray: 7833753,
  2635. lightslategrey: 7833753,
  2636. lightsteelblue: 11584734,
  2637. lightyellow: 16777184,
  2638. lime: 65280,
  2639. limegreen: 3329330,
  2640. linen: 16445670,
  2641. magenta: 16711935,
  2642. maroon: 8388608,
  2643. mediumaquamarine: 6737322,
  2644. mediumblue: 205,
  2645. mediumorchid: 12211667,
  2646. mediumpurple: 9662683,
  2647. mediumseagreen: 3978097,
  2648. mediumslateblue: 8087790,
  2649. mediumspringgreen: 64154,
  2650. mediumturquoise: 4772300,
  2651. mediumvioletred: 13047173,
  2652. midnightblue: 1644912,
  2653. mintcream: 16121850,
  2654. mistyrose: 16770273,
  2655. moccasin: 16770229,
  2656. navajowhite: 16768685,
  2657. navy: 128,
  2658. oldlace: 16643558,
  2659. olive: 8421376,
  2660. olivedrab: 7048739,
  2661. orange: 16753920,
  2662. orangered: 16729344,
  2663. orchid: 14315734,
  2664. palegoldenrod: 15657130,
  2665. palegreen: 10025880,
  2666. paleturquoise: 11529966,
  2667. palevioletred: 14381203,
  2668. papayawhip: 16773077,
  2669. peachpuff: 16767673,
  2670. peru: 13468991,
  2671. pink: 16761035,
  2672. plum: 14524637,
  2673. powderblue: 11591910,
  2674. purple: 8388736,
  2675. rebeccapurple: 6697881,
  2676. red: 16711680,
  2677. rosybrown: 12357519,
  2678. royalblue: 4286945,
  2679. saddlebrown: 9127187,
  2680. salmon: 16416882,
  2681. sandybrown: 16032864,
  2682. seagreen: 3050327,
  2683. seashell: 16774638,
  2684. sienna: 10506797,
  2685. silver: 12632256,
  2686. skyblue: 8900331,
  2687. slateblue: 6970061,
  2688. slategray: 7372944,
  2689. slategrey: 7372944,
  2690. snow: 16775930,
  2691. springgreen: 65407,
  2692. steelblue: 4620980,
  2693. tan: 13808780,
  2694. teal: 32896,
  2695. thistle: 14204888,
  2696. tomato: 16737095,
  2697. turquoise: 4251856,
  2698. violet: 15631086,
  2699. wheat: 16113331,
  2700. white: 16777215,
  2701. whitesmoke: 16119285,
  2702. yellow: 16776960,
  2703. yellowgreen: 10145074
  2704. });
  2705. d3_rgb_names.forEach(function(key, value) {
  2706. d3_rgb_names.set(key, d3_rgbNumber(value));
  2707. });
  2708. function d3_functor(v) {
  2709. return typeof v === "function" ? v : function() {
  2710. return v;
  2711. };
  2712. }
  2713. d3.functor = d3_functor;
  2714. d3.xhr = d3_xhrType(d3_identity);
  2715. function d3_xhrType(response) {
  2716. return function(url, mimeType, callback) {
  2717. if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType,
  2718. mimeType = null;
  2719. return d3_xhr(url, mimeType, response, callback);
  2720. };
  2721. }
  2722. function d3_xhr(url, mimeType, response, callback) {
  2723. var xhr = {}, dispatch = d3.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null;
  2724. if (this.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest();
  2725. "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() {
  2726. request.readyState > 3 && respond();
  2727. };
  2728. function respond() {
  2729. var status = request.status, result;
  2730. if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) {
  2731. try {
  2732. result = response.call(xhr, request);
  2733. } catch (e) {
  2734. dispatch.error.call(xhr, e);
  2735. return;
  2736. }
  2737. dispatch.load.call(xhr, result);
  2738. } else {
  2739. dispatch.error.call(xhr, request);
  2740. }
  2741. }
  2742. request.onprogress = function(event) {
  2743. var o = d3.event;
  2744. d3.event = event;
  2745. try {
  2746. dispatch.progress.call(xhr, request);
  2747. } finally {
  2748. d3.event = o;
  2749. }
  2750. };
  2751. xhr.header = function(name, value) {
  2752. name = (name + "").toLowerCase();
  2753. if (arguments.length < 2) return headers[name];
  2754. if (value == null) delete headers[name]; else headers[name] = value + "";
  2755. return xhr;
  2756. };
  2757. xhr.mimeType = function(value) {
  2758. if (!arguments.length) return mimeType;
  2759. mimeType = value == null ? null : value + "";
  2760. return xhr;
  2761. };
  2762. xhr.responseType = function(value) {
  2763. if (!arguments.length) return responseType;
  2764. responseType = value;
  2765. return xhr;
  2766. };
  2767. xhr.response = function(value) {
  2768. response = value;
  2769. return xhr;
  2770. };
  2771. [ "get", "post" ].forEach(function(method) {
  2772. xhr[method] = function() {
  2773. return xhr.send.apply(xhr, [ method ].concat(d3_array(arguments)));
  2774. };
  2775. });
  2776. xhr.send = function(method, data, callback) {
  2777. if (arguments.length === 2 && typeof data === "function") callback = data, data = null;
  2778. request.open(method, url, true);
  2779. if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*";
  2780. if (request.setRequestHeader) for (var name in headers) request.setRequestHeader(name, headers[name]);
  2781. if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType);
  2782. if (responseType != null) request.responseType = responseType;
  2783. if (callback != null) xhr.on("error", callback).on("load", function(request) {
  2784. callback(null, request);
  2785. });
  2786. dispatch.beforesend.call(xhr, request);
  2787. request.send(data == null ? null : data);
  2788. return xhr;
  2789. };
  2790. xhr.abort = function() {
  2791. request.abort();
  2792. return xhr;
  2793. };
  2794. d3.rebind(xhr, dispatch, "on");
  2795. return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback));
  2796. }
  2797. function d3_xhr_fixCallback(callback) {
  2798. return callback.length === 1 ? function(error, request) {
  2799. callback(error == null ? request : null);
  2800. } : callback;
  2801. }
  2802. function d3_xhrHasResponse(request) {
  2803. var type = request.responseType;
  2804. return type && type !== "text" ? request.response : request.responseText;
  2805. }
  2806. d3.dsv = function(delimiter, mimeType) {
  2807. var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0);
  2808. function dsv(url, row, callback) {
  2809. if (arguments.length < 3) callback = row, row = null;
  2810. var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback);
  2811. xhr.row = function(_) {
  2812. return arguments.length ? xhr.response((row = _) == null ? response : typedResponse(_)) : row;
  2813. };
  2814. return xhr;
  2815. }
  2816. function response(request) {
  2817. return dsv.parse(request.responseText);
  2818. }
  2819. function typedResponse(f) {
  2820. return function(request) {
  2821. return dsv.parse(request.responseText, f);
  2822. };
  2823. }
  2824. dsv.parse = function(text, f) {
  2825. var o;
  2826. return dsv.parseRows(text, function(row, i) {
  2827. if (o) return o(row, i - 1);
  2828. var a = new Function("d", "return {" + row.map(function(name, i) {
  2829. return JSON.stringify(name) + ": d[" + i + "]";
  2830. }).join(",") + "}");
  2831. o = f ? function(row, i) {
  2832. return f(a(row), i);
  2833. } : a;
  2834. });
  2835. };
  2836. dsv.parseRows = function(text, f) {
  2837. var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol;
  2838. function token() {
  2839. if (I >= N) return EOF;
  2840. if (eol) return eol = false, EOL;
  2841. var j = I;
  2842. if (text.charCodeAt(j) === 34) {
  2843. var i = j;
  2844. while (i++ < N) {
  2845. if (text.charCodeAt(i) === 34) {
  2846. if (text.charCodeAt(i + 1) !== 34) break;
  2847. ++i;
  2848. }
  2849. }
  2850. I = i + 2;
  2851. var c = text.charCodeAt(i + 1);
  2852. if (c === 13) {
  2853. eol = true;
  2854. if (text.charCodeAt(i + 2) === 10) ++I;
  2855. } else if (c === 10) {
  2856. eol = true;
  2857. }
  2858. return text.slice(j + 1, i).replace(/""/g, '"');
  2859. }
  2860. while (I < N) {
  2861. var c = text.charCodeAt(I++), k = 1;
  2862. if (c === 10) eol = true; else if (c === 13) {
  2863. eol = true;
  2864. if (text.charCodeAt(I) === 10) ++I, ++k;
  2865. } else if (c !== delimiterCode) continue;
  2866. return text.slice(j, I - k);
  2867. }
  2868. return text.slice(j);
  2869. }
  2870. while ((t = token()) !== EOF) {
  2871. var a = [];
  2872. while (t !== EOL && t !== EOF) {
  2873. a.push(t);
  2874. t = token();
  2875. }
  2876. if (f && (a = f(a, n++)) == null) continue;
  2877. rows.push(a);
  2878. }
  2879. return rows;
  2880. };
  2881. dsv.format = function(rows) {
  2882. if (Array.isArray(rows[0])) return dsv.formatRows(rows);
  2883. var fieldSet = new d3_Set(), fields = [];
  2884. rows.forEach(function(row) {
  2885. for (var field in row) {
  2886. if (!fieldSet.has(field)) {
  2887. fields.push(fieldSet.add(field));
  2888. }
  2889. }
  2890. });
  2891. return [ fields.map(formatValue).join(delimiter) ].concat(rows.map(function(row) {
  2892. return fields.map(function(field) {
  2893. return formatValue(row[field]);
  2894. }).join(delimiter);
  2895. })).join("\n");
  2896. };
  2897. dsv.formatRows = function(rows) {
  2898. return rows.map(formatRow).join("\n");
  2899. };
  2900. function formatRow(row) {
  2901. return row.map(formatValue).join(delimiter);
  2902. }
  2903. function formatValue(text) {
  2904. return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text;
  2905. }
  2906. return dsv;
  2907. };
  2908. d3.csv = d3.dsv(",", "text/csv");
  2909. d3.tsv = d3.dsv(" ", "text/tab-separated-values");
  2910. var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) {
  2911. setTimeout(callback, 17);
  2912. };
  2913. d3.timer = function() {
  2914. d3_timer.apply(this, arguments);
  2915. };
  2916. function d3_timer(callback, delay, then) {
  2917. var n = arguments.length;
  2918. if (n < 2) delay = 0;
  2919. if (n < 3) then = Date.now();
  2920. var time = then + delay, timer = {
  2921. c: callback,
  2922. t: time,
  2923. n: null
  2924. };
  2925. if (d3_timer_queueTail) d3_timer_queueTail.n = timer; else d3_timer_queueHead = timer;
  2926. d3_timer_queueTail = timer;
  2927. if (!d3_timer_interval) {
  2928. d3_timer_timeout = clearTimeout(d3_timer_timeout);
  2929. d3_timer_interval = 1;
  2930. d3_timer_frame(d3_timer_step);
  2931. }
  2932. return timer;
  2933. }
  2934. function d3_timer_step() {
  2935. var now = d3_timer_mark(), delay = d3_timer_sweep() - now;
  2936. if (delay > 24) {
  2937. if (isFinite(delay)) {
  2938. clearTimeout(d3_timer_timeout);
  2939. d3_timer_timeout = setTimeout(d3_timer_step, delay);
  2940. }
  2941. d3_timer_interval = 0;
  2942. } else {
  2943. d3_timer_interval = 1;
  2944. d3_timer_frame(d3_timer_step);
  2945. }
  2946. }
  2947. d3.timer.flush = function() {
  2948. d3_timer_mark();
  2949. d3_timer_sweep();
  2950. };
  2951. function d3_timer_mark() {
  2952. var now = Date.now(), timer = d3_timer_queueHead;
  2953. while (timer) {
  2954. if (now >= timer.t && timer.c(now - timer.t)) timer.c = null;
  2955. timer = timer.n;
  2956. }
  2957. return now;
  2958. }
  2959. function d3_timer_sweep() {
  2960. var t0, t1 = d3_timer_queueHead, time = Infinity;
  2961. while (t1) {
  2962. if (t1.c) {
  2963. if (t1.t < time) time = t1.t;
  2964. t1 = (t0 = t1).n;
  2965. } else {
  2966. t1 = t0 ? t0.n = t1.n : d3_timer_queueHead = t1.n;
  2967. }
  2968. }
  2969. d3_timer_queueTail = t0;
  2970. return time;
  2971. }
  2972. function d3_format_precision(x, p) {
  2973. return p - (x ? Math.ceil(Math.log(x) / Math.LN10) : 1);
  2974. }
  2975. d3.round = function(x, n) {
  2976. return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x);
  2977. };
  2978. var d3_formatPrefixes = [ "y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y" ].map(d3_formatPrefix);
  2979. d3.formatPrefix = function(value, precision) {
  2980. var i = 0;
  2981. if (value = +value) {
  2982. if (value < 0) value *= -1;
  2983. if (precision) value = d3.round(value, d3_format_precision(value, precision));
  2984. i = 1 + Math.floor(1e-12 + Math.log(value) / Math.LN10);
  2985. i = Math.max(-24, Math.min(24, Math.floor((i - 1) / 3) * 3));
  2986. }
  2987. return d3_formatPrefixes[8 + i / 3];
  2988. };
  2989. function d3_formatPrefix(d, i) {
  2990. var k = Math.pow(10, abs(8 - i) * 3);
  2991. return {
  2992. scale: i > 8 ? function(d) {
  2993. return d / k;
  2994. } : function(d) {
  2995. return d * k;
  2996. },
  2997. symbol: d
  2998. };
  2999. }
  3000. function d3_locale_numberFormat(locale) {
  3001. var locale_decimal = locale.decimal, locale_thousands = locale.thousands, locale_grouping = locale.grouping, locale_currency = locale.currency, formatGroup = locale_grouping && locale_thousands ? function(value, width) {
  3002. var i = value.length, t = [], j = 0, g = locale_grouping[0], length = 0;
  3003. while (i > 0 && g > 0) {
  3004. if (length + g + 1 > width) g = Math.max(1, width - length);
  3005. t.push(value.substring(i -= g, i + g));
  3006. if ((length += g + 1) > width) break;
  3007. g = locale_grouping[j = (j + 1) % locale_grouping.length];
  3008. }
  3009. return t.reverse().join(locale_thousands);
  3010. } : d3_identity;
  3011. return function(specifier) {
  3012. var match = d3_format_re.exec(specifier), fill = match[1] || " ", align = match[2] || ">", sign = match[3] || "-", symbol = match[4] || "", zfill = match[5], width = +match[6], comma = match[7], precision = match[8], type = match[9], scale = 1, prefix = "", suffix = "", integer = false, exponent = true;
  3013. if (precision) precision = +precision.substring(1);
  3014. if (zfill || fill === "0" && align === "=") {
  3015. zfill = fill = "0";
  3016. align = "=";
  3017. }
  3018. switch (type) {
  3019. case "n":
  3020. comma = true;
  3021. type = "g";
  3022. break;
  3023. case "%":
  3024. scale = 100;
  3025. suffix = "%";
  3026. type = "f";
  3027. break;
  3028. case "p":
  3029. scale = 100;
  3030. suffix = "%";
  3031. type = "r";
  3032. break;
  3033. case "b":
  3034. case "o":
  3035. case "x":
  3036. case "X":
  3037. if (symbol === "#") prefix = "0" + type.toLowerCase();
  3038. case "c":
  3039. exponent = false;
  3040. case "d":
  3041. integer = true;
  3042. precision = 0;
  3043. break;
  3044. case "s":
  3045. scale = -1;
  3046. type = "r";
  3047. break;
  3048. }
  3049. if (symbol === "$") prefix = locale_currency[0], suffix = locale_currency[1];
  3050. if (type == "r" && !precision) type = "g";
  3051. if (precision != null) {
  3052. if (type == "g") precision = Math.max(1, Math.min(21, precision)); else if (type == "e" || type == "f") precision = Math.max(0, Math.min(20, precision));
  3053. }
  3054. type = d3_format_types.get(type) || d3_format_typeDefault;
  3055. var zcomma = zfill && comma;
  3056. return function(value) {
  3057. var fullSuffix = suffix;
  3058. if (integer && value % 1) return "";
  3059. var negative = value < 0 || value === 0 && 1 / value < 0 ? (value = -value, "-") : sign === "-" ? "" : sign;
  3060. if (scale < 0) {
  3061. var unit = d3.formatPrefix(value, precision);
  3062. value = unit.scale(value);
  3063. fullSuffix = unit.symbol + suffix;
  3064. } else {
  3065. value *= scale;
  3066. }
  3067. value = type(value, precision);
  3068. var i = value.lastIndexOf("."), before, after;
  3069. if (i < 0) {
  3070. var j = exponent ? value.lastIndexOf("e") : -1;
  3071. if (j < 0) before = value, after = ""; else before = value.substring(0, j), after = value.substring(j);
  3072. } else {
  3073. before = value.substring(0, i);
  3074. after = locale_decimal + value.substring(i + 1);
  3075. }
  3076. if (!zfill && comma) before = formatGroup(before, Infinity);
  3077. var length = prefix.length + before.length + after.length + (zcomma ? 0 : negative.length), padding = length < width ? new Array(length = width - length + 1).join(fill) : "";
  3078. if (zcomma) before = formatGroup(padding + before, padding.length ? width - after.length : Infinity);
  3079. negative += prefix;
  3080. value = before + after;
  3081. return (align === "<" ? negative + value + padding : align === ">" ? padding + negative + value : align === "^" ? padding.substring(0, length >>= 1) + negative + value + padding.substring(length) : negative + (zcomma ? value : padding + value)) + fullSuffix;
  3082. };
  3083. };
  3084. }
  3085. var d3_format_re = /(?:([^{])?([<>=^]))?([+\- ])?([$#])?(0)?(\d+)?(,)?(\.-?\d+)?([a-z%])?/i;
  3086. var d3_format_types = d3.map({
  3087. b: function(x) {
  3088. return x.toString(2);
  3089. },
  3090. c: function(x) {
  3091. return String.fromCharCode(x);
  3092. },
  3093. o: function(x) {
  3094. return x.toString(8);
  3095. },
  3096. x: function(x) {
  3097. return x.toString(16);
  3098. },
  3099. X: function(x) {
  3100. return x.toString(16).toUpperCase();
  3101. },
  3102. g: function(x, p) {
  3103. return x.toPrecision(p);
  3104. },
  3105. e: function(x, p) {
  3106. return x.toExponential(p);
  3107. },
  3108. f: function(x, p) {
  3109. return x.toFixed(p);
  3110. },
  3111. r: function(x, p) {
  3112. return (x = d3.round(x, d3_format_precision(x, p))).toFixed(Math.max(0, Math.min(20, d3_format_precision(x * (1 + 1e-15), p))));
  3113. }
  3114. });
  3115. function d3_format_typeDefault(x) {
  3116. return x + "";
  3117. }
  3118. var d3_time = d3.time = {}, d3_date = Date;
  3119. function d3_date_utc() {
  3120. this._ = new Date(arguments.length > 1 ? Date.UTC.apply(this, arguments) : arguments[0]);
  3121. }
  3122. d3_date_utc.prototype = {
  3123. getDate: function() {
  3124. return this._.getUTCDate();
  3125. },
  3126. getDay: function() {
  3127. return this._.getUTCDay();
  3128. },
  3129. getFullYear: function() {
  3130. return this._.getUTCFullYear();
  3131. },
  3132. getHours: function() {
  3133. return this._.getUTCHours();
  3134. },
  3135. getMilliseconds: function() {
  3136. return this._.getUTCMilliseconds();
  3137. },
  3138. getMinutes: function() {
  3139. return this._.getUTCMinutes();
  3140. },
  3141. getMonth: function() {
  3142. return this._.getUTCMonth();
  3143. },
  3144. getSeconds: function() {
  3145. return this._.getUTCSeconds();
  3146. },
  3147. getTime: function() {
  3148. return this._.getTime();
  3149. },
  3150. getTimezoneOffset: function() {
  3151. return 0;
  3152. },
  3153. valueOf: function() {
  3154. return this._.valueOf();
  3155. },
  3156. setDate: function() {
  3157. d3_time_prototype.setUTCDate.apply(this._, arguments);
  3158. },
  3159. setDay: function() {
  3160. d3_time_prototype.setUTCDay.apply(this._, arguments);
  3161. },
  3162. setFullYear: function() {
  3163. d3_time_prototype.setUTCFullYear.apply(this._, arguments);
  3164. },
  3165. setHours: function() {
  3166. d3_time_prototype.setUTCHours.apply(this._, arguments);
  3167. },
  3168. setMilliseconds: function() {
  3169. d3_time_prototype.setUTCMilliseconds.apply(this._, arguments);
  3170. },
  3171. setMinutes: function() {
  3172. d3_time_prototype.setUTCMinutes.apply(this._, arguments);
  3173. },
  3174. setMonth: function() {
  3175. d3_time_prototype.setUTCMonth.apply(this._, arguments);
  3176. },
  3177. setSeconds: function() {
  3178. d3_time_prototype.setUTCSeconds.apply(this._, arguments);
  3179. },
  3180. setTime: function() {
  3181. d3_time_prototype.setTime.apply(this._, arguments);
  3182. }
  3183. };
  3184. var d3_time_prototype = Date.prototype;
  3185. function d3_time_interval(local, step, number) {
  3186. function round(date) {
  3187. var d0 = local(date), d1 = offset(d0, 1);
  3188. return date - d0 < d1 - date ? d0 : d1;
  3189. }
  3190. function ceil(date) {
  3191. step(date = local(new d3_date(date - 1)), 1);
  3192. return date;
  3193. }
  3194. function offset(date, k) {
  3195. step(date = new d3_date(+date), k);
  3196. return date;
  3197. }
  3198. function range(t0, t1, dt) {
  3199. var time = ceil(t0), times = [];
  3200. if (dt > 1) {
  3201. while (time < t1) {
  3202. if (!(number(time) % dt)) times.push(new Date(+time));
  3203. step(time, 1);
  3204. }
  3205. } else {
  3206. while (time < t1) times.push(new Date(+time)), step(time, 1);
  3207. }
  3208. return times;
  3209. }
  3210. function range_utc(t0, t1, dt) {
  3211. try {
  3212. d3_date = d3_date_utc;
  3213. var utc = new d3_date_utc();
  3214. utc._ = t0;
  3215. return range(utc, t1, dt);
  3216. } finally {
  3217. d3_date = Date;
  3218. }
  3219. }
  3220. local.floor = local;
  3221. local.round = round;
  3222. local.ceil = ceil;
  3223. local.offset = offset;
  3224. local.range = range;
  3225. var utc = local.utc = d3_time_interval_utc(local);
  3226. utc.floor = utc;
  3227. utc.round = d3_time_interval_utc(round);
  3228. utc.ceil = d3_time_interval_utc(ceil);
  3229. utc.offset = d3_time_interval_utc(offset);
  3230. utc.range = range_utc;
  3231. return local;
  3232. }
  3233. function d3_time_interval_utc(method) {
  3234. return function(date, k) {
  3235. try {
  3236. d3_date = d3_date_utc;
  3237. var utc = new d3_date_utc();
  3238. utc._ = date;
  3239. return method(utc, k)._;
  3240. } finally {
  3241. d3_date = Date;
  3242. }
  3243. };
  3244. }
  3245. d3_time.year = d3_time_interval(function(date) {
  3246. date = d3_time.day(date);
  3247. date.setMonth(0, 1);
  3248. return date;
  3249. }, function(date, offset) {
  3250. date.setFullYear(date.getFullYear() + offset);
  3251. }, function(date) {
  3252. return date.getFullYear();
  3253. });
  3254. d3_time.years = d3_time.year.range;
  3255. d3_time.years.utc = d3_time.year.utc.range;
  3256. d3_time.day = d3_time_interval(function(date) {
  3257. var day = new d3_date(2e3, 0);
  3258. day.setFullYear(date.getFullYear(), date.getMonth(), date.getDate());
  3259. return day;
  3260. }, function(date, offset) {
  3261. date.setDate(date.getDate() + offset);
  3262. }, function(date) {
  3263. return date.getDate() - 1;
  3264. });
  3265. d3_time.days = d3_time.day.range;
  3266. d3_time.days.utc = d3_time.day.utc.range;
  3267. d3_time.dayOfYear = function(date) {
  3268. var year = d3_time.year(date);
  3269. return Math.floor((date - year - (date.getTimezoneOffset() - year.getTimezoneOffset()) * 6e4) / 864e5);
  3270. };
  3271. [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ].forEach(function(day, i) {
  3272. i = 7 - i;
  3273. var interval = d3_time[day] = d3_time_interval(function(date) {
  3274. (date = d3_time.day(date)).setDate(date.getDate() - (date.getDay() + i) % 7);
  3275. return date;
  3276. }, function(date, offset) {
  3277. date.setDate(date.getDate() + Math.floor(offset) * 7);
  3278. }, function(date) {
  3279. var day = d3_time.year(date).getDay();
  3280. return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7) - (day !== i);
  3281. });
  3282. d3_time[day + "s"] = interval.range;
  3283. d3_time[day + "s"].utc = interval.utc.range;
  3284. d3_time[day + "OfYear"] = function(date) {
  3285. var day = d3_time.year(date).getDay();
  3286. return Math.floor((d3_time.dayOfYear(date) + (day + i) % 7) / 7);
  3287. };
  3288. });
  3289. d3_time.week = d3_time.sunday;
  3290. d3_time.weeks = d3_time.sunday.range;
  3291. d3_time.weeks.utc = d3_time.sunday.utc.range;
  3292. d3_time.weekOfYear = d3_time.sundayOfYear;
  3293. function d3_locale_timeFormat(locale) {
  3294. var locale_dateTime = locale.dateTime, locale_date = locale.date, locale_time = locale.time, locale_periods = locale.periods, locale_days = locale.days, locale_shortDays = locale.shortDays, locale_months = locale.months, locale_shortMonths = locale.shortMonths;
  3295. function d3_time_format(template) {
  3296. var n = template.length;
  3297. function format(date) {
  3298. var string = [], i = -1, j = 0, c, p, f;
  3299. while (++i < n) {
  3300. if (template.charCodeAt(i) === 37) {
  3301. string.push(template.slice(j, i));
  3302. if ((p = d3_time_formatPads[c = template.charAt(++i)]) != null) c = template.charAt(++i);
  3303. if (f = d3_time_formats[c]) c = f(date, p == null ? c === "e" ? " " : "0" : p);
  3304. string.push(c);
  3305. j = i + 1;
  3306. }
  3307. }
  3308. string.push(template.slice(j, i));
  3309. return string.join("");
  3310. }
  3311. format.parse = function(string) {
  3312. var d = {
  3313. y: 1900,
  3314. m: 0,
  3315. d: 1,
  3316. H: 0,
  3317. M: 0,
  3318. S: 0,
  3319. L: 0,
  3320. Z: null
  3321. }, i = d3_time_parse(d, template, string, 0);
  3322. if (i != string.length) return null;
  3323. if ("p" in d) d.H = d.H % 12 + d.p * 12;
  3324. var localZ = d.Z != null && d3_date !== d3_date_utc, date = new (localZ ? d3_date_utc : d3_date)();
  3325. if ("j" in d) date.setFullYear(d.y, 0, d.j); else if ("W" in d || "U" in d) {
  3326. if (!("w" in d)) d.w = "W" in d ? 1 : 0;
  3327. date.setFullYear(d.y, 0, 1);
  3328. date.setFullYear(d.y, 0, "W" in d ? (d.w + 6) % 7 + d.W * 7 - (date.getDay() + 5) % 7 : d.w + d.U * 7 - (date.getDay() + 6) % 7);
  3329. } else date.setFullYear(d.y, d.m, d.d);
  3330. date.setHours(d.H + (d.Z / 100 | 0), d.M + d.Z % 100, d.S, d.L);
  3331. return localZ ? date._ : date;
  3332. };
  3333. format.toString = function() {
  3334. return template;
  3335. };
  3336. return format;
  3337. }
  3338. function d3_time_parse(date, template, string, j) {
  3339. var c, p, t, i = 0, n = template.length, m = string.length;
  3340. while (i < n) {
  3341. if (j >= m) return -1;
  3342. c = template.charCodeAt(i++);
  3343. if (c === 37) {
  3344. t = template.charAt(i++);
  3345. p = d3_time_parsers[t in d3_time_formatPads ? template.charAt(i++) : t];
  3346. if (!p || (j = p(date, string, j)) < 0) return -1;
  3347. } else if (c != string.charCodeAt(j++)) {
  3348. return -1;
  3349. }
  3350. }
  3351. return j;
  3352. }
  3353. d3_time_format.utc = function(template) {
  3354. var local = d3_time_format(template);
  3355. function format(date) {
  3356. try {
  3357. d3_date = d3_date_utc;
  3358. var utc = new d3_date();
  3359. utc._ = date;
  3360. return local(utc);
  3361. } finally {
  3362. d3_date = Date;
  3363. }
  3364. }
  3365. format.parse = function(string) {
  3366. try {
  3367. d3_date = d3_date_utc;
  3368. var date = local.parse(string);
  3369. return date && date._;
  3370. } finally {
  3371. d3_date = Date;
  3372. }
  3373. };
  3374. format.toString = local.toString;
  3375. return format;
  3376. };
  3377. d3_time_format.multi = d3_time_format.utc.multi = d3_time_formatMulti;
  3378. var d3_time_periodLookup = d3.map(), d3_time_dayRe = d3_time_formatRe(locale_days), d3_time_dayLookup = d3_time_formatLookup(locale_days), d3_time_dayAbbrevRe = d3_time_formatRe(locale_shortDays), d3_time_dayAbbrevLookup = d3_time_formatLookup(locale_shortDays), d3_time_monthRe = d3_time_formatRe(locale_months), d3_time_monthLookup = d3_time_formatLookup(locale_months), d3_time_monthAbbrevRe = d3_time_formatRe(locale_shortMonths), d3_time_monthAbbrevLookup = d3_time_formatLookup(locale_shortMonths);
  3379. locale_periods.forEach(function(p, i) {
  3380. d3_time_periodLookup.set(p.toLowerCase(), i);
  3381. });
  3382. var d3_time_formats = {
  3383. a: function(d) {
  3384. return locale_shortDays[d.getDay()];
  3385. },
  3386. A: function(d) {
  3387. return locale_days[d.getDay()];
  3388. },
  3389. b: function(d) {
  3390. return locale_shortMonths[d.getMonth()];
  3391. },
  3392. B: function(d) {
  3393. return locale_months[d.getMonth()];
  3394. },
  3395. c: d3_time_format(locale_dateTime),
  3396. d: function(d, p) {
  3397. return d3_time_formatPad(d.getDate(), p, 2);
  3398. },
  3399. e: function(d, p) {
  3400. return d3_time_formatPad(d.getDate(), p, 2);
  3401. },
  3402. H: function(d, p) {
  3403. return d3_time_formatPad(d.getHours(), p, 2);
  3404. },
  3405. I: function(d, p) {
  3406. return d3_time_formatPad(d.getHours() % 12 || 12, p, 2);
  3407. },
  3408. j: function(d, p) {
  3409. return d3_time_formatPad(1 + d3_time.dayOfYear(d), p, 3);
  3410. },
  3411. L: function(d, p) {
  3412. return d3_time_formatPad(d.getMilliseconds(), p, 3);
  3413. },
  3414. m: function(d, p) {
  3415. return d3_time_formatPad(d.getMonth() + 1, p, 2);
  3416. },
  3417. M: function(d, p) {
  3418. return d3_time_formatPad(d.getMinutes(), p, 2);
  3419. },
  3420. p: function(d) {
  3421. return locale_periods[+(d.getHours() >= 12)];
  3422. },
  3423. S: function(d, p) {
  3424. return d3_time_formatPad(d.getSeconds(), p, 2);
  3425. },
  3426. U: function(d, p) {
  3427. return d3_time_formatPad(d3_time.sundayOfYear(d), p, 2);
  3428. },
  3429. w: function(d) {
  3430. return d.getDay();
  3431. },
  3432. W: function(d, p) {
  3433. return d3_time_formatPad(d3_time.mondayOfYear(d), p, 2);
  3434. },
  3435. x: d3_time_format(locale_date),
  3436. X: d3_time_format(locale_time),
  3437. y: function(d, p) {
  3438. return d3_time_formatPad(d.getFullYear() % 100, p, 2);
  3439. },
  3440. Y: function(d, p) {
  3441. return d3_time_formatPad(d.getFullYear() % 1e4, p, 4);
  3442. },
  3443. Z: d3_time_zone,
  3444. "%": function() {
  3445. return "%";
  3446. }
  3447. };
  3448. var d3_time_parsers = {
  3449. a: d3_time_parseWeekdayAbbrev,
  3450. A: d3_time_parseWeekday,
  3451. b: d3_time_parseMonthAbbrev,
  3452. B: d3_time_parseMonth,
  3453. c: d3_time_parseLocaleFull,
  3454. d: d3_time_parseDay,
  3455. e: d3_time_parseDay,
  3456. H: d3_time_parseHour24,
  3457. I: d3_time_parseHour24,
  3458. j: d3_time_parseDayOfYear,
  3459. L: d3_time_parseMilliseconds,
  3460. m: d3_time_parseMonthNumber,
  3461. M: d3_time_parseMinutes,
  3462. p: d3_time_parseAmPm,
  3463. S: d3_time_parseSeconds,
  3464. U: d3_time_parseWeekNumberSunday,
  3465. w: d3_time_parseWeekdayNumber,
  3466. W: d3_time_parseWeekNumberMonday,
  3467. x: d3_time_parseLocaleDate,
  3468. X: d3_time_parseLocaleTime,
  3469. y: d3_time_parseYear,
  3470. Y: d3_time_parseFullYear,
  3471. Z: d3_time_parseZone,
  3472. "%": d3_time_parseLiteralPercent
  3473. };
  3474. function d3_time_parseWeekdayAbbrev(date, string, i) {
  3475. d3_time_dayAbbrevRe.lastIndex = 0;
  3476. var n = d3_time_dayAbbrevRe.exec(string.slice(i));
  3477. return n ? (date.w = d3_time_dayAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  3478. }
  3479. function d3_time_parseWeekday(date, string, i) {
  3480. d3_time_dayRe.lastIndex = 0;
  3481. var n = d3_time_dayRe.exec(string.slice(i));
  3482. return n ? (date.w = d3_time_dayLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  3483. }
  3484. function d3_time_parseMonthAbbrev(date, string, i) {
  3485. d3_time_monthAbbrevRe.lastIndex = 0;
  3486. var n = d3_time_monthAbbrevRe.exec(string.slice(i));
  3487. return n ? (date.m = d3_time_monthAbbrevLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  3488. }
  3489. function d3_time_parseMonth(date, string, i) {
  3490. d3_time_monthRe.lastIndex = 0;
  3491. var n = d3_time_monthRe.exec(string.slice(i));
  3492. return n ? (date.m = d3_time_monthLookup.get(n[0].toLowerCase()), i + n[0].length) : -1;
  3493. }
  3494. function d3_time_parseLocaleFull(date, string, i) {
  3495. return d3_time_parse(date, d3_time_formats.c.toString(), string, i);
  3496. }
  3497. function d3_time_parseLocaleDate(date, string, i) {
  3498. return d3_time_parse(date, d3_time_formats.x.toString(), string, i);
  3499. }
  3500. function d3_time_parseLocaleTime(date, string, i) {
  3501. return d3_time_parse(date, d3_time_formats.X.toString(), string, i);
  3502. }
  3503. function d3_time_parseAmPm(date, string, i) {
  3504. var n = d3_time_periodLookup.get(string.slice(i, i += 2).toLowerCase());
  3505. return n == null ? -1 : (date.p = n, i);
  3506. }
  3507. return d3_time_format;
  3508. }
  3509. var d3_time_formatPads = {
  3510. "-": "",
  3511. _: " ",
  3512. "0": "0"
  3513. }, d3_time_numberRe = /^\s*\d+/, d3_time_percentRe = /^%/;
  3514. function d3_time_formatPad(value, fill, width) {
  3515. var sign = value < 0 ? "-" : "", string = (sign ? -value : value) + "", length = string.length;
  3516. return sign + (length < width ? new Array(width - length + 1).join(fill) + string : string);
  3517. }
  3518. function d3_time_formatRe(names) {
  3519. return new RegExp("^(?:" + names.map(d3.requote).join("|") + ")", "i");
  3520. }
  3521. function d3_time_formatLookup(names) {
  3522. var map = new d3_Map(), i = -1, n = names.length;
  3523. while (++i < n) map.set(names[i].toLowerCase(), i);
  3524. return map;
  3525. }
  3526. function d3_time_parseWeekdayNumber(date, string, i) {
  3527. d3_time_numberRe.lastIndex = 0;
  3528. var n = d3_time_numberRe.exec(string.slice(i, i + 1));
  3529. return n ? (date.w = +n[0], i + n[0].length) : -1;
  3530. }
  3531. function d3_time_parseWeekNumberSunday(date, string, i) {
  3532. d3_time_numberRe.lastIndex = 0;
  3533. var n = d3_time_numberRe.exec(string.slice(i));
  3534. return n ? (date.U = +n[0], i + n[0].length) : -1;
  3535. }
  3536. function d3_time_parseWeekNumberMonday(date, string, i) {
  3537. d3_time_numberRe.lastIndex = 0;
  3538. var n = d3_time_numberRe.exec(string.slice(i));
  3539. return n ? (date.W = +n[0], i + n[0].length) : -1;
  3540. }
  3541. function d3_time_parseFullYear(date, string, i) {
  3542. d3_time_numberRe.lastIndex = 0;
  3543. var n = d3_time_numberRe.exec(string.slice(i, i + 4));
  3544. return n ? (date.y = +n[0], i + n[0].length) : -1;
  3545. }
  3546. function d3_time_parseYear(date, string, i) {
  3547. d3_time_numberRe.lastIndex = 0;
  3548. var n = d3_time_numberRe.exec(string.slice(i, i + 2));
  3549. return n ? (date.y = d3_time_expandYear(+n[0]), i + n[0].length) : -1;
  3550. }
  3551. function d3_time_parseZone(date, string, i) {
  3552. return /^[+-]\d{4}$/.test(string = string.slice(i, i + 5)) ? (date.Z = -string,
  3553. i + 5) : -1;
  3554. }
  3555. function d3_time_expandYear(d) {
  3556. return d + (d > 68 ? 1900 : 2e3);
  3557. }
  3558. function d3_time_parseMonthNumber(date, string, i) {
  3559. d3_time_numberRe.lastIndex = 0;
  3560. var n = d3_time_numberRe.exec(string.slice(i, i + 2));
  3561. return n ? (date.m = n[0] - 1, i + n[0].length) : -1;
  3562. }
  3563. function d3_time_parseDay(date, string, i) {
  3564. d3_time_numberRe.lastIndex = 0;
  3565. var n = d3_time_numberRe.exec(string.slice(i, i + 2));
  3566. return n ? (date.d = +n[0], i + n[0].length) : -1;
  3567. }
  3568. function d3_time_parseDayOfYear(date, string, i) {
  3569. d3_time_numberRe.lastIndex = 0;
  3570. var n = d3_time_numberRe.exec(string.slice(i, i + 3));
  3571. return n ? (date.j = +n[0], i + n[0].length) : -1;
  3572. }
  3573. function d3_time_parseHour24(date, string, i) {
  3574. d3_time_numberRe.lastIndex = 0;
  3575. var n = d3_time_numberRe.exec(string.slice(i, i + 2));
  3576. return n ? (date.H = +n[0], i + n[0].length) : -1;
  3577. }
  3578. function d3_time_parseMinutes(date, string, i) {
  3579. d3_time_numberRe.lastIndex = 0;
  3580. var n = d3_time_numberRe.exec(string.slice(i, i + 2));
  3581. return n ? (date.M = +n[0], i + n[0].length) : -1;
  3582. }
  3583. function d3_time_parseSeconds(date, string, i) {
  3584. d3_time_numberRe.lastIndex = 0;
  3585. var n = d3_time_numberRe.exec(string.slice(i, i + 2));
  3586. return n ? (date.S = +n[0], i + n[0].length) : -1;
  3587. }
  3588. function d3_time_parseMilliseconds(date, string, i) {
  3589. d3_time_numberRe.lastIndex = 0;
  3590. var n = d3_time_numberRe.exec(string.slice(i, i + 3));
  3591. return n ? (date.L = +n[0], i + n[0].length) : -1;
  3592. }
  3593. function d3_time_zone(d) {
  3594. var z = d.getTimezoneOffset(), zs = z > 0 ? "-" : "+", zh = abs(z) / 60 | 0, zm = abs(z) % 60;
  3595. return zs + d3_time_formatPad(zh, "0", 2) + d3_time_formatPad(zm, "0", 2);
  3596. }
  3597. function d3_time_parseLiteralPercent(date, string, i) {
  3598. d3_time_percentRe.lastIndex = 0;
  3599. var n = d3_time_percentRe.exec(string.slice(i, i + 1));
  3600. return n ? i + n[0].length : -1;
  3601. }
  3602. function d3_time_formatMulti(formats) {
  3603. var n = formats.length, i = -1;
  3604. while (++i < n) formats[i][0] = this(formats[i][0]);
  3605. return function(date) {
  3606. var i = 0, f = formats[i];
  3607. while (!f[1](date)) f = formats[++i];
  3608. return f[0](date);
  3609. };
  3610. }
  3611. d3.locale = function(locale) {
  3612. return {
  3613. numberFormat: d3_locale_numberFormat(locale),
  3614. timeFormat: d3_locale_timeFormat(locale)
  3615. };
  3616. };
  3617. var d3_locale_enUS = d3.locale({
  3618. decimal: ".",
  3619. thousands: ",",
  3620. grouping: [ 3 ],
  3621. currency: [ "$", "" ],
  3622. dateTime: "%a %b %e %X %Y",
  3623. date: "%m/%d/%Y",
  3624. time: "%H:%M:%S",
  3625. periods: [ "AM", "PM" ],
  3626. days: [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ],
  3627. shortDays: [ "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ],
  3628. months: [ "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ],
  3629. shortMonths: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ]
  3630. });
  3631. d3.format = d3_locale_enUS.numberFormat;
  3632. d3.geo = {};
  3633. function d3_adder() {}
  3634. d3_adder.prototype = {
  3635. s: 0,
  3636. t: 0,
  3637. add: function(y) {
  3638. d3_adderSum(y, this.t, d3_adderTemp);
  3639. d3_adderSum(d3_adderTemp.s, this.s, this);
  3640. if (this.s) this.t += d3_adderTemp.t; else this.s = d3_adderTemp.t;
  3641. },
  3642. reset: function() {
  3643. this.s = this.t = 0;
  3644. },
  3645. valueOf: function() {
  3646. return this.s;
  3647. }
  3648. };
  3649. var d3_adderTemp = new d3_adder();
  3650. function d3_adderSum(a, b, o) {
  3651. var x = o.s = a + b, bv = x - a, av = x - bv;
  3652. o.t = a - av + (b - bv);
  3653. }
  3654. d3.geo.stream = function(object, listener) {
  3655. if (object && d3_geo_streamObjectType.hasOwnProperty(object.type)) {
  3656. d3_geo_streamObjectType[object.type](object, listener);
  3657. } else {
  3658. d3_geo_streamGeometry(object, listener);
  3659. }
  3660. };
  3661. function d3_geo_streamGeometry(geometry, listener) {
  3662. if (geometry && d3_geo_streamGeometryType.hasOwnProperty(geometry.type)) {
  3663. d3_geo_streamGeometryType[geometry.type](geometry, listener);
  3664. }
  3665. }
  3666. var d3_geo_streamObjectType = {
  3667. Feature: function(feature, listener) {
  3668. d3_geo_streamGeometry(feature.geometry, listener);
  3669. },
  3670. FeatureCollection: function(object, listener) {
  3671. var features = object.features, i = -1, n = features.length;
  3672. while (++i < n) d3_geo_streamGeometry(features[i].geometry, listener);
  3673. }
  3674. };
  3675. var d3_geo_streamGeometryType = {
  3676. Sphere: function(object, listener) {
  3677. listener.sphere();
  3678. },
  3679. Point: function(object, listener) {
  3680. object = object.coordinates;
  3681. listener.point(object[0], object[1], object[2]);
  3682. },
  3683. MultiPoint: function(object, listener) {
  3684. var coordinates = object.coordinates, i = -1, n = coordinates.length;
  3685. while (++i < n) object = coordinates[i], listener.point(object[0], object[1], object[2]);
  3686. },
  3687. LineString: function(object, listener) {
  3688. d3_geo_streamLine(object.coordinates, listener, 0);
  3689. },
  3690. MultiLineString: function(object, listener) {
  3691. var coordinates = object.coordinates, i = -1, n = coordinates.length;
  3692. while (++i < n) d3_geo_streamLine(coordinates[i], listener, 0);
  3693. },
  3694. Polygon: function(object, listener) {
  3695. d3_geo_streamPolygon(object.coordinates, listener);
  3696. },
  3697. MultiPolygon: function(object, listener) {
  3698. var coordinates = object.coordinates, i = -1, n = coordinates.length;
  3699. while (++i < n) d3_geo_streamPolygon(coordinates[i], listener);
  3700. },
  3701. GeometryCollection: function(object, listener) {
  3702. var geometries = object.geometries, i = -1, n = geometries.length;
  3703. while (++i < n) d3_geo_streamGeometry(geometries[i], listener);
  3704. }
  3705. };
  3706. function d3_geo_streamLine(coordinates, listener, closed) {
  3707. var i = -1, n = coordinates.length - closed, coordinate;
  3708. listener.lineStart();
  3709. while (++i < n) coordinate = coordinates[i], listener.point(coordinate[0], coordinate[1], coordinate[2]);
  3710. listener.lineEnd();
  3711. }
  3712. function d3_geo_streamPolygon(coordinates, listener) {
  3713. var i = -1, n = coordinates.length;
  3714. listener.polygonStart();
  3715. while (++i < n) d3_geo_streamLine(coordinates[i], listener, 1);
  3716. listener.polygonEnd();
  3717. }
  3718. d3.geo.area = function(object) {
  3719. d3_geo_areaSum = 0;
  3720. d3.geo.stream(object, d3_geo_area);
  3721. return d3_geo_areaSum;
  3722. };
  3723. var d3_geo_areaSum, d3_geo_areaRingSum = new d3_adder();
  3724. var d3_geo_area = {
  3725. sphere: function() {
  3726. d3_geo_areaSum += 4 * π;
  3727. },
  3728. point: d3_noop,
  3729. lineStart: d3_noop,
  3730. lineEnd: d3_noop,
  3731. polygonStart: function() {
  3732. d3_geo_areaRingSum.reset();
  3733. d3_geo_area.lineStart = d3_geo_areaRingStart;
  3734. },
  3735. polygonEnd: function() {
  3736. var area = 2 * d3_geo_areaRingSum;
  3737. d3_geo_areaSum += area < 0 ? 4 * π + area : area;
  3738. d3_geo_area.lineStart = d3_geo_area.lineEnd = d3_geo_area.point = d3_noop;
  3739. }
  3740. };
  3741. function d3_geo_areaRingStart() {
  3742. var λ00, φ00, λ0, cosφ0, sinφ0;
  3743. d3_geo_area.point = function(λ, φ) {
  3744. d3_geo_area.point = nextPoint;
  3745. λ0 = (λ00 = λ) * d3_radians, cosφ0 = Math.cos(φ = (φ00 = φ) * d3_radians / 2 + π / 4),
  3746. sinφ0 = Math.sin(φ);
  3747. };
  3748. function nextPoint(λ, φ) {
  3749. λ *= d3_radians;
  3750. φ = φ * d3_radians / 2 + π / 4;
  3751. var dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, cosφ = Math.cos(φ), sinφ = Math.sin(φ), k = sinφ0 * sinφ, u = cosφ0 * cosφ + k * Math.cos(adλ), v = k * sdλ * Math.sin(adλ);
  3752. d3_geo_areaRingSum.add(Math.atan2(v, u));
  3753. λ0 = λ, cosφ0 = cosφ, sinφ0 = sinφ;
  3754. }
  3755. d3_geo_area.lineEnd = function() {
  3756. nextPoint(λ00, φ00);
  3757. };
  3758. }
  3759. function d3_geo_cartesian(spherical) {
  3760. var λ = spherical[0], φ = spherical[1], cosφ = Math.cos(φ);
  3761. return [ cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ) ];
  3762. }
  3763. function d3_geo_cartesianDot(a, b) {
  3764. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
  3765. }
  3766. function d3_geo_cartesianCross(a, b) {
  3767. return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ];
  3768. }
  3769. function d3_geo_cartesianAdd(a, b) {
  3770. a[0] += b[0];
  3771. a[1] += b[1];
  3772. a[2] += b[2];
  3773. }
  3774. function d3_geo_cartesianScale(vector, k) {
  3775. return [ vector[0] * k, vector[1] * k, vector[2] * k ];
  3776. }
  3777. function d3_geo_cartesianNormalize(d) {
  3778. var l = Math.sqrt(d[0] * d[0] + d[1] * d[1] + d[2] * d[2]);
  3779. d[0] /= l;
  3780. d[1] /= l;
  3781. d[2] /= l;
  3782. }
  3783. function d3_geo_spherical(cartesian) {
  3784. return [ Math.atan2(cartesian[1], cartesian[0]), d3_asin(cartesian[2]) ];
  3785. }
  3786. function d3_geo_sphericalEqual(a, b) {
  3787. return abs(a[0] - b[0]) < ε && abs(a[1] - b[1]) < ε;
  3788. }
  3789. d3.geo.bounds = function() {
  3790. var λ0, φ0, λ1, φ1, λ_, λ__, φ__, p0, dλSum, ranges, range;
  3791. var bound = {
  3792. point: point,
  3793. lineStart: lineStart,
  3794. lineEnd: lineEnd,
  3795. polygonStart: function() {
  3796. bound.point = ringPoint;
  3797. bound.lineStart = ringStart;
  3798. bound.lineEnd = ringEnd;
  3799. dλSum = 0;
  3800. d3_geo_area.polygonStart();
  3801. },
  3802. polygonEnd: function() {
  3803. d3_geo_area.polygonEnd();
  3804. bound.point = point;
  3805. bound.lineStart = lineStart;
  3806. bound.lineEnd = lineEnd;
  3807. if (d3_geo_areaRingSum < 0) λ0 = -(λ1 = 180), φ0 = -(φ1 = 90); else if (dλSum > ε) φ1 = 90; else if (dλSum < -ε) φ0 = -90;
  3808. range[0] = λ0, range[1] = λ1;
  3809. }
  3810. };
  3811. function point(λ, φ) {
  3812. ranges.push(range = [ λ0 = λ, λ1 = λ ]);
  3813. if (φ < φ0) φ0 = φ;
  3814. if (φ > φ1) φ1 = φ;
  3815. }
  3816. function linePoint(λ, φ) {
  3817. var p = d3_geo_cartesian([ λ * d3_radians, φ * d3_radians ]);
  3818. if (p0) {
  3819. var normal = d3_geo_cartesianCross(p0, p), equatorial = [ normal[1], -normal[0], 0 ], inflection = d3_geo_cartesianCross(equatorial, normal);
  3820. d3_geo_cartesianNormalize(inflection);
  3821. inflection = d3_geo_spherical(inflection);
  3822. var dλ = λ - λ_, s = dλ > 0 ? 1 : -1, λi = inflection[0] * d3_degrees * s, antimeridian = abs(dλ) > 180;
  3823. if (antimeridian ^ (s * λ_ < λi && λi < s * λ)) {
  3824. var φi = inflection[1] * d3_degrees;
  3825. if (φi > φ1) φ1 = φi;
  3826. } else if (λi = (λi + 360) % 360 - 180, antimeridian ^ (s * λ_ < λi && λi < s * λ)) {
  3827. var φi = -inflection[1] * d3_degrees;
  3828. if (φi < φ0) φ0 = φi;
  3829. } else {
  3830. if (φ < φ0) φ0 = φ;
  3831. if (φ > φ1) φ1 = φ;
  3832. }
  3833. if (antimeridian) {
  3834. if (λ < λ_) {
  3835. if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ;
  3836. } else {
  3837. if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ;
  3838. }
  3839. } else {
  3840. if (λ1 >= λ0) {
  3841. if (λ < λ0) λ0 = λ;
  3842. if (λ > λ1) λ1 = λ;
  3843. } else {
  3844. if (λ > λ_) {
  3845. if (angle(λ0, λ) > angle(λ0, λ1)) λ1 = λ;
  3846. } else {
  3847. if (angle(λ, λ1) > angle(λ0, λ1)) λ0 = λ;
  3848. }
  3849. }
  3850. }
  3851. } else {
  3852. point(λ, φ);
  3853. }
  3854. p0 = p, λ_ = λ;
  3855. }
  3856. function lineStart() {
  3857. bound.point = linePoint;
  3858. }
  3859. function lineEnd() {
  3860. range[0] = λ0, range[1] = λ1;
  3861. bound.point = point;
  3862. p0 = null;
  3863. }
  3864. function ringPoint(λ, φ) {
  3865. if (p0) {
  3866. var dλ = λ - λ_;
  3867. dλSum += abs(dλ) > 180 ? dλ + (dλ > 0 ? 360 : -360) : dλ;
  3868. } else λ__ = λ, φ__ = φ;
  3869. d3_geo_area.point(λ, φ);
  3870. linePoint(λ, φ);
  3871. }
  3872. function ringStart() {
  3873. d3_geo_area.lineStart();
  3874. }
  3875. function ringEnd() {
  3876. ringPoint(λ__, φ__);
  3877. d3_geo_area.lineEnd();
  3878. if (abs(dλSum) > ε) λ0 = -(λ1 = 180);
  3879. range[0] = λ0, range[1] = λ1;
  3880. p0 = null;
  3881. }
  3882. function angle(λ0, λ1) {
  3883. return (λ1 -= λ0) < 0 ? λ1 + 360 : λ1;
  3884. }
  3885. function compareRanges(a, b) {
  3886. return a[0] - b[0];
  3887. }
  3888. function withinRange(x, range) {
  3889. return range[0] <= range[1] ? range[0] <= x && x <= range[1] : x < range[0] || range[1] < x;
  3890. }
  3891. return function(feature) {
  3892. φ1 = λ1 = -(λ0 = φ0 = Infinity);
  3893. ranges = [];
  3894. d3.geo.stream(feature, bound);
  3895. var n = ranges.length;
  3896. if (n) {
  3897. ranges.sort(compareRanges);
  3898. for (var i = 1, a = ranges[0], b, merged = [ a ]; i < n; ++i) {
  3899. b = ranges[i];
  3900. if (withinRange(b[0], a) || withinRange(b[1], a)) {
  3901. if (angle(a[0], b[1]) > angle(a[0], a[1])) a[1] = b[1];
  3902. if (angle(b[0], a[1]) > angle(a[0], a[1])) a[0] = b[0];
  3903. } else {
  3904. merged.push(a = b);
  3905. }
  3906. }
  3907. var best = -Infinity, dλ;
  3908. for (var n = merged.length - 1, i = 0, a = merged[n], b; i <= n; a = b, ++i) {
  3909. b = merged[i];
  3910. if ((dλ = angle(a[1], b[0])) > best) best = dλ, λ0 = b[0], λ1 = a[1];
  3911. }
  3912. }
  3913. ranges = range = null;
  3914. return λ0 === Infinity || φ0 === Infinity ? [ [ NaN, NaN ], [ NaN, NaN ] ] : [ [ λ0, φ0 ], [ λ1, φ1 ] ];
  3915. };
  3916. }();
  3917. d3.geo.centroid = function(object) {
  3918. d3_geo_centroidW0 = d3_geo_centroidW1 = d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0;
  3919. d3.geo.stream(object, d3_geo_centroid);
  3920. var x = d3_geo_centroidX2, y = d3_geo_centroidY2, z = d3_geo_centroidZ2, m = x * x + y * y + z * z;
  3921. if (m < ε2) {
  3922. x = d3_geo_centroidX1, y = d3_geo_centroidY1, z = d3_geo_centroidZ1;
  3923. if (d3_geo_centroidW1 < ε) x = d3_geo_centroidX0, y = d3_geo_centroidY0, z = d3_geo_centroidZ0;
  3924. m = x * x + y * y + z * z;
  3925. if (m < ε2) return [ NaN, NaN ];
  3926. }
  3927. return [ Math.atan2(y, x) * d3_degrees, d3_asin(z / Math.sqrt(m)) * d3_degrees ];
  3928. };
  3929. var d3_geo_centroidW0, d3_geo_centroidW1, d3_geo_centroidX0, d3_geo_centroidY0, d3_geo_centroidZ0, d3_geo_centroidX1, d3_geo_centroidY1, d3_geo_centroidZ1, d3_geo_centroidX2, d3_geo_centroidY2, d3_geo_centroidZ2;
  3930. var d3_geo_centroid = {
  3931. sphere: d3_noop,
  3932. point: d3_geo_centroidPoint,
  3933. lineStart: d3_geo_centroidLineStart,
  3934. lineEnd: d3_geo_centroidLineEnd,
  3935. polygonStart: function() {
  3936. d3_geo_centroid.lineStart = d3_geo_centroidRingStart;
  3937. },
  3938. polygonEnd: function() {
  3939. d3_geo_centroid.lineStart = d3_geo_centroidLineStart;
  3940. }
  3941. };
  3942. function d3_geo_centroidPoint(λ, φ) {
  3943. λ *= d3_radians;
  3944. var cosφ = Math.cos(φ *= d3_radians);
  3945. d3_geo_centroidPointXYZ(cosφ * Math.cos(λ), cosφ * Math.sin(λ), Math.sin(φ));
  3946. }
  3947. function d3_geo_centroidPointXYZ(x, y, z) {
  3948. ++d3_geo_centroidW0;
  3949. d3_geo_centroidX0 += (x - d3_geo_centroidX0) / d3_geo_centroidW0;
  3950. d3_geo_centroidY0 += (y - d3_geo_centroidY0) / d3_geo_centroidW0;
  3951. d3_geo_centroidZ0 += (z - d3_geo_centroidZ0) / d3_geo_centroidW0;
  3952. }
  3953. function d3_geo_centroidLineStart() {
  3954. var x0, y0, z0;
  3955. d3_geo_centroid.point = function(λ, φ) {
  3956. λ *= d3_radians;
  3957. var cosφ = Math.cos(φ *= d3_radians);
  3958. x0 = cosφ * Math.cos(λ);
  3959. y0 = cosφ * Math.sin(λ);
  3960. z0 = Math.sin(φ);
  3961. d3_geo_centroid.point = nextPoint;
  3962. d3_geo_centroidPointXYZ(x0, y0, z0);
  3963. };
  3964. function nextPoint(λ, φ) {
  3965. λ *= d3_radians;
  3966. var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), w = Math.atan2(Math.sqrt((w = y0 * z - z0 * y) * w + (w = z0 * x - x0 * z) * w + (w = x0 * y - y0 * x) * w), x0 * x + y0 * y + z0 * z);
  3967. d3_geo_centroidW1 += w;
  3968. d3_geo_centroidX1 += w * (x0 + (x0 = x));
  3969. d3_geo_centroidY1 += w * (y0 + (y0 = y));
  3970. d3_geo_centroidZ1 += w * (z0 + (z0 = z));
  3971. d3_geo_centroidPointXYZ(x0, y0, z0);
  3972. }
  3973. }
  3974. function d3_geo_centroidLineEnd() {
  3975. d3_geo_centroid.point = d3_geo_centroidPoint;
  3976. }
  3977. function d3_geo_centroidRingStart() {
  3978. var λ00, φ00, x0, y0, z0;
  3979. d3_geo_centroid.point = function(λ, φ) {
  3980. λ00 = λ, φ00 = φ;
  3981. d3_geo_centroid.point = nextPoint;
  3982. λ *= d3_radians;
  3983. var cosφ = Math.cos(φ *= d3_radians);
  3984. x0 = cosφ * Math.cos(λ);
  3985. y0 = cosφ * Math.sin(λ);
  3986. z0 = Math.sin(φ);
  3987. d3_geo_centroidPointXYZ(x0, y0, z0);
  3988. };
  3989. d3_geo_centroid.lineEnd = function() {
  3990. nextPoint(λ00, φ00);
  3991. d3_geo_centroid.lineEnd = d3_geo_centroidLineEnd;
  3992. d3_geo_centroid.point = d3_geo_centroidPoint;
  3993. };
  3994. function nextPoint(λ, φ) {
  3995. λ *= d3_radians;
  3996. var cosφ = Math.cos(φ *= d3_radians), x = cosφ * Math.cos(λ), y = cosφ * Math.sin(λ), z = Math.sin(φ), cx = y0 * z - z0 * y, cy = z0 * x - x0 * z, cz = x0 * y - y0 * x, m = Math.sqrt(cx * cx + cy * cy + cz * cz), u = x0 * x + y0 * y + z0 * z, v = m && -d3_acos(u) / m, w = Math.atan2(m, u);
  3997. d3_geo_centroidX2 += v * cx;
  3998. d3_geo_centroidY2 += v * cy;
  3999. d3_geo_centroidZ2 += v * cz;
  4000. d3_geo_centroidW1 += w;
  4001. d3_geo_centroidX1 += w * (x0 + (x0 = x));
  4002. d3_geo_centroidY1 += w * (y0 + (y0 = y));
  4003. d3_geo_centroidZ1 += w * (z0 + (z0 = z));
  4004. d3_geo_centroidPointXYZ(x0, y0, z0);
  4005. }
  4006. }
  4007. function d3_geo_compose(a, b) {
  4008. function compose(x, y) {
  4009. return x = a(x, y), b(x[0], x[1]);
  4010. }
  4011. if (a.invert && b.invert) compose.invert = function(x, y) {
  4012. return x = b.invert(x, y), x && a.invert(x[0], x[1]);
  4013. };
  4014. return compose;
  4015. }
  4016. function d3_true() {
  4017. return true;
  4018. }
  4019. function d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener) {
  4020. var subject = [], clip = [];
  4021. segments.forEach(function(segment) {
  4022. if ((n = segment.length - 1) <= 0) return;
  4023. var n, p0 = segment[0], p1 = segment[n];
  4024. if (d3_geo_sphericalEqual(p0, p1)) {
  4025. listener.lineStart();
  4026. for (var i = 0; i < n; ++i) listener.point((p0 = segment[i])[0], p0[1]);
  4027. listener.lineEnd();
  4028. return;
  4029. }
  4030. var a = new d3_geo_clipPolygonIntersection(p0, segment, null, true), b = new d3_geo_clipPolygonIntersection(p0, null, a, false);
  4031. a.o = b;
  4032. subject.push(a);
  4033. clip.push(b);
  4034. a = new d3_geo_clipPolygonIntersection(p1, segment, null, false);
  4035. b = new d3_geo_clipPolygonIntersection(p1, null, a, true);
  4036. a.o = b;
  4037. subject.push(a);
  4038. clip.push(b);
  4039. });
  4040. clip.sort(compare);
  4041. d3_geo_clipPolygonLinkCircular(subject);
  4042. d3_geo_clipPolygonLinkCircular(clip);
  4043. if (!subject.length) return;
  4044. for (var i = 0, entry = clipStartInside, n = clip.length; i < n; ++i) {
  4045. clip[i].e = entry = !entry;
  4046. }
  4047. var start = subject[0], points, point;
  4048. while (1) {
  4049. var current = start, isSubject = true;
  4050. while (current.v) if ((current = current.n) === start) return;
  4051. points = current.z;
  4052. listener.lineStart();
  4053. do {
  4054. current.v = current.o.v = true;
  4055. if (current.e) {
  4056. if (isSubject) {
  4057. for (var i = 0, n = points.length; i < n; ++i) listener.point((point = points[i])[0], point[1]);
  4058. } else {
  4059. interpolate(current.x, current.n.x, 1, listener);
  4060. }
  4061. current = current.n;
  4062. } else {
  4063. if (isSubject) {
  4064. points = current.p.z;
  4065. for (var i = points.length - 1; i >= 0; --i) listener.point((point = points[i])[0], point[1]);
  4066. } else {
  4067. interpolate(current.x, current.p.x, -1, listener);
  4068. }
  4069. current = current.p;
  4070. }
  4071. current = current.o;
  4072. points = current.z;
  4073. isSubject = !isSubject;
  4074. } while (!current.v);
  4075. listener.lineEnd();
  4076. }
  4077. }
  4078. function d3_geo_clipPolygonLinkCircular(array) {
  4079. if (!(n = array.length)) return;
  4080. var n, i = 0, a = array[0], b;
  4081. while (++i < n) {
  4082. a.n = b = array[i];
  4083. b.p = a;
  4084. a = b;
  4085. }
  4086. a.n = b = array[0];
  4087. b.p = a;
  4088. }
  4089. function d3_geo_clipPolygonIntersection(point, points, other, entry) {
  4090. this.x = point;
  4091. this.z = points;
  4092. this.o = other;
  4093. this.e = entry;
  4094. this.v = false;
  4095. this.n = this.p = null;
  4096. }
  4097. function d3_geo_clip(pointVisible, clipLine, interpolate, clipStart) {
  4098. return function(rotate, listener) {
  4099. var line = clipLine(listener), rotatedClipStart = rotate.invert(clipStart[0], clipStart[1]);
  4100. var clip = {
  4101. point: point,
  4102. lineStart: lineStart,
  4103. lineEnd: lineEnd,
  4104. polygonStart: function() {
  4105. clip.point = pointRing;
  4106. clip.lineStart = ringStart;
  4107. clip.lineEnd = ringEnd;
  4108. segments = [];
  4109. polygon = [];
  4110. },
  4111. polygonEnd: function() {
  4112. clip.point = point;
  4113. clip.lineStart = lineStart;
  4114. clip.lineEnd = lineEnd;
  4115. segments = d3.merge(segments);
  4116. var clipStartInside = d3_geo_pointInPolygon(rotatedClipStart, polygon);
  4117. if (segments.length) {
  4118. if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
  4119. d3_geo_clipPolygon(segments, d3_geo_clipSort, clipStartInside, interpolate, listener);
  4120. } else if (clipStartInside) {
  4121. if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
  4122. listener.lineStart();
  4123. interpolate(null, null, 1, listener);
  4124. listener.lineEnd();
  4125. }
  4126. if (polygonStarted) listener.polygonEnd(), polygonStarted = false;
  4127. segments = polygon = null;
  4128. },
  4129. sphere: function() {
  4130. listener.polygonStart();
  4131. listener.lineStart();
  4132. interpolate(null, null, 1, listener);
  4133. listener.lineEnd();
  4134. listener.polygonEnd();
  4135. }
  4136. };
  4137. function point(λ, φ) {
  4138. var point = rotate(λ, φ);
  4139. if (pointVisible(λ = point[0], φ = point[1])) listener.point(λ, φ);
  4140. }
  4141. function pointLine(λ, φ) {
  4142. var point = rotate(λ, φ);
  4143. line.point(point[0], point[1]);
  4144. }
  4145. function lineStart() {
  4146. clip.point = pointLine;
  4147. line.lineStart();
  4148. }
  4149. function lineEnd() {
  4150. clip.point = point;
  4151. line.lineEnd();
  4152. }
  4153. var segments;
  4154. var buffer = d3_geo_clipBufferListener(), ringListener = clipLine(buffer), polygonStarted = false, polygon, ring;
  4155. function pointRing(λ, φ) {
  4156. ring.push([ λ, φ ]);
  4157. var point = rotate(λ, φ);
  4158. ringListener.point(point[0], point[1]);
  4159. }
  4160. function ringStart() {
  4161. ringListener.lineStart();
  4162. ring = [];
  4163. }
  4164. function ringEnd() {
  4165. pointRing(ring[0][0], ring[0][1]);
  4166. ringListener.lineEnd();
  4167. var clean = ringListener.clean(), ringSegments = buffer.buffer(), segment, n = ringSegments.length;
  4168. ring.pop();
  4169. polygon.push(ring);
  4170. ring = null;
  4171. if (!n) return;
  4172. if (clean & 1) {
  4173. segment = ringSegments[0];
  4174. var n = segment.length - 1, i = -1, point;
  4175. if (n > 0) {
  4176. if (!polygonStarted) listener.polygonStart(), polygonStarted = true;
  4177. listener.lineStart();
  4178. while (++i < n) listener.point((point = segment[i])[0], point[1]);
  4179. listener.lineEnd();
  4180. }
  4181. return;
  4182. }
  4183. if (n > 1 && clean & 2) ringSegments.push(ringSegments.pop().concat(ringSegments.shift()));
  4184. segments.push(ringSegments.filter(d3_geo_clipSegmentLength1));
  4185. }
  4186. return clip;
  4187. };
  4188. }
  4189. function d3_geo_clipSegmentLength1(segment) {
  4190. return segment.length > 1;
  4191. }
  4192. function d3_geo_clipBufferListener() {
  4193. var lines = [], line;
  4194. return {
  4195. lineStart: function() {
  4196. lines.push(line = []);
  4197. },
  4198. point: function(λ, φ) {
  4199. line.push([ λ, φ ]);
  4200. },
  4201. lineEnd: d3_noop,
  4202. buffer: function() {
  4203. var buffer = lines;
  4204. lines = [];
  4205. line = null;
  4206. return buffer;
  4207. },
  4208. rejoin: function() {
  4209. if (lines.length > 1) lines.push(lines.pop().concat(lines.shift()));
  4210. }
  4211. };
  4212. }
  4213. function d3_geo_clipSort(a, b) {
  4214. return ((a = a.x)[0] < 0 ? a[1] - halfπ - ε : halfπ - a[1]) - ((b = b.x)[0] < 0 ? b[1] - halfπ - ε : halfπ - b[1]);
  4215. }
  4216. var d3_geo_clipAntimeridian = d3_geo_clip(d3_true, d3_geo_clipAntimeridianLine, d3_geo_clipAntimeridianInterpolate, [ -π, -π / 2 ]);
  4217. function d3_geo_clipAntimeridianLine(listener) {
  4218. var λ0 = NaN, φ0 = NaN, sλ0 = NaN, clean;
  4219. return {
  4220. lineStart: function() {
  4221. listener.lineStart();
  4222. clean = 1;
  4223. },
  4224. point: function(λ1, φ1) {
  4225. var sλ1 = λ1 > 0 ? π : -π, dλ = abs(λ1 - λ0);
  4226. if (abs(dλ - π) < ε) {
  4227. listener.point(λ0, φ0 = (φ0 + φ1) / 2 > 0 ? halfπ : -halfπ);
  4228. listener.point(sλ0, φ0);
  4229. listener.lineEnd();
  4230. listener.lineStart();
  4231. listener.point(sλ1, φ0);
  4232. listener.point(λ1, φ0);
  4233. clean = 0;
  4234. } else if (sλ0 !== sλ1 && dλ >= π) {
  4235. if (abs(λ0 - sλ0) < ε) λ0 -= sλ0 * ε;
  4236. if (abs(λ1 - sλ1) < ε) λ1 -= sλ1 * ε;
  4237. φ0 = d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1);
  4238. listener.point(sλ0, φ0);
  4239. listener.lineEnd();
  4240. listener.lineStart();
  4241. listener.point(sλ1, φ0);
  4242. clean = 0;
  4243. }
  4244. listener.point(λ0 = λ1, φ0 = φ1);
  4245. sλ0 = sλ1;
  4246. },
  4247. lineEnd: function() {
  4248. listener.lineEnd();
  4249. λ0 = φ0 = NaN;
  4250. },
  4251. clean: function() {
  4252. return 2 - clean;
  4253. }
  4254. };
  4255. }
  4256. function d3_geo_clipAntimeridianIntersect(λ0, φ0, λ1, φ1) {
  4257. var cosφ0, cosφ1, sinλ0_λ1 = Math.sin(λ0 - λ1);
  4258. return abs(sinλ0_λ1) > ε ? Math.atan((Math.sin(φ0) * (cosφ1 = Math.cos(φ1)) * Math.sin(λ1) - Math.sin(φ1) * (cosφ0 = Math.cos(φ0)) * Math.sin(λ0)) / (cosφ0 * cosφ1 * sinλ0_λ1)) : (φ0 + φ1) / 2;
  4259. }
  4260. function d3_geo_clipAntimeridianInterpolate(from, to, direction, listener) {
  4261. var φ;
  4262. if (from == null) {
  4263. φ = direction * halfπ;
  4264. listener.point(-π, φ);
  4265. listener.point(0, φ);
  4266. listener.point(π, φ);
  4267. listener.point(π, 0);
  4268. listener.point(π, -φ);
  4269. listener.point(0, -φ);
  4270. listener.point(-π, -φ);
  4271. listener.point(-π, 0);
  4272. listener.point(-π, φ);
  4273. } else if (abs(from[0] - to[0]) > ε) {
  4274. var s = from[0] < to[0] ? π : -π;
  4275. φ = direction * s / 2;
  4276. listener.point(-s, φ);
  4277. listener.point(0, φ);
  4278. listener.point(s, φ);
  4279. } else {
  4280. listener.point(to[0], to[1]);
  4281. }
  4282. }
  4283. function d3_geo_pointInPolygon(point, polygon) {
  4284. var meridian = point[0], parallel = point[1], meridianNormal = [ Math.sin(meridian), -Math.cos(meridian), 0 ], polarAngle = 0, winding = 0;
  4285. d3_geo_areaRingSum.reset();
  4286. for (var i = 0, n = polygon.length; i < n; ++i) {
  4287. var ring = polygon[i], m = ring.length;
  4288. if (!m) continue;
  4289. var point0 = ring[0], λ0 = point0[0], φ0 = point0[1] / 2 + π / 4, sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), j = 1;
  4290. while (true) {
  4291. if (j === m) j = 0;
  4292. point = ring[j];
  4293. var λ = point[0], φ = point[1] / 2 + π / 4, sinφ = Math.sin(φ), cosφ = Math.cos(φ), dλ = λ - λ0, sdλ = dλ >= 0 ? 1 : -1, adλ = sdλ * dλ, antimeridian = adλ > π, k = sinφ0 * sinφ;
  4294. d3_geo_areaRingSum.add(Math.atan2(k * sdλ * Math.sin(adλ), cosφ0 * cosφ + k * Math.cos(adλ)));
  4295. polarAngle += antimeridian ? dλ + sdλ * τ : dλ;
  4296. if (antimeridian ^ λ0 >= meridian ^ λ >= meridian) {
  4297. var arc = d3_geo_cartesianCross(d3_geo_cartesian(point0), d3_geo_cartesian(point));
  4298. d3_geo_cartesianNormalize(arc);
  4299. var intersection = d3_geo_cartesianCross(meridianNormal, arc);
  4300. d3_geo_cartesianNormalize(intersection);
  4301. var φarc = (antimeridian ^ dλ >= 0 ? -1 : 1) * d3_asin(intersection[2]);
  4302. if (parallel > φarc || parallel === φarc && (arc[0] || arc[1])) {
  4303. winding += antimeridian ^ dλ >= 0 ? 1 : -1;
  4304. }
  4305. }
  4306. if (!j++) break;
  4307. λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ, point0 = point;
  4308. }
  4309. }
  4310. return (polarAngle < -ε || polarAngle < ε && d3_geo_areaRingSum < -ε) ^ winding & 1;
  4311. }
  4312. function d3_geo_clipCircle(radius) {
  4313. var cr = Math.cos(radius), smallRadius = cr > 0, notHemisphere = abs(cr) > ε, interpolate = d3_geo_circleInterpolate(radius, 6 * d3_radians);
  4314. return d3_geo_clip(visible, clipLine, interpolate, smallRadius ? [ 0, -radius ] : [ -π, radius - π ]);
  4315. function visible(λ, φ) {
  4316. return Math.cos(λ) * Math.cos(φ) > cr;
  4317. }
  4318. function clipLine(listener) {
  4319. var point0, c0, v0, v00, clean;
  4320. return {
  4321. lineStart: function() {
  4322. v00 = v0 = false;
  4323. clean = 1;
  4324. },
  4325. point: function(λ, φ) {
  4326. var point1 = [ λ, φ ], point2, v = visible(λ, φ), c = smallRadius ? v ? 0 : code(λ, φ) : v ? code(λ + (λ < 0 ? π : -π), φ) : 0;
  4327. if (!point0 && (v00 = v0 = v)) listener.lineStart();
  4328. if (v !== v0) {
  4329. point2 = intersect(point0, point1);
  4330. if (d3_geo_sphericalEqual(point0, point2) || d3_geo_sphericalEqual(point1, point2)) {
  4331. point1[0] += ε;
  4332. point1[1] += ε;
  4333. v = visible(point1[0], point1[1]);
  4334. }
  4335. }
  4336. if (v !== v0) {
  4337. clean = 0;
  4338. if (v) {
  4339. listener.lineStart();
  4340. point2 = intersect(point1, point0);
  4341. listener.point(point2[0], point2[1]);
  4342. } else {
  4343. point2 = intersect(point0, point1);
  4344. listener.point(point2[0], point2[1]);
  4345. listener.lineEnd();
  4346. }
  4347. point0 = point2;
  4348. } else if (notHemisphere && point0 && smallRadius ^ v) {
  4349. var t;
  4350. if (!(c & c0) && (t = intersect(point1, point0, true))) {
  4351. clean = 0;
  4352. if (smallRadius) {
  4353. listener.lineStart();
  4354. listener.point(t[0][0], t[0][1]);
  4355. listener.point(t[1][0], t[1][1]);
  4356. listener.lineEnd();
  4357. } else {
  4358. listener.point(t[1][0], t[1][1]);
  4359. listener.lineEnd();
  4360. listener.lineStart();
  4361. listener.point(t[0][0], t[0][1]);
  4362. }
  4363. }
  4364. }
  4365. if (v && (!point0 || !d3_geo_sphericalEqual(point0, point1))) {
  4366. listener.point(point1[0], point1[1]);
  4367. }
  4368. point0 = point1, v0 = v, c0 = c;
  4369. },
  4370. lineEnd: function() {
  4371. if (v0) listener.lineEnd();
  4372. point0 = null;
  4373. },
  4374. clean: function() {
  4375. return clean | (v00 && v0) << 1;
  4376. }
  4377. };
  4378. }
  4379. function intersect(a, b, two) {
  4380. var pa = d3_geo_cartesian(a), pb = d3_geo_cartesian(b);
  4381. var n1 = [ 1, 0, 0 ], n2 = d3_geo_cartesianCross(pa, pb), n2n2 = d3_geo_cartesianDot(n2, n2), n1n2 = n2[0], determinant = n2n2 - n1n2 * n1n2;
  4382. if (!determinant) return !two && a;
  4383. var c1 = cr * n2n2 / determinant, c2 = -cr * n1n2 / determinant, n1xn2 = d3_geo_cartesianCross(n1, n2), A = d3_geo_cartesianScale(n1, c1), B = d3_geo_cartesianScale(n2, c2);
  4384. d3_geo_cartesianAdd(A, B);
  4385. var u = n1xn2, w = d3_geo_cartesianDot(A, u), uu = d3_geo_cartesianDot(u, u), t2 = w * w - uu * (d3_geo_cartesianDot(A, A) - 1);
  4386. if (t2 < 0) return;
  4387. var t = Math.sqrt(t2), q = d3_geo_cartesianScale(u, (-w - t) / uu);
  4388. d3_geo_cartesianAdd(q, A);
  4389. q = d3_geo_spherical(q);
  4390. if (!two) return q;
  4391. var λ0 = a[0], λ1 = b[0], φ0 = a[1], φ1 = b[1], z;
  4392. if (λ1 < λ0) z = λ0, λ0 = λ1, λ1 = z;
  4393. var δλ = λ1 - λ0, polar = abs(δλ - π) < ε, meridian = polar || δλ < ε;
  4394. if (!polar && φ1 < φ0) z = φ0, φ0 = φ1, φ1 = z;
  4395. if (meridian ? polar ? φ0 + φ1 > 0 ^ q[1] < (abs(q[0] - λ0) < ε ? φ0 : φ1) : φ0 <= q[1] && q[1] <= φ1 : δλ > π ^ (λ0 <= q[0] && q[0] <= λ1)) {
  4396. var q1 = d3_geo_cartesianScale(u, (-w + t) / uu);
  4397. d3_geo_cartesianAdd(q1, A);
  4398. return [ q, d3_geo_spherical(q1) ];
  4399. }
  4400. }
  4401. function code(λ, φ) {
  4402. var r = smallRadius ? radius : π - radius, code = 0;
  4403. if (λ < -r) code |= 1; else if (λ > r) code |= 2;
  4404. if (φ < -r) code |= 4; else if (φ > r) code |= 8;
  4405. return code;
  4406. }
  4407. }
  4408. function d3_geom_clipLine(x0, y0, x1, y1) {
  4409. return function(line) {
  4410. var a = line.a, b = line.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t0 = 0, t1 = 1, dx = bx - ax, dy = by - ay, r;
  4411. r = x0 - ax;
  4412. if (!dx && r > 0) return;
  4413. r /= dx;
  4414. if (dx < 0) {
  4415. if (r < t0) return;
  4416. if (r < t1) t1 = r;
  4417. } else if (dx > 0) {
  4418. if (r > t1) return;
  4419. if (r > t0) t0 = r;
  4420. }
  4421. r = x1 - ax;
  4422. if (!dx && r < 0) return;
  4423. r /= dx;
  4424. if (dx < 0) {
  4425. if (r > t1) return;
  4426. if (r > t0) t0 = r;
  4427. } else if (dx > 0) {
  4428. if (r < t0) return;
  4429. if (r < t1) t1 = r;
  4430. }
  4431. r = y0 - ay;
  4432. if (!dy && r > 0) return;
  4433. r /= dy;
  4434. if (dy < 0) {
  4435. if (r < t0) return;
  4436. if (r < t1) t1 = r;
  4437. } else if (dy > 0) {
  4438. if (r > t1) return;
  4439. if (r > t0) t0 = r;
  4440. }
  4441. r = y1 - ay;
  4442. if (!dy && r < 0) return;
  4443. r /= dy;
  4444. if (dy < 0) {
  4445. if (r > t1) return;
  4446. if (r > t0) t0 = r;
  4447. } else if (dy > 0) {
  4448. if (r < t0) return;
  4449. if (r < t1) t1 = r;
  4450. }
  4451. if (t0 > 0) line.a = {
  4452. x: ax + t0 * dx,
  4453. y: ay + t0 * dy
  4454. };
  4455. if (t1 < 1) line.b = {
  4456. x: ax + t1 * dx,
  4457. y: ay + t1 * dy
  4458. };
  4459. return line;
  4460. };
  4461. }
  4462. var d3_geo_clipExtentMAX = 1e9;
  4463. d3.geo.clipExtent = function() {
  4464. var x0, y0, x1, y1, stream, clip, clipExtent = {
  4465. stream: function(output) {
  4466. if (stream) stream.valid = false;
  4467. stream = clip(output);
  4468. stream.valid = true;
  4469. return stream;
  4470. },
  4471. extent: function(_) {
  4472. if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ];
  4473. clip = d3_geo_clipExtent(x0 = +_[0][0], y0 = +_[0][1], x1 = +_[1][0], y1 = +_[1][1]);
  4474. if (stream) stream.valid = false, stream = null;
  4475. return clipExtent;
  4476. }
  4477. };
  4478. return clipExtent.extent([ [ 0, 0 ], [ 960, 500 ] ]);
  4479. };
  4480. function d3_geo_clipExtent(x0, y0, x1, y1) {
  4481. return function(listener) {
  4482. var listener_ = listener, bufferListener = d3_geo_clipBufferListener(), clipLine = d3_geom_clipLine(x0, y0, x1, y1), segments, polygon, ring;
  4483. var clip = {
  4484. point: point,
  4485. lineStart: lineStart,
  4486. lineEnd: lineEnd,
  4487. polygonStart: function() {
  4488. listener = bufferListener;
  4489. segments = [];
  4490. polygon = [];
  4491. clean = true;
  4492. },
  4493. polygonEnd: function() {
  4494. listener = listener_;
  4495. segments = d3.merge(segments);
  4496. var clipStartInside = insidePolygon([ x0, y1 ]), inside = clean && clipStartInside, visible = segments.length;
  4497. if (inside || visible) {
  4498. listener.polygonStart();
  4499. if (inside) {
  4500. listener.lineStart();
  4501. interpolate(null, null, 1, listener);
  4502. listener.lineEnd();
  4503. }
  4504. if (visible) {
  4505. d3_geo_clipPolygon(segments, compare, clipStartInside, interpolate, listener);
  4506. }
  4507. listener.polygonEnd();
  4508. }
  4509. segments = polygon = ring = null;
  4510. }
  4511. };
  4512. function insidePolygon(p) {
  4513. var wn = 0, n = polygon.length, y = p[1];
  4514. for (var i = 0; i < n; ++i) {
  4515. for (var j = 1, v = polygon[i], m = v.length, a = v[0], b; j < m; ++j) {
  4516. b = v[j];
  4517. if (a[1] <= y) {
  4518. if (b[1] > y && d3_cross2d(a, b, p) > 0) ++wn;
  4519. } else {
  4520. if (b[1] <= y && d3_cross2d(a, b, p) < 0) --wn;
  4521. }
  4522. a = b;
  4523. }
  4524. }
  4525. return wn !== 0;
  4526. }
  4527. function interpolate(from, to, direction, listener) {
  4528. var a = 0, a1 = 0;
  4529. if (from == null || (a = corner(from, direction)) !== (a1 = corner(to, direction)) || comparePoints(from, to) < 0 ^ direction > 0) {
  4530. do {
  4531. listener.point(a === 0 || a === 3 ? x0 : x1, a > 1 ? y1 : y0);
  4532. } while ((a = (a + direction + 4) % 4) !== a1);
  4533. } else {
  4534. listener.point(to[0], to[1]);
  4535. }
  4536. }
  4537. function pointVisible(x, y) {
  4538. return x0 <= x && x <= x1 && y0 <= y && y <= y1;
  4539. }
  4540. function point(x, y) {
  4541. if (pointVisible(x, y)) listener.point(x, y);
  4542. }
  4543. var x__, y__, v__, x_, y_, v_, first, clean;
  4544. function lineStart() {
  4545. clip.point = linePoint;
  4546. if (polygon) polygon.push(ring = []);
  4547. first = true;
  4548. v_ = false;
  4549. x_ = y_ = NaN;
  4550. }
  4551. function lineEnd() {
  4552. if (segments) {
  4553. linePoint(x__, y__);
  4554. if (v__ && v_) bufferListener.rejoin();
  4555. segments.push(bufferListener.buffer());
  4556. }
  4557. clip.point = point;
  4558. if (v_) listener.lineEnd();
  4559. }
  4560. function linePoint(x, y) {
  4561. x = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, x));
  4562. y = Math.max(-d3_geo_clipExtentMAX, Math.min(d3_geo_clipExtentMAX, y));
  4563. var v = pointVisible(x, y);
  4564. if (polygon) ring.push([ x, y ]);
  4565. if (first) {
  4566. x__ = x, y__ = y, v__ = v;
  4567. first = false;
  4568. if (v) {
  4569. listener.lineStart();
  4570. listener.point(x, y);
  4571. }
  4572. } else {
  4573. if (v && v_) listener.point(x, y); else {
  4574. var l = {
  4575. a: {
  4576. x: x_,
  4577. y: y_
  4578. },
  4579. b: {
  4580. x: x,
  4581. y: y
  4582. }
  4583. };
  4584. if (clipLine(l)) {
  4585. if (!v_) {
  4586. listener.lineStart();
  4587. listener.point(l.a.x, l.a.y);
  4588. }
  4589. listener.point(l.b.x, l.b.y);
  4590. if (!v) listener.lineEnd();
  4591. clean = false;
  4592. } else if (v) {
  4593. listener.lineStart();
  4594. listener.point(x, y);
  4595. clean = false;
  4596. }
  4597. }
  4598. }
  4599. x_ = x, y_ = y, v_ = v;
  4600. }
  4601. return clip;
  4602. };
  4603. function corner(p, direction) {
  4604. return abs(p[0] - x0) < ε ? direction > 0 ? 0 : 3 : abs(p[0] - x1) < ε ? direction > 0 ? 2 : 1 : abs(p[1] - y0) < ε ? direction > 0 ? 1 : 0 : direction > 0 ? 3 : 2;
  4605. }
  4606. function compare(a, b) {
  4607. return comparePoints(a.x, b.x);
  4608. }
  4609. function comparePoints(a, b) {
  4610. var ca = corner(a, 1), cb = corner(b, 1);
  4611. return ca !== cb ? ca - cb : ca === 0 ? b[1] - a[1] : ca === 1 ? a[0] - b[0] : ca === 2 ? a[1] - b[1] : b[0] - a[0];
  4612. }
  4613. }
  4614. function d3_geo_conic(projectAt) {
  4615. var φ0 = 0, φ1 = π / 3, m = d3_geo_projectionMutator(projectAt), p = m(φ0, φ1);
  4616. p.parallels = function(_) {
  4617. if (!arguments.length) return [ φ0 / π * 180, φ1 / π * 180 ];
  4618. return m(φ0 = _[0] * π / 180, φ1 = _[1] * π / 180);
  4619. };
  4620. return p;
  4621. }
  4622. function d3_geo_conicEqualArea(φ0, φ1) {
  4623. var sinφ0 = Math.sin(φ0), n = (sinφ0 + Math.sin(φ1)) / 2, C = 1 + sinφ0 * (2 * n - sinφ0), ρ0 = Math.sqrt(C) / n;
  4624. function forward(λ, φ) {
  4625. var ρ = Math.sqrt(C - 2 * n * Math.sin(φ)) / n;
  4626. return [ ρ * Math.sin(λ *= n), ρ0 - ρ * Math.cos(λ) ];
  4627. }
  4628. forward.invert = function(x, y) {
  4629. var ρ0_y = ρ0 - y;
  4630. return [ Math.atan2(x, ρ0_y) / n, d3_asin((C - (x * x + ρ0_y * ρ0_y) * n * n) / (2 * n)) ];
  4631. };
  4632. return forward;
  4633. }
  4634. (d3.geo.conicEqualArea = function() {
  4635. return d3_geo_conic(d3_geo_conicEqualArea);
  4636. }).raw = d3_geo_conicEqualArea;
  4637. d3.geo.albers = function() {
  4638. return d3.geo.conicEqualArea().rotate([ 96, 0 ]).center([ -.6, 38.7 ]).parallels([ 29.5, 45.5 ]).scale(1070);
  4639. };
  4640. d3.geo.albersUsa = function() {
  4641. var lower48 = d3.geo.albers();
  4642. var alaska = d3.geo.conicEqualArea().rotate([ 154, 0 ]).center([ -2, 58.5 ]).parallels([ 55, 65 ]);
  4643. var hawaii = d3.geo.conicEqualArea().rotate([ 157, 0 ]).center([ -3, 19.9 ]).parallels([ 8, 18 ]);
  4644. var point, pointStream = {
  4645. point: function(x, y) {
  4646. point = [ x, y ];
  4647. }
  4648. }, lower48Point, alaskaPoint, hawaiiPoint;
  4649. function albersUsa(coordinates) {
  4650. var x = coordinates[0], y = coordinates[1];
  4651. point = null;
  4652. (lower48Point(x, y), point) || (alaskaPoint(x, y), point) || hawaiiPoint(x, y);
  4653. return point;
  4654. }
  4655. albersUsa.invert = function(coordinates) {
  4656. var k = lower48.scale(), t = lower48.translate(), x = (coordinates[0] - t[0]) / k, y = (coordinates[1] - t[1]) / k;
  4657. return (y >= .12 && y < .234 && x >= -.425 && x < -.214 ? alaska : y >= .166 && y < .234 && x >= -.214 && x < -.115 ? hawaii : lower48).invert(coordinates);
  4658. };
  4659. albersUsa.stream = function(stream) {
  4660. var lower48Stream = lower48.stream(stream), alaskaStream = alaska.stream(stream), hawaiiStream = hawaii.stream(stream);
  4661. return {
  4662. point: function(x, y) {
  4663. lower48Stream.point(x, y);
  4664. alaskaStream.point(x, y);
  4665. hawaiiStream.point(x, y);
  4666. },
  4667. sphere: function() {
  4668. lower48Stream.sphere();
  4669. alaskaStream.sphere();
  4670. hawaiiStream.sphere();
  4671. },
  4672. lineStart: function() {
  4673. lower48Stream.lineStart();
  4674. alaskaStream.lineStart();
  4675. hawaiiStream.lineStart();
  4676. },
  4677. lineEnd: function() {
  4678. lower48Stream.lineEnd();
  4679. alaskaStream.lineEnd();
  4680. hawaiiStream.lineEnd();
  4681. },
  4682. polygonStart: function() {
  4683. lower48Stream.polygonStart();
  4684. alaskaStream.polygonStart();
  4685. hawaiiStream.polygonStart();
  4686. },
  4687. polygonEnd: function() {
  4688. lower48Stream.polygonEnd();
  4689. alaskaStream.polygonEnd();
  4690. hawaiiStream.polygonEnd();
  4691. }
  4692. };
  4693. };
  4694. albersUsa.precision = function(_) {
  4695. if (!arguments.length) return lower48.precision();
  4696. lower48.precision(_);
  4697. alaska.precision(_);
  4698. hawaii.precision(_);
  4699. return albersUsa;
  4700. };
  4701. albersUsa.scale = function(_) {
  4702. if (!arguments.length) return lower48.scale();
  4703. lower48.scale(_);
  4704. alaska.scale(_ * .35);
  4705. hawaii.scale(_);
  4706. return albersUsa.translate(lower48.translate());
  4707. };
  4708. albersUsa.translate = function(_) {
  4709. if (!arguments.length) return lower48.translate();
  4710. var k = lower48.scale(), x = +_[0], y = +_[1];
  4711. lower48Point = lower48.translate(_).clipExtent([ [ x - .455 * k, y - .238 * k ], [ x + .455 * k, y + .238 * k ] ]).stream(pointStream).point;
  4712. alaskaPoint = alaska.translate([ x - .307 * k, y + .201 * k ]).clipExtent([ [ x - .425 * k + ε, y + .12 * k + ε ], [ x - .214 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point;
  4713. hawaiiPoint = hawaii.translate([ x - .205 * k, y + .212 * k ]).clipExtent([ [ x - .214 * k + ε, y + .166 * k + ε ], [ x - .115 * k - ε, y + .234 * k - ε ] ]).stream(pointStream).point;
  4714. return albersUsa;
  4715. };
  4716. return albersUsa.scale(1070);
  4717. };
  4718. var d3_geo_pathAreaSum, d3_geo_pathAreaPolygon, d3_geo_pathArea = {
  4719. point: d3_noop,
  4720. lineStart: d3_noop,
  4721. lineEnd: d3_noop,
  4722. polygonStart: function() {
  4723. d3_geo_pathAreaPolygon = 0;
  4724. d3_geo_pathArea.lineStart = d3_geo_pathAreaRingStart;
  4725. },
  4726. polygonEnd: function() {
  4727. d3_geo_pathArea.lineStart = d3_geo_pathArea.lineEnd = d3_geo_pathArea.point = d3_noop;
  4728. d3_geo_pathAreaSum += abs(d3_geo_pathAreaPolygon / 2);
  4729. }
  4730. };
  4731. function d3_geo_pathAreaRingStart() {
  4732. var x00, y00, x0, y0;
  4733. d3_geo_pathArea.point = function(x, y) {
  4734. d3_geo_pathArea.point = nextPoint;
  4735. x00 = x0 = x, y00 = y0 = y;
  4736. };
  4737. function nextPoint(x, y) {
  4738. d3_geo_pathAreaPolygon += y0 * x - x0 * y;
  4739. x0 = x, y0 = y;
  4740. }
  4741. d3_geo_pathArea.lineEnd = function() {
  4742. nextPoint(x00, y00);
  4743. };
  4744. }
  4745. var d3_geo_pathBoundsX0, d3_geo_pathBoundsY0, d3_geo_pathBoundsX1, d3_geo_pathBoundsY1;
  4746. var d3_geo_pathBounds = {
  4747. point: d3_geo_pathBoundsPoint,
  4748. lineStart: d3_noop,
  4749. lineEnd: d3_noop,
  4750. polygonStart: d3_noop,
  4751. polygonEnd: d3_noop
  4752. };
  4753. function d3_geo_pathBoundsPoint(x, y) {
  4754. if (x < d3_geo_pathBoundsX0) d3_geo_pathBoundsX0 = x;
  4755. if (x > d3_geo_pathBoundsX1) d3_geo_pathBoundsX1 = x;
  4756. if (y < d3_geo_pathBoundsY0) d3_geo_pathBoundsY0 = y;
  4757. if (y > d3_geo_pathBoundsY1) d3_geo_pathBoundsY1 = y;
  4758. }
  4759. function d3_geo_pathBuffer() {
  4760. var pointCircle = d3_geo_pathBufferCircle(4.5), buffer = [];
  4761. var stream = {
  4762. point: point,
  4763. lineStart: function() {
  4764. stream.point = pointLineStart;
  4765. },
  4766. lineEnd: lineEnd,
  4767. polygonStart: function() {
  4768. stream.lineEnd = lineEndPolygon;
  4769. },
  4770. polygonEnd: function() {
  4771. stream.lineEnd = lineEnd;
  4772. stream.point = point;
  4773. },
  4774. pointRadius: function(_) {
  4775. pointCircle = d3_geo_pathBufferCircle(_);
  4776. return stream;
  4777. },
  4778. result: function() {
  4779. if (buffer.length) {
  4780. var result = buffer.join("");
  4781. buffer = [];
  4782. return result;
  4783. }
  4784. }
  4785. };
  4786. function point(x, y) {
  4787. buffer.push("M", x, ",", y, pointCircle);
  4788. }
  4789. function pointLineStart(x, y) {
  4790. buffer.push("M", x, ",", y);
  4791. stream.point = pointLine;
  4792. }
  4793. function pointLine(x, y) {
  4794. buffer.push("L", x, ",", y);
  4795. }
  4796. function lineEnd() {
  4797. stream.point = point;
  4798. }
  4799. function lineEndPolygon() {
  4800. buffer.push("Z");
  4801. }
  4802. return stream;
  4803. }
  4804. function d3_geo_pathBufferCircle(radius) {
  4805. return "m0," + radius + "a" + radius + "," + radius + " 0 1,1 0," + -2 * radius + "a" + radius + "," + radius + " 0 1,1 0," + 2 * radius + "z";
  4806. }
  4807. var d3_geo_pathCentroid = {
  4808. point: d3_geo_pathCentroidPoint,
  4809. lineStart: d3_geo_pathCentroidLineStart,
  4810. lineEnd: d3_geo_pathCentroidLineEnd,
  4811. polygonStart: function() {
  4812. d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidRingStart;
  4813. },
  4814. polygonEnd: function() {
  4815. d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint;
  4816. d3_geo_pathCentroid.lineStart = d3_geo_pathCentroidLineStart;
  4817. d3_geo_pathCentroid.lineEnd = d3_geo_pathCentroidLineEnd;
  4818. }
  4819. };
  4820. function d3_geo_pathCentroidPoint(x, y) {
  4821. d3_geo_centroidX0 += x;
  4822. d3_geo_centroidY0 += y;
  4823. ++d3_geo_centroidZ0;
  4824. }
  4825. function d3_geo_pathCentroidLineStart() {
  4826. var x0, y0;
  4827. d3_geo_pathCentroid.point = function(x, y) {
  4828. d3_geo_pathCentroid.point = nextPoint;
  4829. d3_geo_pathCentroidPoint(x0 = x, y0 = y);
  4830. };
  4831. function nextPoint(x, y) {
  4832. var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy);
  4833. d3_geo_centroidX1 += z * (x0 + x) / 2;
  4834. d3_geo_centroidY1 += z * (y0 + y) / 2;
  4835. d3_geo_centroidZ1 += z;
  4836. d3_geo_pathCentroidPoint(x0 = x, y0 = y);
  4837. }
  4838. }
  4839. function d3_geo_pathCentroidLineEnd() {
  4840. d3_geo_pathCentroid.point = d3_geo_pathCentroidPoint;
  4841. }
  4842. function d3_geo_pathCentroidRingStart() {
  4843. var x00, y00, x0, y0;
  4844. d3_geo_pathCentroid.point = function(x, y) {
  4845. d3_geo_pathCentroid.point = nextPoint;
  4846. d3_geo_pathCentroidPoint(x00 = x0 = x, y00 = y0 = y);
  4847. };
  4848. function nextPoint(x, y) {
  4849. var dx = x - x0, dy = y - y0, z = Math.sqrt(dx * dx + dy * dy);
  4850. d3_geo_centroidX1 += z * (x0 + x) / 2;
  4851. d3_geo_centroidY1 += z * (y0 + y) / 2;
  4852. d3_geo_centroidZ1 += z;
  4853. z = y0 * x - x0 * y;
  4854. d3_geo_centroidX2 += z * (x0 + x);
  4855. d3_geo_centroidY2 += z * (y0 + y);
  4856. d3_geo_centroidZ2 += z * 3;
  4857. d3_geo_pathCentroidPoint(x0 = x, y0 = y);
  4858. }
  4859. d3_geo_pathCentroid.lineEnd = function() {
  4860. nextPoint(x00, y00);
  4861. };
  4862. }
  4863. function d3_geo_pathContext(context) {
  4864. var pointRadius = 4.5;
  4865. var stream = {
  4866. point: point,
  4867. lineStart: function() {
  4868. stream.point = pointLineStart;
  4869. },
  4870. lineEnd: lineEnd,
  4871. polygonStart: function() {
  4872. stream.lineEnd = lineEndPolygon;
  4873. },
  4874. polygonEnd: function() {
  4875. stream.lineEnd = lineEnd;
  4876. stream.point = point;
  4877. },
  4878. pointRadius: function(_) {
  4879. pointRadius = _;
  4880. return stream;
  4881. },
  4882. result: d3_noop
  4883. };
  4884. function point(x, y) {
  4885. context.moveTo(x + pointRadius, y);
  4886. context.arc(x, y, pointRadius, 0, τ);
  4887. }
  4888. function pointLineStart(x, y) {
  4889. context.moveTo(x, y);
  4890. stream.point = pointLine;
  4891. }
  4892. function pointLine(x, y) {
  4893. context.lineTo(x, y);
  4894. }
  4895. function lineEnd() {
  4896. stream.point = point;
  4897. }
  4898. function lineEndPolygon() {
  4899. context.closePath();
  4900. }
  4901. return stream;
  4902. }
  4903. function d3_geo_resample(project) {
  4904. var δ2 = .5, cosMinDistance = Math.cos(30 * d3_radians), maxDepth = 16;
  4905. function resample(stream) {
  4906. return (maxDepth ? resampleRecursive : resampleNone)(stream);
  4907. }
  4908. function resampleNone(stream) {
  4909. return d3_geo_transformPoint(stream, function(x, y) {
  4910. x = project(x, y);
  4911. stream.point(x[0], x[1]);
  4912. });
  4913. }
  4914. function resampleRecursive(stream) {
  4915. var λ00, φ00, x00, y00, a00, b00, c00, λ0, x0, y0, a0, b0, c0;
  4916. var resample = {
  4917. point: point,
  4918. lineStart: lineStart,
  4919. lineEnd: lineEnd,
  4920. polygonStart: function() {
  4921. stream.polygonStart();
  4922. resample.lineStart = ringStart;
  4923. },
  4924. polygonEnd: function() {
  4925. stream.polygonEnd();
  4926. resample.lineStart = lineStart;
  4927. }
  4928. };
  4929. function point(x, y) {
  4930. x = project(x, y);
  4931. stream.point(x[0], x[1]);
  4932. }
  4933. function lineStart() {
  4934. x0 = NaN;
  4935. resample.point = linePoint;
  4936. stream.lineStart();
  4937. }
  4938. function linePoint(λ, φ) {
  4939. var c = d3_geo_cartesian([ λ, φ ]), p = project(λ, φ);
  4940. resampleLineTo(x0, y0, λ0, a0, b0, c0, x0 = p[0], y0 = p[1], λ0 = λ, a0 = c[0], b0 = c[1], c0 = c[2], maxDepth, stream);
  4941. stream.point(x0, y0);
  4942. }
  4943. function lineEnd() {
  4944. resample.point = point;
  4945. stream.lineEnd();
  4946. }
  4947. function ringStart() {
  4948. lineStart();
  4949. resample.point = ringPoint;
  4950. resample.lineEnd = ringEnd;
  4951. }
  4952. function ringPoint(λ, φ) {
  4953. linePoint(λ00 = λ, φ00 = φ), x00 = x0, y00 = y0, a00 = a0, b00 = b0, c00 = c0;
  4954. resample.point = linePoint;
  4955. }
  4956. function ringEnd() {
  4957. resampleLineTo(x0, y0, λ0, a0, b0, c0, x00, y00, λ00, a00, b00, c00, maxDepth, stream);
  4958. resample.lineEnd = lineEnd;
  4959. lineEnd();
  4960. }
  4961. return resample;
  4962. }
  4963. function resampleLineTo(x0, y0, λ0, a0, b0, c0, x1, y1, λ1, a1, b1, c1, depth, stream) {
  4964. var dx = x1 - x0, dy = y1 - y0, d2 = dx * dx + dy * dy;
  4965. if (d2 > 4 * δ2 && depth--) {
  4966. var a = a0 + a1, b = b0 + b1, c = c0 + c1, m = Math.sqrt(a * a + b * b + c * c), φ2 = Math.asin(c /= m), λ2 = abs(abs(c) - 1) < ε || abs(λ0 - λ1) < ε ? (λ0 + λ1) / 2 : Math.atan2(b, a), p = project(λ2, φ2), x2 = p[0], y2 = p[1], dx2 = x2 - x0, dy2 = y2 - y0, dz = dy * dx2 - dx * dy2;
  4967. if (dz * dz / d2 > δ2 || abs((dx * dx2 + dy * dy2) / d2 - .5) > .3 || a0 * a1 + b0 * b1 + c0 * c1 < cosMinDistance) {
  4968. resampleLineTo(x0, y0, λ0, a0, b0, c0, x2, y2, λ2, a /= m, b /= m, c, depth, stream);
  4969. stream.point(x2, y2);
  4970. resampleLineTo(x2, y2, λ2, a, b, c, x1, y1, λ1, a1, b1, c1, depth, stream);
  4971. }
  4972. }
  4973. }
  4974. resample.precision = function(_) {
  4975. if (!arguments.length) return Math.sqrt(δ2);
  4976. maxDepth = (δ2 = _ * _) > 0 && 16;
  4977. return resample;
  4978. };
  4979. return resample;
  4980. }
  4981. d3.geo.path = function() {
  4982. var pointRadius = 4.5, projection, context, projectStream, contextStream, cacheStream;
  4983. function path(object) {
  4984. if (object) {
  4985. if (typeof pointRadius === "function") contextStream.pointRadius(+pointRadius.apply(this, arguments));
  4986. if (!cacheStream || !cacheStream.valid) cacheStream = projectStream(contextStream);
  4987. d3.geo.stream(object, cacheStream);
  4988. }
  4989. return contextStream.result();
  4990. }
  4991. path.area = function(object) {
  4992. d3_geo_pathAreaSum = 0;
  4993. d3.geo.stream(object, projectStream(d3_geo_pathArea));
  4994. return d3_geo_pathAreaSum;
  4995. };
  4996. path.centroid = function(object) {
  4997. d3_geo_centroidX0 = d3_geo_centroidY0 = d3_geo_centroidZ0 = d3_geo_centroidX1 = d3_geo_centroidY1 = d3_geo_centroidZ1 = d3_geo_centroidX2 = d3_geo_centroidY2 = d3_geo_centroidZ2 = 0;
  4998. d3.geo.stream(object, projectStream(d3_geo_pathCentroid));
  4999. return d3_geo_centroidZ2 ? [ d3_geo_centroidX2 / d3_geo_centroidZ2, d3_geo_centroidY2 / d3_geo_centroidZ2 ] : d3_geo_centroidZ1 ? [ d3_geo_centroidX1 / d3_geo_centroidZ1, d3_geo_centroidY1 / d3_geo_centroidZ1 ] : d3_geo_centroidZ0 ? [ d3_geo_centroidX0 / d3_geo_centroidZ0, d3_geo_centroidY0 / d3_geo_centroidZ0 ] : [ NaN, NaN ];
  5000. };
  5001. path.bounds = function(object) {
  5002. d3_geo_pathBoundsX1 = d3_geo_pathBoundsY1 = -(d3_geo_pathBoundsX0 = d3_geo_pathBoundsY0 = Infinity);
  5003. d3.geo.stream(object, projectStream(d3_geo_pathBounds));
  5004. return [ [ d3_geo_pathBoundsX0, d3_geo_pathBoundsY0 ], [ d3_geo_pathBoundsX1, d3_geo_pathBoundsY1 ] ];
  5005. };
  5006. path.projection = function(_) {
  5007. if (!arguments.length) return projection;
  5008. projectStream = (projection = _) ? _.stream || d3_geo_pathProjectStream(_) : d3_identity;
  5009. return reset();
  5010. };
  5011. path.context = function(_) {
  5012. if (!arguments.length) return context;
  5013. contextStream = (context = _) == null ? new d3_geo_pathBuffer() : new d3_geo_pathContext(_);
  5014. if (typeof pointRadius !== "function") contextStream.pointRadius(pointRadius);
  5015. return reset();
  5016. };
  5017. path.pointRadius = function(_) {
  5018. if (!arguments.length) return pointRadius;
  5019. pointRadius = typeof _ === "function" ? _ : (contextStream.pointRadius(+_), +_);
  5020. return path;
  5021. };
  5022. function reset() {
  5023. cacheStream = null;
  5024. return path;
  5025. }
  5026. return path.projection(d3.geo.albersUsa()).context(null);
  5027. };
  5028. function d3_geo_pathProjectStream(project) {
  5029. var resample = d3_geo_resample(function(x, y) {
  5030. return project([ x * d3_degrees, y * d3_degrees ]);
  5031. });
  5032. return function(stream) {
  5033. return d3_geo_projectionRadians(resample(stream));
  5034. };
  5035. }
  5036. d3.geo.transform = function(methods) {
  5037. return {
  5038. stream: function(stream) {
  5039. var transform = new d3_geo_transform(stream);
  5040. for (var k in methods) transform[k] = methods[k];
  5041. return transform;
  5042. }
  5043. };
  5044. };
  5045. function d3_geo_transform(stream) {
  5046. this.stream = stream;
  5047. }
  5048. d3_geo_transform.prototype = {
  5049. point: function(x, y) {
  5050. this.stream.point(x, y);
  5051. },
  5052. sphere: function() {
  5053. this.stream.sphere();
  5054. },
  5055. lineStart: function() {
  5056. this.stream.lineStart();
  5057. },
  5058. lineEnd: function() {
  5059. this.stream.lineEnd();
  5060. },
  5061. polygonStart: function() {
  5062. this.stream.polygonStart();
  5063. },
  5064. polygonEnd: function() {
  5065. this.stream.polygonEnd();
  5066. }
  5067. };
  5068. function d3_geo_transformPoint(stream, point) {
  5069. return {
  5070. point: point,
  5071. sphere: function() {
  5072. stream.sphere();
  5073. },
  5074. lineStart: function() {
  5075. stream.lineStart();
  5076. },
  5077. lineEnd: function() {
  5078. stream.lineEnd();
  5079. },
  5080. polygonStart: function() {
  5081. stream.polygonStart();
  5082. },
  5083. polygonEnd: function() {
  5084. stream.polygonEnd();
  5085. }
  5086. };
  5087. }
  5088. d3.geo.projection = d3_geo_projection;
  5089. d3.geo.projectionMutator = d3_geo_projectionMutator;
  5090. function d3_geo_projection(project) {
  5091. return d3_geo_projectionMutator(function() {
  5092. return project;
  5093. })();
  5094. }
  5095. function d3_geo_projectionMutator(projectAt) {
  5096. var project, rotate, projectRotate, projectResample = d3_geo_resample(function(x, y) {
  5097. x = project(x, y);
  5098. return [ x[0] * k + δx, δy - x[1] * k ];
  5099. }), k = 150, x = 480, y = 250, λ = 0, φ = 0, δλ = 0, δφ = 0, δγ = 0, δx, δy, preclip = d3_geo_clipAntimeridian, postclip = d3_identity, clipAngle = null, clipExtent = null, stream;
  5100. function projection(point) {
  5101. point = projectRotate(point[0] * d3_radians, point[1] * d3_radians);
  5102. return [ point[0] * k + δx, δy - point[1] * k ];
  5103. }
  5104. function invert(point) {
  5105. point = projectRotate.invert((point[0] - δx) / k, (δy - point[1]) / k);
  5106. return point && [ point[0] * d3_degrees, point[1] * d3_degrees ];
  5107. }
  5108. projection.stream = function(output) {
  5109. if (stream) stream.valid = false;
  5110. stream = d3_geo_projectionRadians(preclip(rotate, projectResample(postclip(output))));
  5111. stream.valid = true;
  5112. return stream;
  5113. };
  5114. projection.clipAngle = function(_) {
  5115. if (!arguments.length) return clipAngle;
  5116. preclip = _ == null ? (clipAngle = _, d3_geo_clipAntimeridian) : d3_geo_clipCircle((clipAngle = +_) * d3_radians);
  5117. return invalidate();
  5118. };
  5119. projection.clipExtent = function(_) {
  5120. if (!arguments.length) return clipExtent;
  5121. clipExtent = _;
  5122. postclip = _ ? d3_geo_clipExtent(_[0][0], _[0][1], _[1][0], _[1][1]) : d3_identity;
  5123. return invalidate();
  5124. };
  5125. projection.scale = function(_) {
  5126. if (!arguments.length) return k;
  5127. k = +_;
  5128. return reset();
  5129. };
  5130. projection.translate = function(_) {
  5131. if (!arguments.length) return [ x, y ];
  5132. x = +_[0];
  5133. y = +_[1];
  5134. return reset();
  5135. };
  5136. projection.center = function(_) {
  5137. if (!arguments.length) return [ λ * d3_degrees, φ * d3_degrees ];
  5138. λ = _[0] % 360 * d3_radians;
  5139. φ = _[1] % 360 * d3_radians;
  5140. return reset();
  5141. };
  5142. projection.rotate = function(_) {
  5143. if (!arguments.length) return [ δλ * d3_degrees, δφ * d3_degrees, δγ * d3_degrees ];
  5144. δλ = _[0] % 360 * d3_radians;
  5145. δφ = _[1] % 360 * d3_radians;
  5146. δγ = _.length > 2 ? _[2] % 360 * d3_radians : 0;
  5147. return reset();
  5148. };
  5149. d3.rebind(projection, projectResample, "precision");
  5150. function reset() {
  5151. projectRotate = d3_geo_compose(rotate = d3_geo_rotation(δλ, δφ, δγ), project);
  5152. var center = project(λ, φ);
  5153. δx = x - center[0] * k;
  5154. δy = y + center[1] * k;
  5155. return invalidate();
  5156. }
  5157. function invalidate() {
  5158. if (stream) stream.valid = false, stream = null;
  5159. return projection;
  5160. }
  5161. return function() {
  5162. project = projectAt.apply(this, arguments);
  5163. projection.invert = project.invert && invert;
  5164. return reset();
  5165. };
  5166. }
  5167. function d3_geo_projectionRadians(stream) {
  5168. return d3_geo_transformPoint(stream, function(x, y) {
  5169. stream.point(x * d3_radians, y * d3_radians);
  5170. });
  5171. }
  5172. function d3_geo_equirectangular(λ, φ) {
  5173. return [ λ, φ ];
  5174. }
  5175. (d3.geo.equirectangular = function() {
  5176. return d3_geo_projection(d3_geo_equirectangular);
  5177. }).raw = d3_geo_equirectangular.invert = d3_geo_equirectangular;
  5178. d3.geo.rotation = function(rotate) {
  5179. rotate = d3_geo_rotation(rotate[0] % 360 * d3_radians, rotate[1] * d3_radians, rotate.length > 2 ? rotate[2] * d3_radians : 0);
  5180. function forward(coordinates) {
  5181. coordinates = rotate(coordinates[0] * d3_radians, coordinates[1] * d3_radians);
  5182. return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates;
  5183. }
  5184. forward.invert = function(coordinates) {
  5185. coordinates = rotate.invert(coordinates[0] * d3_radians, coordinates[1] * d3_radians);
  5186. return coordinates[0] *= d3_degrees, coordinates[1] *= d3_degrees, coordinates;
  5187. };
  5188. return forward;
  5189. };
  5190. function d3_geo_identityRotation(λ, φ) {
  5191. return [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ];
  5192. }
  5193. d3_geo_identityRotation.invert = d3_geo_equirectangular;
  5194. function d3_geo_rotation(δλ, δφ, δγ) {
  5195. return δλ ? δφ || δγ ? d3_geo_compose(d3_geo_rotationλ(δλ), d3_geo_rotationφγ(δφ, δγ)) : d3_geo_rotationλ(δλ) : δφ || δγ ? d3_geo_rotationφγ(δφ, δγ) : d3_geo_identityRotation;
  5196. }
  5197. function d3_geo_forwardRotationλ(δλ) {
  5198. return function(λ, φ) {
  5199. return λ += δλ, [ λ > π ? λ - τ : λ < -π ? λ + τ : λ, φ ];
  5200. };
  5201. }
  5202. function d3_geo_rotationλ(δλ) {
  5203. var rotation = d3_geo_forwardRotationλ(δλ);
  5204. rotation.invert = d3_geo_forwardRotationλ(-δλ);
  5205. return rotation;
  5206. }
  5207. function d3_geo_rotationφγ(δφ, δγ) {
  5208. var cosδφ = Math.cos(δφ), sinδφ = Math.sin(δφ), cosδγ = Math.cos(δγ), sinδγ = Math.sin(δγ);
  5209. function rotation(λ, φ) {
  5210. var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδφ + x * sinδφ;
  5211. return [ Math.atan2(y * cosδγ - k * sinδγ, x * cosδφ - z * sinδφ), d3_asin(k * cosδγ + y * sinδγ) ];
  5212. }
  5213. rotation.invert = function(λ, φ) {
  5214. var cosφ = Math.cos(φ), x = Math.cos(λ) * cosφ, y = Math.sin(λ) * cosφ, z = Math.sin(φ), k = z * cosδγ - y * sinδγ;
  5215. return [ Math.atan2(y * cosδγ + z * sinδγ, x * cosδφ + k * sinδφ), d3_asin(k * cosδφ - x * sinδφ) ];
  5216. };
  5217. return rotation;
  5218. }
  5219. d3.geo.circle = function() {
  5220. var origin = [ 0, 0 ], angle, precision = 6, interpolate;
  5221. function circle() {
  5222. var center = typeof origin === "function" ? origin.apply(this, arguments) : origin, rotate = d3_geo_rotation(-center[0] * d3_radians, -center[1] * d3_radians, 0).invert, ring = [];
  5223. interpolate(null, null, 1, {
  5224. point: function(x, y) {
  5225. ring.push(x = rotate(x, y));
  5226. x[0] *= d3_degrees, x[1] *= d3_degrees;
  5227. }
  5228. });
  5229. return {
  5230. type: "Polygon",
  5231. coordinates: [ ring ]
  5232. };
  5233. }
  5234. circle.origin = function(x) {
  5235. if (!arguments.length) return origin;
  5236. origin = x;
  5237. return circle;
  5238. };
  5239. circle.angle = function(x) {
  5240. if (!arguments.length) return angle;
  5241. interpolate = d3_geo_circleInterpolate((angle = +x) * d3_radians, precision * d3_radians);
  5242. return circle;
  5243. };
  5244. circle.precision = function(_) {
  5245. if (!arguments.length) return precision;
  5246. interpolate = d3_geo_circleInterpolate(angle * d3_radians, (precision = +_) * d3_radians);
  5247. return circle;
  5248. };
  5249. return circle.angle(90);
  5250. };
  5251. function d3_geo_circleInterpolate(radius, precision) {
  5252. var cr = Math.cos(radius), sr = Math.sin(radius);
  5253. return function(from, to, direction, listener) {
  5254. var step = direction * precision;
  5255. if (from != null) {
  5256. from = d3_geo_circleAngle(cr, from);
  5257. to = d3_geo_circleAngle(cr, to);
  5258. if (direction > 0 ? from < to : from > to) from += direction * τ;
  5259. } else {
  5260. from = radius + direction * τ;
  5261. to = radius - .5 * step;
  5262. }
  5263. for (var point, t = from; direction > 0 ? t > to : t < to; t -= step) {
  5264. listener.point((point = d3_geo_spherical([ cr, -sr * Math.cos(t), -sr * Math.sin(t) ]))[0], point[1]);
  5265. }
  5266. };
  5267. }
  5268. function d3_geo_circleAngle(cr, point) {
  5269. var a = d3_geo_cartesian(point);
  5270. a[0] -= cr;
  5271. d3_geo_cartesianNormalize(a);
  5272. var angle = d3_acos(-a[1]);
  5273. return ((-a[2] < 0 ? -angle : angle) + 2 * Math.PI - ε) % (2 * Math.PI);
  5274. }
  5275. d3.geo.distance = function(a, b) {
  5276. var Δλ = (b[0] - a[0]) * d3_radians, φ0 = a[1] * d3_radians, φ1 = b[1] * d3_radians, sinΔλ = Math.sin(Δλ), cosΔλ = Math.cos(Δλ), sinφ0 = Math.sin(φ0), cosφ0 = Math.cos(φ0), sinφ1 = Math.sin(φ1), cosφ1 = Math.cos(φ1), t;
  5277. return Math.atan2(Math.sqrt((t = cosφ1 * sinΔλ) * t + (t = cosφ0 * sinφ1 - sinφ0 * cosφ1 * cosΔλ) * t), sinφ0 * sinφ1 + cosφ0 * cosφ1 * cosΔλ);
  5278. };
  5279. d3.geo.graticule = function() {
  5280. var x1, x0, X1, X0, y1, y0, Y1, Y0, dx = 10, dy = dx, DX = 90, DY = 360, x, y, X, Y, precision = 2.5;
  5281. function graticule() {
  5282. return {
  5283. type: "MultiLineString",
  5284. coordinates: lines()
  5285. };
  5286. }
  5287. function lines() {
  5288. return d3.range(Math.ceil(X0 / DX) * DX, X1, DX).map(X).concat(d3.range(Math.ceil(Y0 / DY) * DY, Y1, DY).map(Y)).concat(d3.range(Math.ceil(x0 / dx) * dx, x1, dx).filter(function(x) {
  5289. return abs(x % DX) > ε;
  5290. }).map(x)).concat(d3.range(Math.ceil(y0 / dy) * dy, y1, dy).filter(function(y) {
  5291. return abs(y % DY) > ε;
  5292. }).map(y));
  5293. }
  5294. graticule.lines = function() {
  5295. return lines().map(function(coordinates) {
  5296. return {
  5297. type: "LineString",
  5298. coordinates: coordinates
  5299. };
  5300. });
  5301. };
  5302. graticule.outline = function() {
  5303. return {
  5304. type: "Polygon",
  5305. coordinates: [ X(X0).concat(Y(Y1).slice(1), X(X1).reverse().slice(1), Y(Y0).reverse().slice(1)) ]
  5306. };
  5307. };
  5308. graticule.extent = function(_) {
  5309. if (!arguments.length) return graticule.minorExtent();
  5310. return graticule.majorExtent(_).minorExtent(_);
  5311. };
  5312. graticule.majorExtent = function(_) {
  5313. if (!arguments.length) return [ [ X0, Y0 ], [ X1, Y1 ] ];
  5314. X0 = +_[0][0], X1 = +_[1][0];
  5315. Y0 = +_[0][1], Y1 = +_[1][1];
  5316. if (X0 > X1) _ = X0, X0 = X1, X1 = _;
  5317. if (Y0 > Y1) _ = Y0, Y0 = Y1, Y1 = _;
  5318. return graticule.precision(precision);
  5319. };
  5320. graticule.minorExtent = function(_) {
  5321. if (!arguments.length) return [ [ x0, y0 ], [ x1, y1 ] ];
  5322. x0 = +_[0][0], x1 = +_[1][0];
  5323. y0 = +_[0][1], y1 = +_[1][1];
  5324. if (x0 > x1) _ = x0, x0 = x1, x1 = _;
  5325. if (y0 > y1) _ = y0, y0 = y1, y1 = _;
  5326. return graticule.precision(precision);
  5327. };
  5328. graticule.step = function(_) {
  5329. if (!arguments.length) return graticule.minorStep();
  5330. return graticule.majorStep(_).minorStep(_);
  5331. };
  5332. graticule.majorStep = function(_) {
  5333. if (!arguments.length) return [ DX, DY ];
  5334. DX = +_[0], DY = +_[1];
  5335. return graticule;
  5336. };
  5337. graticule.minorStep = function(_) {
  5338. if (!arguments.length) return [ dx, dy ];
  5339. dx = +_[0], dy = +_[1];
  5340. return graticule;
  5341. };
  5342. graticule.precision = function(_) {
  5343. if (!arguments.length) return precision;
  5344. precision = +_;
  5345. x = d3_geo_graticuleX(y0, y1, 90);
  5346. y = d3_geo_graticuleY(x0, x1, precision);
  5347. X = d3_geo_graticuleX(Y0, Y1, 90);
  5348. Y = d3_geo_graticuleY(X0, X1, precision);
  5349. return graticule;
  5350. };
  5351. return graticule.majorExtent([ [ -180, -90 + ε ], [ 180, 90 - ε ] ]).minorExtent([ [ -180, -80 - ε ], [ 180, 80 + ε ] ]);
  5352. };
  5353. function d3_geo_graticuleX(y0, y1, dy) {
  5354. var y = d3.range(y0, y1 - ε, dy).concat(y1);
  5355. return function(x) {
  5356. return y.map(function(y) {
  5357. return [ x, y ];
  5358. });
  5359. };
  5360. }
  5361. function d3_geo_graticuleY(x0, x1, dx) {
  5362. var x = d3.range(x0, x1 - ε, dx).concat(x1);
  5363. return function(y) {
  5364. return x.map(function(x) {
  5365. return [ x, y ];
  5366. });
  5367. };
  5368. }
  5369. function d3_source(d) {
  5370. return d.source;
  5371. }
  5372. function d3_target(d) {
  5373. return d.target;
  5374. }
  5375. d3.geo.greatArc = function() {
  5376. var source = d3_source, source_, target = d3_target, target_;
  5377. function greatArc() {
  5378. return {
  5379. type: "LineString",
  5380. coordinates: [ source_ || source.apply(this, arguments), target_ || target.apply(this, arguments) ]
  5381. };
  5382. }
  5383. greatArc.distance = function() {
  5384. return d3.geo.distance(source_ || source.apply(this, arguments), target_ || target.apply(this, arguments));
  5385. };
  5386. greatArc.source = function(_) {
  5387. if (!arguments.length) return source;
  5388. source = _, source_ = typeof _ === "function" ? null : _;
  5389. return greatArc;
  5390. };
  5391. greatArc.target = function(_) {
  5392. if (!arguments.length) return target;
  5393. target = _, target_ = typeof _ === "function" ? null : _;
  5394. return greatArc;
  5395. };
  5396. greatArc.precision = function() {
  5397. return arguments.length ? greatArc : 0;
  5398. };
  5399. return greatArc;
  5400. };
  5401. d3.geo.interpolate = function(source, target) {
  5402. return d3_geo_interpolate(source[0] * d3_radians, source[1] * d3_radians, target[0] * d3_radians, target[1] * d3_radians);
  5403. };
  5404. function d3_geo_interpolate(x0, y0, x1, y1) {
  5405. var cy0 = Math.cos(y0), sy0 = Math.sin(y0), cy1 = Math.cos(y1), sy1 = Math.sin(y1), kx0 = cy0 * Math.cos(x0), ky0 = cy0 * Math.sin(x0), kx1 = cy1 * Math.cos(x1), ky1 = cy1 * Math.sin(x1), d = 2 * Math.asin(Math.sqrt(d3_haversin(y1 - y0) + cy0 * cy1 * d3_haversin(x1 - x0))), k = 1 / Math.sin(d);
  5406. var interpolate = d ? function(t) {
  5407. var B = Math.sin(t *= d) * k, A = Math.sin(d - t) * k, x = A * kx0 + B * kx1, y = A * ky0 + B * ky1, z = A * sy0 + B * sy1;
  5408. return [ Math.atan2(y, x) * d3_degrees, Math.atan2(z, Math.sqrt(x * x + y * y)) * d3_degrees ];
  5409. } : function() {
  5410. return [ x0 * d3_degrees, y0 * d3_degrees ];
  5411. };
  5412. interpolate.distance = d;
  5413. return interpolate;
  5414. }
  5415. d3.geo.length = function(object) {
  5416. d3_geo_lengthSum = 0;
  5417. d3.geo.stream(object, d3_geo_length);
  5418. return d3_geo_lengthSum;
  5419. };
  5420. var d3_geo_lengthSum;
  5421. var d3_geo_length = {
  5422. sphere: d3_noop,
  5423. point: d3_noop,
  5424. lineStart: d3_geo_lengthLineStart,
  5425. lineEnd: d3_noop,
  5426. polygonStart: d3_noop,
  5427. polygonEnd: d3_noop
  5428. };
  5429. function d3_geo_lengthLineStart() {
  5430. var λ0, sinφ0, cosφ0;
  5431. d3_geo_length.point = function(λ, φ) {
  5432. λ0 = λ * d3_radians, sinφ0 = Math.sin(φ *= d3_radians), cosφ0 = Math.cos(φ);
  5433. d3_geo_length.point = nextPoint;
  5434. };
  5435. d3_geo_length.lineEnd = function() {
  5436. d3_geo_length.point = d3_geo_length.lineEnd = d3_noop;
  5437. };
  5438. function nextPoint(λ, φ) {
  5439. var sinφ = Math.sin(φ *= d3_radians), cosφ = Math.cos(φ), t = abs((λ *= d3_radians) - λ0), cosΔλ = Math.cos(t);
  5440. d3_geo_lengthSum += Math.atan2(Math.sqrt((t = cosφ * Math.sin(t)) * t + (t = cosφ0 * sinφ - sinφ0 * cosφ * cosΔλ) * t), sinφ0 * sinφ + cosφ0 * cosφ * cosΔλ);
  5441. λ0 = λ, sinφ0 = sinφ, cosφ0 = cosφ;
  5442. }
  5443. }
  5444. function d3_geo_azimuthal(scale, angle) {
  5445. function azimuthal(λ, φ) {
  5446. var cosλ = Math.cos(λ), cosφ = Math.cos(φ), k = scale(cosλ * cosφ);
  5447. return [ k * cosφ * Math.sin(λ), k * Math.sin(φ) ];
  5448. }
  5449. azimuthal.invert = function(x, y) {
  5450. var ρ = Math.sqrt(x * x + y * y), c = angle(ρ), sinc = Math.sin(c), cosc = Math.cos(c);
  5451. return [ Math.atan2(x * sinc, ρ * cosc), Math.asin(ρ && y * sinc / ρ) ];
  5452. };
  5453. return azimuthal;
  5454. }
  5455. var d3_geo_azimuthalEqualArea = d3_geo_azimuthal(function(cosλcosφ) {
  5456. return Math.sqrt(2 / (1 + cosλcosφ));
  5457. }, function(ρ) {
  5458. return 2 * Math.asin(ρ / 2);
  5459. });
  5460. (d3.geo.azimuthalEqualArea = function() {
  5461. return d3_geo_projection(d3_geo_azimuthalEqualArea);
  5462. }).raw = d3_geo_azimuthalEqualArea;
  5463. var d3_geo_azimuthalEquidistant = d3_geo_azimuthal(function(cosλcosφ) {
  5464. var c = Math.acos(cosλcosφ);
  5465. return c && c / Math.sin(c);
  5466. }, d3_identity);
  5467. (d3.geo.azimuthalEquidistant = function() {
  5468. return d3_geo_projection(d3_geo_azimuthalEquidistant);
  5469. }).raw = d3_geo_azimuthalEquidistant;
  5470. function d3_geo_conicConformal(φ0, φ1) {
  5471. var cosφ0 = Math.cos(φ0), t = function(φ) {
  5472. return Math.tan(π / 4 + φ / 2);
  5473. }, n = φ0 === φ1 ? Math.sin(φ0) : Math.log(cosφ0 / Math.cos(φ1)) / Math.log(t(φ1) / t(φ0)), F = cosφ0 * Math.pow(t(φ0), n) / n;
  5474. if (!n) return d3_geo_mercator;
  5475. function forward(λ, φ) {
  5476. if (F > 0) {
  5477. if (φ < -halfπ + ε) φ = -halfπ + ε;
  5478. } else {
  5479. if (φ > halfπ - ε) φ = halfπ - ε;
  5480. }
  5481. var ρ = F / Math.pow(t(φ), n);
  5482. return [ ρ * Math.sin(n * λ), F - ρ * Math.cos(n * λ) ];
  5483. }
  5484. forward.invert = function(x, y) {
  5485. var ρ0_y = F - y, ρ = d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y);
  5486. return [ Math.atan2(x, ρ0_y) / n, 2 * Math.atan(Math.pow(F / ρ, 1 / n)) - halfπ ];
  5487. };
  5488. return forward;
  5489. }
  5490. (d3.geo.conicConformal = function() {
  5491. return d3_geo_conic(d3_geo_conicConformal);
  5492. }).raw = d3_geo_conicConformal;
  5493. function d3_geo_conicEquidistant(φ0, φ1) {
  5494. var cosφ0 = Math.cos(φ0), n = φ0 === φ1 ? Math.sin(φ0) : (cosφ0 - Math.cos(φ1)) / (φ1 - φ0), G = cosφ0 / n + φ0;
  5495. if (abs(n) < ε) return d3_geo_equirectangular;
  5496. function forward(λ, φ) {
  5497. var ρ = G - φ;
  5498. return [ ρ * Math.sin(n * λ), G - ρ * Math.cos(n * λ) ];
  5499. }
  5500. forward.invert = function(x, y) {
  5501. var ρ0_y = G - y;
  5502. return [ Math.atan2(x, ρ0_y) / n, G - d3_sgn(n) * Math.sqrt(x * x + ρ0_y * ρ0_y) ];
  5503. };
  5504. return forward;
  5505. }
  5506. (d3.geo.conicEquidistant = function() {
  5507. return d3_geo_conic(d3_geo_conicEquidistant);
  5508. }).raw = d3_geo_conicEquidistant;
  5509. var d3_geo_gnomonic = d3_geo_azimuthal(function(cosλcosφ) {
  5510. return 1 / cosλcosφ;
  5511. }, Math.atan);
  5512. (d3.geo.gnomonic = function() {
  5513. return d3_geo_projection(d3_geo_gnomonic);
  5514. }).raw = d3_geo_gnomonic;
  5515. function d3_geo_mercator(λ, φ) {
  5516. return [ λ, Math.log(Math.tan(π / 4 + φ / 2)) ];
  5517. }
  5518. d3_geo_mercator.invert = function(x, y) {
  5519. return [ x, 2 * Math.atan(Math.exp(y)) - halfπ ];
  5520. };
  5521. function d3_geo_mercatorProjection(project) {
  5522. var m = d3_geo_projection(project), scale = m.scale, translate = m.translate, clipExtent = m.clipExtent, clipAuto;
  5523. m.scale = function() {
  5524. var v = scale.apply(m, arguments);
  5525. return v === m ? clipAuto ? m.clipExtent(null) : m : v;
  5526. };
  5527. m.translate = function() {
  5528. var v = translate.apply(m, arguments);
  5529. return v === m ? clipAuto ? m.clipExtent(null) : m : v;
  5530. };
  5531. m.clipExtent = function(_) {
  5532. var v = clipExtent.apply(m, arguments);
  5533. if (v === m) {
  5534. if (clipAuto = _ == null) {
  5535. var k = π * scale(), t = translate();
  5536. clipExtent([ [ t[0] - k, t[1] - k ], [ t[0] + k, t[1] + k ] ]);
  5537. }
  5538. } else if (clipAuto) {
  5539. v = null;
  5540. }
  5541. return v;
  5542. };
  5543. return m.clipExtent(null);
  5544. }
  5545. (d3.geo.mercator = function() {
  5546. return d3_geo_mercatorProjection(d3_geo_mercator);
  5547. }).raw = d3_geo_mercator;
  5548. var d3_geo_orthographic = d3_geo_azimuthal(function() {
  5549. return 1;
  5550. }, Math.asin);
  5551. (d3.geo.orthographic = function() {
  5552. return d3_geo_projection(d3_geo_orthographic);
  5553. }).raw = d3_geo_orthographic;
  5554. var d3_geo_stereographic = d3_geo_azimuthal(function(cosλcosφ) {
  5555. return 1 / (1 + cosλcosφ);
  5556. }, function(ρ) {
  5557. return 2 * Math.atan(ρ);
  5558. });
  5559. (d3.geo.stereographic = function() {
  5560. return d3_geo_projection(d3_geo_stereographic);
  5561. }).raw = d3_geo_stereographic;
  5562. function d3_geo_transverseMercator(λ, φ) {
  5563. return [ Math.log(Math.tan(π / 4 + φ / 2)), -λ ];
  5564. }
  5565. d3_geo_transverseMercator.invert = function(x, y) {
  5566. return [ -y, 2 * Math.atan(Math.exp(x)) - halfπ ];
  5567. };
  5568. (d3.geo.transverseMercator = function() {
  5569. var projection = d3_geo_mercatorProjection(d3_geo_transverseMercator), center = projection.center, rotate = projection.rotate;
  5570. projection.center = function(_) {
  5571. return _ ? center([ -_[1], _[0] ]) : (_ = center(), [ _[1], -_[0] ]);
  5572. };
  5573. projection.rotate = function(_) {
  5574. return _ ? rotate([ _[0], _[1], _.length > 2 ? _[2] + 90 : 90 ]) : (_ = rotate(),
  5575. [ _[0], _[1], _[2] - 90 ]);
  5576. };
  5577. return rotate([ 0, 0, 90 ]);
  5578. }).raw = d3_geo_transverseMercator;
  5579. d3.geom = {};
  5580. function d3_geom_pointX(d) {
  5581. return d[0];
  5582. }
  5583. function d3_geom_pointY(d) {
  5584. return d[1];
  5585. }
  5586. d3.geom.hull = function(vertices) {
  5587. var x = d3_geom_pointX, y = d3_geom_pointY;
  5588. if (arguments.length) return hull(vertices);
  5589. function hull(data) {
  5590. if (data.length < 3) return [];
  5591. var fx = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = [];
  5592. for (i = 0; i < n; i++) {
  5593. points.push([ +fx.call(this, data[i], i), +fy.call(this, data[i], i), i ]);
  5594. }
  5595. points.sort(d3_geom_hullOrder);
  5596. for (i = 0; i < n; i++) flippedPoints.push([ points[i][0], -points[i][1] ]);
  5597. var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints);
  5598. var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon = [];
  5599. for (i = upper.length - 1; i >= 0; --i) polygon.push(data[points[upper[i]][2]]);
  5600. for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon.push(data[points[lower[i]][2]]);
  5601. return polygon;
  5602. }
  5603. hull.x = function(_) {
  5604. return arguments.length ? (x = _, hull) : x;
  5605. };
  5606. hull.y = function(_) {
  5607. return arguments.length ? (y = _, hull) : y;
  5608. };
  5609. return hull;
  5610. };
  5611. function d3_geom_hullUpper(points) {
  5612. var n = points.length, hull = [ 0, 1 ], hs = 2;
  5613. for (var i = 2; i < n; i++) {
  5614. while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs;
  5615. hull[hs++] = i;
  5616. }
  5617. return hull.slice(0, hs);
  5618. }
  5619. function d3_geom_hullOrder(a, b) {
  5620. return a[0] - b[0] || a[1] - b[1];
  5621. }
  5622. d3.geom.polygon = function(coordinates) {
  5623. d3_subclass(coordinates, d3_geom_polygonPrototype);
  5624. return coordinates;
  5625. };
  5626. var d3_geom_polygonPrototype = d3.geom.polygon.prototype = [];
  5627. d3_geom_polygonPrototype.area = function() {
  5628. var i = -1, n = this.length, a, b = this[n - 1], area = 0;
  5629. while (++i < n) {
  5630. a = b;
  5631. b = this[i];
  5632. area += a[1] * b[0] - a[0] * b[1];
  5633. }
  5634. return area * .5;
  5635. };
  5636. d3_geom_polygonPrototype.centroid = function(k) {
  5637. var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c;
  5638. if (!arguments.length) k = -1 / (6 * this.area());
  5639. while (++i < n) {
  5640. a = b;
  5641. b = this[i];
  5642. c = a[0] * b[1] - b[0] * a[1];
  5643. x += (a[0] + b[0]) * c;
  5644. y += (a[1] + b[1]) * c;
  5645. }
  5646. return [ x * k, y * k ];
  5647. };
  5648. d3_geom_polygonPrototype.clip = function(subject) {
  5649. var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d;
  5650. while (++i < n) {
  5651. input = subject.slice();
  5652. subject.length = 0;
  5653. b = this[i];
  5654. c = input[(m = input.length - closed) - 1];
  5655. j = -1;
  5656. while (++j < m) {
  5657. d = input[j];
  5658. if (d3_geom_polygonInside(d, a, b)) {
  5659. if (!d3_geom_polygonInside(c, a, b)) {
  5660. subject.push(d3_geom_polygonIntersect(c, d, a, b));
  5661. }
  5662. subject.push(d);
  5663. } else if (d3_geom_polygonInside(c, a, b)) {
  5664. subject.push(d3_geom_polygonIntersect(c, d, a, b));
  5665. }
  5666. c = d;
  5667. }
  5668. if (closed) subject.push(subject[0]);
  5669. a = b;
  5670. }
  5671. return subject;
  5672. };
  5673. function d3_geom_polygonInside(p, a, b) {
  5674. return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]);
  5675. }
  5676. function d3_geom_polygonIntersect(c, d, a, b) {
  5677. var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21);
  5678. return [ x1 + ua * x21, y1 + ua * y21 ];
  5679. }
  5680. function d3_geom_polygonClosed(coordinates) {
  5681. var a = coordinates[0], b = coordinates[coordinates.length - 1];
  5682. return !(a[0] - b[0] || a[1] - b[1]);
  5683. }
  5684. var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = [];
  5685. function d3_geom_voronoiBeach() {
  5686. d3_geom_voronoiRedBlackNode(this);
  5687. this.edge = this.site = this.circle = null;
  5688. }
  5689. function d3_geom_voronoiCreateBeach(site) {
  5690. var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach();
  5691. beach.site = site;
  5692. return beach;
  5693. }
  5694. function d3_geom_voronoiDetachBeach(beach) {
  5695. d3_geom_voronoiDetachCircle(beach);
  5696. d3_geom_voronoiBeaches.remove(beach);
  5697. d3_geom_voronoiBeachPool.push(beach);
  5698. d3_geom_voronoiRedBlackNode(beach);
  5699. }
  5700. function d3_geom_voronoiRemoveBeach(beach) {
  5701. var circle = beach.circle, x = circle.x, y = circle.cy, vertex = {
  5702. x: x,
  5703. y: y
  5704. }, previous = beach.P, next = beach.N, disappearing = [ beach ];
  5705. d3_geom_voronoiDetachBeach(beach);
  5706. var lArc = previous;
  5707. while (lArc.circle && abs(x - lArc.circle.x) < ε && abs(y - lArc.circle.cy) < ε) {
  5708. previous = lArc.P;
  5709. disappearing.unshift(lArc);
  5710. d3_geom_voronoiDetachBeach(lArc);
  5711. lArc = previous;
  5712. }
  5713. disappearing.unshift(lArc);
  5714. d3_geom_voronoiDetachCircle(lArc);
  5715. var rArc = next;
  5716. while (rArc.circle && abs(x - rArc.circle.x) < ε && abs(y - rArc.circle.cy) < ε) {
  5717. next = rArc.N;
  5718. disappearing.push(rArc);
  5719. d3_geom_voronoiDetachBeach(rArc);
  5720. rArc = next;
  5721. }
  5722. disappearing.push(rArc);
  5723. d3_geom_voronoiDetachCircle(rArc);
  5724. var nArcs = disappearing.length, iArc;
  5725. for (iArc = 1; iArc < nArcs; ++iArc) {
  5726. rArc = disappearing[iArc];
  5727. lArc = disappearing[iArc - 1];
  5728. d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex);
  5729. }
  5730. lArc = disappearing[0];
  5731. rArc = disappearing[nArcs - 1];
  5732. rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex);
  5733. d3_geom_voronoiAttachCircle(lArc);
  5734. d3_geom_voronoiAttachCircle(rArc);
  5735. }
  5736. function d3_geom_voronoiAddBeach(site) {
  5737. var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._;
  5738. while (node) {
  5739. dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x;
  5740. if (dxl > ε) node = node.L; else {
  5741. dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix);
  5742. if (dxr > ε) {
  5743. if (!node.R) {
  5744. lArc = node;
  5745. break;
  5746. }
  5747. node = node.R;
  5748. } else {
  5749. if (dxl > -ε) {
  5750. lArc = node.P;
  5751. rArc = node;
  5752. } else if (dxr > -ε) {
  5753. lArc = node;
  5754. rArc = node.N;
  5755. } else {
  5756. lArc = rArc = node;
  5757. }
  5758. break;
  5759. }
  5760. }
  5761. }
  5762. var newArc = d3_geom_voronoiCreateBeach(site);
  5763. d3_geom_voronoiBeaches.insert(lArc, newArc);
  5764. if (!lArc && !rArc) return;
  5765. if (lArc === rArc) {
  5766. d3_geom_voronoiDetachCircle(lArc);
  5767. rArc = d3_geom_voronoiCreateBeach(lArc.site);
  5768. d3_geom_voronoiBeaches.insert(newArc, rArc);
  5769. newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
  5770. d3_geom_voronoiAttachCircle(lArc);
  5771. d3_geom_voronoiAttachCircle(rArc);
  5772. return;
  5773. }
  5774. if (!rArc) {
  5775. newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site);
  5776. return;
  5777. }
  5778. d3_geom_voronoiDetachCircle(lArc);
  5779. d3_geom_voronoiDetachCircle(rArc);
  5780. var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = {
  5781. x: (cy * hb - by * hc) / d + ax,
  5782. y: (bx * hc - cx * hb) / d + ay
  5783. };
  5784. d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex);
  5785. newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex);
  5786. rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex);
  5787. d3_geom_voronoiAttachCircle(lArc);
  5788. d3_geom_voronoiAttachCircle(rArc);
  5789. }
  5790. function d3_geom_voronoiLeftBreakPoint(arc, directrix) {
  5791. var site = arc.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix;
  5792. if (!pby2) return rfocx;
  5793. var lArc = arc.P;
  5794. if (!lArc) return -Infinity;
  5795. site = lArc.site;
  5796. var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix;
  5797. if (!plby2) return lfocx;
  5798. var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2;
  5799. if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx;
  5800. return (rfocx + lfocx) / 2;
  5801. }
  5802. function d3_geom_voronoiRightBreakPoint(arc, directrix) {
  5803. var rArc = arc.N;
  5804. if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix);
  5805. var site = arc.site;
  5806. return site.y === directrix ? site.x : Infinity;
  5807. }
  5808. function d3_geom_voronoiCell(site) {
  5809. this.site = site;
  5810. this.edges = [];
  5811. }
  5812. d3_geom_voronoiCell.prototype.prepare = function() {
  5813. var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge;
  5814. while (iHalfEdge--) {
  5815. edge = halfEdges[iHalfEdge].edge;
  5816. if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1);
  5817. }
  5818. halfEdges.sort(d3_geom_voronoiHalfEdgeOrder);
  5819. return halfEdges.length;
  5820. };
  5821. function d3_geom_voronoiCloseCells(extent) {
  5822. var x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end;
  5823. while (iCell--) {
  5824. cell = cells[iCell];
  5825. if (!cell || !cell.prepare()) continue;
  5826. halfEdges = cell.edges;
  5827. nHalfEdges = halfEdges.length;
  5828. iHalfEdge = 0;
  5829. while (iHalfEdge < nHalfEdges) {
  5830. end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y;
  5831. start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y;
  5832. if (abs(x3 - x2) > ε || abs(y3 - y2) > ε) {
  5833. halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs(x3 - x0) < ε && y1 - y3 > ε ? {
  5834. x: x0,
  5835. y: abs(x2 - x0) < ε ? y2 : y1
  5836. } : abs(y3 - y1) < ε && x1 - x3 > ε ? {
  5837. x: abs(y2 - y1) < ε ? x2 : x1,
  5838. y: y1
  5839. } : abs(x3 - x1) < ε && y3 - y0 > ε ? {
  5840. x: x1,
  5841. y: abs(x2 - x1) < ε ? y2 : y0
  5842. } : abs(y3 - y0) < ε && x3 - x0 > ε ? {
  5843. x: abs(y2 - y0) < ε ? x2 : x0,
  5844. y: y0
  5845. } : null), cell.site, null));
  5846. ++nHalfEdges;
  5847. }
  5848. }
  5849. }
  5850. }
  5851. function d3_geom_voronoiHalfEdgeOrder(a, b) {
  5852. return b.angle - a.angle;
  5853. }
  5854. function d3_geom_voronoiCircle() {
  5855. d3_geom_voronoiRedBlackNode(this);
  5856. this.x = this.y = this.arc = this.site = this.cy = null;
  5857. }
  5858. function d3_geom_voronoiAttachCircle(arc) {
  5859. var lArc = arc.P, rArc = arc.N;
  5860. if (!lArc || !rArc) return;
  5861. var lSite = lArc.site, cSite = arc.site, rSite = rArc.site;
  5862. if (lSite === rSite) return;
  5863. var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by;
  5864. var d = 2 * (ax * cy - ay * cx);
  5865. if (d >= -ε2) return;
  5866. var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by;
  5867. var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle();
  5868. circle.arc = arc;
  5869. circle.site = cSite;
  5870. circle.x = x + bx;
  5871. circle.y = cy + Math.sqrt(x * x + y * y);
  5872. circle.cy = cy;
  5873. arc.circle = circle;
  5874. var before = null, node = d3_geom_voronoiCircles._;
  5875. while (node) {
  5876. if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) {
  5877. if (node.L) node = node.L; else {
  5878. before = node.P;
  5879. break;
  5880. }
  5881. } else {
  5882. if (node.R) node = node.R; else {
  5883. before = node;
  5884. break;
  5885. }
  5886. }
  5887. }
  5888. d3_geom_voronoiCircles.insert(before, circle);
  5889. if (!before) d3_geom_voronoiFirstCircle = circle;
  5890. }
  5891. function d3_geom_voronoiDetachCircle(arc) {
  5892. var circle = arc.circle;
  5893. if (circle) {
  5894. if (!circle.P) d3_geom_voronoiFirstCircle = circle.N;
  5895. d3_geom_voronoiCircles.remove(circle);
  5896. d3_geom_voronoiCirclePool.push(circle);
  5897. d3_geom_voronoiRedBlackNode(circle);
  5898. arc.circle = null;
  5899. }
  5900. }
  5901. function d3_geom_voronoiClipEdges(extent) {
  5902. var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent[0][0], extent[0][1], extent[1][0], extent[1][1]), i = edges.length, e;
  5903. while (i--) {
  5904. e = edges[i];
  5905. if (!d3_geom_voronoiConnectEdge(e, extent) || !clip(e) || abs(e.a.x - e.b.x) < ε && abs(e.a.y - e.b.y) < ε) {
  5906. e.a = e.b = null;
  5907. edges.splice(i, 1);
  5908. }
  5909. }
  5910. }
  5911. function d3_geom_voronoiConnectEdge(edge, extent) {
  5912. var vb = edge.b;
  5913. if (vb) return true;
  5914. var va = edge.a, x0 = extent[0][0], x1 = extent[1][0], y0 = extent[0][1], y1 = extent[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb;
  5915. if (ry === ly) {
  5916. if (fx < x0 || fx >= x1) return;
  5917. if (lx > rx) {
  5918. if (!va) va = {
  5919. x: fx,
  5920. y: y0
  5921. }; else if (va.y >= y1) return;
  5922. vb = {
  5923. x: fx,
  5924. y: y1
  5925. };
  5926. } else {
  5927. if (!va) va = {
  5928. x: fx,
  5929. y: y1
  5930. }; else if (va.y < y0) return;
  5931. vb = {
  5932. x: fx,
  5933. y: y0
  5934. };
  5935. }
  5936. } else {
  5937. fm = (lx - rx) / (ry - ly);
  5938. fb = fy - fm * fx;
  5939. if (fm < -1 || fm > 1) {
  5940. if (lx > rx) {
  5941. if (!va) va = {
  5942. x: (y0 - fb) / fm,
  5943. y: y0
  5944. }; else if (va.y >= y1) return;
  5945. vb = {
  5946. x: (y1 - fb) / fm,
  5947. y: y1
  5948. };
  5949. } else {
  5950. if (!va) va = {
  5951. x: (y1 - fb) / fm,
  5952. y: y1
  5953. }; else if (va.y < y0) return;
  5954. vb = {
  5955. x: (y0 - fb) / fm,
  5956. y: y0
  5957. };
  5958. }
  5959. } else {
  5960. if (ly < ry) {
  5961. if (!va) va = {
  5962. x: x0,
  5963. y: fm * x0 + fb
  5964. }; else if (va.x >= x1) return;
  5965. vb = {
  5966. x: x1,
  5967. y: fm * x1 + fb
  5968. };
  5969. } else {
  5970. if (!va) va = {
  5971. x: x1,
  5972. y: fm * x1 + fb
  5973. }; else if (va.x < x0) return;
  5974. vb = {
  5975. x: x0,
  5976. y: fm * x0 + fb
  5977. };
  5978. }
  5979. }
  5980. }
  5981. edge.a = va;
  5982. edge.b = vb;
  5983. return true;
  5984. }
  5985. function d3_geom_voronoiEdge(lSite, rSite) {
  5986. this.l = lSite;
  5987. this.r = rSite;
  5988. this.a = this.b = null;
  5989. }
  5990. function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) {
  5991. var edge = new d3_geom_voronoiEdge(lSite, rSite);
  5992. d3_geom_voronoiEdges.push(edge);
  5993. if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va);
  5994. if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb);
  5995. d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite));
  5996. d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite));
  5997. return edge;
  5998. }
  5999. function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) {
  6000. var edge = new d3_geom_voronoiEdge(lSite, null);
  6001. edge.a = va;
  6002. edge.b = vb;
  6003. d3_geom_voronoiEdges.push(edge);
  6004. return edge;
  6005. }
  6006. function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) {
  6007. if (!edge.a && !edge.b) {
  6008. edge.a = vertex;
  6009. edge.l = lSite;
  6010. edge.r = rSite;
  6011. } else if (edge.l === rSite) {
  6012. edge.b = vertex;
  6013. } else {
  6014. edge.a = vertex;
  6015. }
  6016. }
  6017. function d3_geom_voronoiHalfEdge(edge, lSite, rSite) {
  6018. var va = edge.a, vb = edge.b;
  6019. this.edge = edge;
  6020. this.site = lSite;
  6021. this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y);
  6022. }
  6023. d3_geom_voronoiHalfEdge.prototype = {
  6024. start: function() {
  6025. return this.edge.l === this.site ? this.edge.a : this.edge.b;
  6026. },
  6027. end: function() {
  6028. return this.edge.l === this.site ? this.edge.b : this.edge.a;
  6029. }
  6030. };
  6031. function d3_geom_voronoiRedBlackTree() {
  6032. this._ = null;
  6033. }
  6034. function d3_geom_voronoiRedBlackNode(node) {
  6035. node.U = node.C = node.L = node.R = node.P = node.N = null;
  6036. }
  6037. d3_geom_voronoiRedBlackTree.prototype = {
  6038. insert: function(after, node) {
  6039. var parent, grandpa, uncle;
  6040. if (after) {
  6041. node.P = after;
  6042. node.N = after.N;
  6043. if (after.N) after.N.P = node;
  6044. after.N = node;
  6045. if (after.R) {
  6046. after = after.R;
  6047. while (after.L) after = after.L;
  6048. after.L = node;
  6049. } else {
  6050. after.R = node;
  6051. }
  6052. parent = after;
  6053. } else if (this._) {
  6054. after = d3_geom_voronoiRedBlackFirst(this._);
  6055. node.P = null;
  6056. node.N = after;
  6057. after.P = after.L = node;
  6058. parent = after;
  6059. } else {
  6060. node.P = node.N = null;
  6061. this._ = node;
  6062. parent = null;
  6063. }
  6064. node.L = node.R = null;
  6065. node.U = parent;
  6066. node.C = true;
  6067. after = node;
  6068. while (parent && parent.C) {
  6069. grandpa = parent.U;
  6070. if (parent === grandpa.L) {
  6071. uncle = grandpa.R;
  6072. if (uncle && uncle.C) {
  6073. parent.C = uncle.C = false;
  6074. grandpa.C = true;
  6075. after = grandpa;
  6076. } else {
  6077. if (after === parent.R) {
  6078. d3_geom_voronoiRedBlackRotateLeft(this, parent);
  6079. after = parent;
  6080. parent = after.U;
  6081. }
  6082. parent.C = false;
  6083. grandpa.C = true;
  6084. d3_geom_voronoiRedBlackRotateRight(this, grandpa);
  6085. }
  6086. } else {
  6087. uncle = grandpa.L;
  6088. if (uncle && uncle.C) {
  6089. parent.C = uncle.C = false;
  6090. grandpa.C = true;
  6091. after = grandpa;
  6092. } else {
  6093. if (after === parent.L) {
  6094. d3_geom_voronoiRedBlackRotateRight(this, parent);
  6095. after = parent;
  6096. parent = after.U;
  6097. }
  6098. parent.C = false;
  6099. grandpa.C = true;
  6100. d3_geom_voronoiRedBlackRotateLeft(this, grandpa);
  6101. }
  6102. }
  6103. parent = after.U;
  6104. }
  6105. this._.C = false;
  6106. },
  6107. remove: function(node) {
  6108. if (node.N) node.N.P = node.P;
  6109. if (node.P) node.P.N = node.N;
  6110. node.N = node.P = null;
  6111. var parent = node.U, sibling, left = node.L, right = node.R, next, red;
  6112. if (!left) next = right; else if (!right) next = left; else next = d3_geom_voronoiRedBlackFirst(right);
  6113. if (parent) {
  6114. if (parent.L === node) parent.L = next; else parent.R = next;
  6115. } else {
  6116. this._ = next;
  6117. }
  6118. if (left && right) {
  6119. red = next.C;
  6120. next.C = node.C;
  6121. next.L = left;
  6122. left.U = next;
  6123. if (next !== right) {
  6124. parent = next.U;
  6125. next.U = node.U;
  6126. node = next.R;
  6127. parent.L = node;
  6128. next.R = right;
  6129. right.U = next;
  6130. } else {
  6131. next.U = parent;
  6132. parent = next;
  6133. node = next.R;
  6134. }
  6135. } else {
  6136. red = node.C;
  6137. node = next;
  6138. }
  6139. if (node) node.U = parent;
  6140. if (red) return;
  6141. if (node && node.C) {
  6142. node.C = false;
  6143. return;
  6144. }
  6145. do {
  6146. if (node === this._) break;
  6147. if (node === parent.L) {
  6148. sibling = parent.R;
  6149. if (sibling.C) {
  6150. sibling.C = false;
  6151. parent.C = true;
  6152. d3_geom_voronoiRedBlackRotateLeft(this, parent);
  6153. sibling = parent.R;
  6154. }
  6155. if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
  6156. if (!sibling.R || !sibling.R.C) {
  6157. sibling.L.C = false;
  6158. sibling.C = true;
  6159. d3_geom_voronoiRedBlackRotateRight(this, sibling);
  6160. sibling = parent.R;
  6161. }
  6162. sibling.C = parent.C;
  6163. parent.C = sibling.R.C = false;
  6164. d3_geom_voronoiRedBlackRotateLeft(this, parent);
  6165. node = this._;
  6166. break;
  6167. }
  6168. } else {
  6169. sibling = parent.L;
  6170. if (sibling.C) {
  6171. sibling.C = false;
  6172. parent.C = true;
  6173. d3_geom_voronoiRedBlackRotateRight(this, parent);
  6174. sibling = parent.L;
  6175. }
  6176. if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) {
  6177. if (!sibling.L || !sibling.L.C) {
  6178. sibling.R.C = false;
  6179. sibling.C = true;
  6180. d3_geom_voronoiRedBlackRotateLeft(this, sibling);
  6181. sibling = parent.L;
  6182. }
  6183. sibling.C = parent.C;
  6184. parent.C = sibling.L.C = false;
  6185. d3_geom_voronoiRedBlackRotateRight(this, parent);
  6186. node = this._;
  6187. break;
  6188. }
  6189. }
  6190. sibling.C = true;
  6191. node = parent;
  6192. parent = parent.U;
  6193. } while (!node.C);
  6194. if (node) node.C = false;
  6195. }
  6196. };
  6197. function d3_geom_voronoiRedBlackRotateLeft(tree, node) {
  6198. var p = node, q = node.R, parent = p.U;
  6199. if (parent) {
  6200. if (parent.L === p) parent.L = q; else parent.R = q;
  6201. } else {
  6202. tree._ = q;
  6203. }
  6204. q.U = parent;
  6205. p.U = q;
  6206. p.R = q.L;
  6207. if (p.R) p.R.U = p;
  6208. q.L = p;
  6209. }
  6210. function d3_geom_voronoiRedBlackRotateRight(tree, node) {
  6211. var p = node, q = node.L, parent = p.U;
  6212. if (parent) {
  6213. if (parent.L === p) parent.L = q; else parent.R = q;
  6214. } else {
  6215. tree._ = q;
  6216. }
  6217. q.U = parent;
  6218. p.U = q;
  6219. p.L = q.R;
  6220. if (p.L) p.L.U = p;
  6221. q.R = p;
  6222. }
  6223. function d3_geom_voronoiRedBlackFirst(node) {
  6224. while (node.L) node = node.L;
  6225. return node;
  6226. }
  6227. function d3_geom_voronoi(sites, bbox) {
  6228. var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle;
  6229. d3_geom_voronoiEdges = [];
  6230. d3_geom_voronoiCells = new Array(sites.length);
  6231. d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree();
  6232. d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree();
  6233. while (true) {
  6234. circle = d3_geom_voronoiFirstCircle;
  6235. if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) {
  6236. if (site.x !== x0 || site.y !== y0) {
  6237. d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site);
  6238. d3_geom_voronoiAddBeach(site);
  6239. x0 = site.x, y0 = site.y;
  6240. }
  6241. site = sites.pop();
  6242. } else if (circle) {
  6243. d3_geom_voronoiRemoveBeach(circle.arc);
  6244. } else {
  6245. break;
  6246. }
  6247. }
  6248. if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox);
  6249. var diagram = {
  6250. cells: d3_geom_voronoiCells,
  6251. edges: d3_geom_voronoiEdges
  6252. };
  6253. d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null;
  6254. return diagram;
  6255. }
  6256. function d3_geom_voronoiVertexOrder(a, b) {
  6257. return b.y - a.y || b.x - a.x;
  6258. }
  6259. d3.geom.voronoi = function(points) {
  6260. var x = d3_geom_pointX, y = d3_geom_pointY, fx = x, fy = y, clipExtent = d3_geom_voronoiClipExtent;
  6261. if (points) return voronoi(points);
  6262. function voronoi(data) {
  6263. var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1];
  6264. d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) {
  6265. var edges = cell.edges, site = cell.site, polygon = polygons[i] = edges.length ? edges.map(function(e) {
  6266. var s = e.start();
  6267. return [ s.x, s.y ];
  6268. }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [ [ x0, y1 ], [ x1, y1 ], [ x1, y0 ], [ x0, y0 ] ] : [];
  6269. polygon.point = data[i];
  6270. });
  6271. return polygons;
  6272. }
  6273. function sites(data) {
  6274. return data.map(function(d, i) {
  6275. return {
  6276. x: Math.round(fx(d, i) / ε) * ε,
  6277. y: Math.round(fy(d, i) / ε) * ε,
  6278. i: i
  6279. };
  6280. });
  6281. }
  6282. voronoi.links = function(data) {
  6283. return d3_geom_voronoi(sites(data)).edges.filter(function(edge) {
  6284. return edge.l && edge.r;
  6285. }).map(function(edge) {
  6286. return {
  6287. source: data[edge.l.i],
  6288. target: data[edge.r.i]
  6289. };
  6290. });
  6291. };
  6292. voronoi.triangles = function(data) {
  6293. var triangles = [];
  6294. d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) {
  6295. var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, e0, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l;
  6296. while (++j < m) {
  6297. e0 = e1;
  6298. s0 = s1;
  6299. e1 = edges[j].edge;
  6300. s1 = e1.l === site ? e1.r : e1.l;
  6301. if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) {
  6302. triangles.push([ data[i], data[s0.i], data[s1.i] ]);
  6303. }
  6304. }
  6305. });
  6306. return triangles;
  6307. };
  6308. voronoi.x = function(_) {
  6309. return arguments.length ? (fx = d3_functor(x = _), voronoi) : x;
  6310. };
  6311. voronoi.y = function(_) {
  6312. return arguments.length ? (fy = d3_functor(y = _), voronoi) : y;
  6313. };
  6314. voronoi.clipExtent = function(_) {
  6315. if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent;
  6316. clipExtent = _ == null ? d3_geom_voronoiClipExtent : _;
  6317. return voronoi;
  6318. };
  6319. voronoi.size = function(_) {
  6320. if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1];
  6321. return voronoi.clipExtent(_ && [ [ 0, 0 ], _ ]);
  6322. };
  6323. return voronoi;
  6324. };
  6325. var d3_geom_voronoiClipExtent = [ [ -1e6, -1e6 ], [ 1e6, 1e6 ] ];
  6326. function d3_geom_voronoiTriangleArea(a, b, c) {
  6327. return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y);
  6328. }
  6329. d3.geom.delaunay = function(vertices) {
  6330. return d3.geom.voronoi().triangles(vertices);
  6331. };
  6332. d3.geom.quadtree = function(points, x1, y1, x2, y2) {
  6333. var x = d3_geom_pointX, y = d3_geom_pointY, compat;
  6334. if (compat = arguments.length) {
  6335. x = d3_geom_quadtreeCompatX;
  6336. y = d3_geom_quadtreeCompatY;
  6337. if (compat === 3) {
  6338. y2 = y1;
  6339. x2 = x1;
  6340. y1 = x1 = 0;
  6341. }
  6342. return quadtree(points);
  6343. }
  6344. function quadtree(data) {
  6345. var d, fx = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_;
  6346. if (x1 != null) {
  6347. x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2;
  6348. } else {
  6349. x2_ = y2_ = -(x1_ = y1_ = Infinity);
  6350. xs = [], ys = [];
  6351. n = data.length;
  6352. if (compat) for (i = 0; i < n; ++i) {
  6353. d = data[i];
  6354. if (d.x < x1_) x1_ = d.x;
  6355. if (d.y < y1_) y1_ = d.y;
  6356. if (d.x > x2_) x2_ = d.x;
  6357. if (d.y > y2_) y2_ = d.y;
  6358. xs.push(d.x);
  6359. ys.push(d.y);
  6360. } else for (i = 0; i < n; ++i) {
  6361. var x_ = +fx(d = data[i], i), y_ = +fy(d, i);
  6362. if (x_ < x1_) x1_ = x_;
  6363. if (y_ < y1_) y1_ = y_;
  6364. if (x_ > x2_) x2_ = x_;
  6365. if (y_ > y2_) y2_ = y_;
  6366. xs.push(x_);
  6367. ys.push(y_);
  6368. }
  6369. }
  6370. var dx = x2_ - x1_, dy = y2_ - y1_;
  6371. if (dx > dy) y2_ = y1_ + dx; else x2_ = x1_ + dy;
  6372. function insert(n, d, x, y, x1, y1, x2, y2) {
  6373. if (isNaN(x) || isNaN(y)) return;
  6374. if (n.leaf) {
  6375. var nx = n.x, ny = n.y;
  6376. if (nx != null) {
  6377. if (abs(nx - x) + abs(ny - y) < .01) {
  6378. insertChild(n, d, x, y, x1, y1, x2, y2);
  6379. } else {
  6380. var nPoint = n.point;
  6381. n.x = n.y = n.point = null;
  6382. insertChild(n, nPoint, nx, ny, x1, y1, x2, y2);
  6383. insertChild(n, d, x, y, x1, y1, x2, y2);
  6384. }
  6385. } else {
  6386. n.x = x, n.y = y, n.point = d;
  6387. }
  6388. } else {
  6389. insertChild(n, d, x, y, x1, y1, x2, y2);
  6390. }
  6391. }
  6392. function insertChild(n, d, x, y, x1, y1, x2, y2) {
  6393. var xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym, i = below << 1 | right;
  6394. n.leaf = false;
  6395. n = n.nodes[i] || (n.nodes[i] = d3_geom_quadtreeNode());
  6396. if (right) x1 = xm; else x2 = xm;
  6397. if (below) y1 = ym; else y2 = ym;
  6398. insert(n, d, x, y, x1, y1, x2, y2);
  6399. }
  6400. var root = d3_geom_quadtreeNode();
  6401. root.add = function(d) {
  6402. insert(root, d, +fx(d, ++i), +fy(d, i), x1_, y1_, x2_, y2_);
  6403. };
  6404. root.visit = function(f) {
  6405. d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_);
  6406. };
  6407. root.find = function(point) {
  6408. return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_);
  6409. };
  6410. i = -1;
  6411. if (x1 == null) {
  6412. while (++i < n) {
  6413. insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_);
  6414. }
  6415. --i;
  6416. } else data.forEach(root.add);
  6417. xs = ys = data = d = null;
  6418. return root;
  6419. }
  6420. quadtree.x = function(_) {
  6421. return arguments.length ? (x = _, quadtree) : x;
  6422. };
  6423. quadtree.y = function(_) {
  6424. return arguments.length ? (y = _, quadtree) : y;
  6425. };
  6426. quadtree.extent = function(_) {
  6427. if (!arguments.length) return x1 == null ? null : [ [ x1, y1 ], [ x2, y2 ] ];
  6428. if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = +_[0][0], y1 = +_[0][1], x2 = +_[1][0],
  6429. y2 = +_[1][1];
  6430. return quadtree;
  6431. };
  6432. quadtree.size = function(_) {
  6433. if (!arguments.length) return x1 == null ? null : [ x2 - x1, y2 - y1 ];
  6434. if (_ == null) x1 = y1 = x2 = y2 = null; else x1 = y1 = 0, x2 = +_[0], y2 = +_[1];
  6435. return quadtree;
  6436. };
  6437. return quadtree;
  6438. };
  6439. function d3_geom_quadtreeCompatX(d) {
  6440. return d.x;
  6441. }
  6442. function d3_geom_quadtreeCompatY(d) {
  6443. return d.y;
  6444. }
  6445. function d3_geom_quadtreeNode() {
  6446. return {
  6447. leaf: true,
  6448. nodes: [],
  6449. point: null,
  6450. x: null,
  6451. y: null
  6452. };
  6453. }
  6454. function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) {
  6455. if (!f(node, x1, y1, x2, y2)) {
  6456. var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5, children = node.nodes;
  6457. if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy);
  6458. if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy);
  6459. if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2);
  6460. if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2);
  6461. }
  6462. }
  6463. function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) {
  6464. var minDistance2 = Infinity, closestPoint;
  6465. (function find(node, x1, y1, x2, y2) {
  6466. if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return;
  6467. if (point = node.point) {
  6468. var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy;
  6469. if (distance2 < minDistance2) {
  6470. var distance = Math.sqrt(minDistance2 = distance2);
  6471. x0 = x - distance, y0 = y - distance;
  6472. x3 = x + distance, y3 = y + distance;
  6473. closestPoint = point;
  6474. }
  6475. }
  6476. var children = node.nodes, xm = (x1 + x2) * .5, ym = (y1 + y2) * .5, right = x >= xm, below = y >= ym;
  6477. for (var i = below << 1 | right, j = i + 4; i < j; ++i) {
  6478. if (node = children[i & 3]) switch (i & 3) {
  6479. case 0:
  6480. find(node, x1, y1, xm, ym);
  6481. break;
  6482. case 1:
  6483. find(node, xm, y1, x2, ym);
  6484. break;
  6485. case 2:
  6486. find(node, x1, ym, xm, y2);
  6487. break;
  6488. case 3:
  6489. find(node, xm, ym, x2, y2);
  6490. break;
  6491. }
  6492. }
  6493. })(root, x0, y0, x3, y3);
  6494. return closestPoint;
  6495. }
  6496. d3.interpolateRgb = d3_interpolateRgb;
  6497. function d3_interpolateRgb(a, b) {
  6498. a = d3.rgb(a);
  6499. b = d3.rgb(b);
  6500. var ar = a.r, ag = a.g, ab = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab;
  6501. return function(t) {
  6502. return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab + bb * t));
  6503. };
  6504. }
  6505. d3.interpolateObject = d3_interpolateObject;
  6506. function d3_interpolateObject(a, b) {
  6507. var i = {}, c = {}, k;
  6508. for (k in a) {
  6509. if (k in b) {
  6510. i[k] = d3_interpolate(a[k], b[k]);
  6511. } else {
  6512. c[k] = a[k];
  6513. }
  6514. }
  6515. for (k in b) {
  6516. if (!(k in a)) {
  6517. c[k] = b[k];
  6518. }
  6519. }
  6520. return function(t) {
  6521. for (k in i) c[k] = i[k](t);
  6522. return c;
  6523. };
  6524. }
  6525. d3.interpolateNumber = d3_interpolateNumber;
  6526. function d3_interpolateNumber(a, b) {
  6527. a = +a, b = +b;
  6528. return function(t) {
  6529. return a * (1 - t) + b * t;
  6530. };
  6531. }
  6532. d3.interpolateString = d3_interpolateString;
  6533. function d3_interpolateString(a, b) {
  6534. var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = [];
  6535. a = a + "", b = b + "";
  6536. while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) {
  6537. if ((bs = bm.index) > bi) {
  6538. bs = b.slice(bi, bs);
  6539. if (s[i]) s[i] += bs; else s[++i] = bs;
  6540. }
  6541. if ((am = am[0]) === (bm = bm[0])) {
  6542. if (s[i]) s[i] += bm; else s[++i] = bm;
  6543. } else {
  6544. s[++i] = null;
  6545. q.push({
  6546. i: i,
  6547. x: d3_interpolateNumber(am, bm)
  6548. });
  6549. }
  6550. bi = d3_interpolate_numberB.lastIndex;
  6551. }
  6552. if (bi < b.length) {
  6553. bs = b.slice(bi);
  6554. if (s[i]) s[i] += bs; else s[++i] = bs;
  6555. }
  6556. return s.length < 2 ? q[0] ? (b = q[0].x, function(t) {
  6557. return b(t) + "";
  6558. }) : function() {
  6559. return b;
  6560. } : (b = q.length, function(t) {
  6561. for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t);
  6562. return s.join("");
  6563. });
  6564. }
  6565. var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g");
  6566. d3.interpolate = d3_interpolate;
  6567. function d3_interpolate(a, b) {
  6568. var i = d3.interpolators.length, f;
  6569. while (--i >= 0 && !(f = d3.interpolators[i](a, b))) ;
  6570. return f;
  6571. }
  6572. d3.interpolators = [ function(a, b) {
  6573. var t = typeof b;
  6574. return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b);
  6575. } ];
  6576. d3.interpolateArray = d3_interpolateArray;
  6577. function d3_interpolateArray(a, b) {
  6578. var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i;
  6579. for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i]));
  6580. for (;i < na; ++i) c[i] = a[i];
  6581. for (;i < nb; ++i) c[i] = b[i];
  6582. return function(t) {
  6583. for (i = 0; i < n0; ++i) c[i] = x[i](t);
  6584. return c;
  6585. };
  6586. }
  6587. var d3_ease_default = function() {
  6588. return d3_identity;
  6589. };
  6590. var d3_ease = d3.map({
  6591. linear: d3_ease_default,
  6592. poly: d3_ease_poly,
  6593. quad: function() {
  6594. return d3_ease_quad;
  6595. },
  6596. cubic: function() {
  6597. return d3_ease_cubic;
  6598. },
  6599. sin: function() {
  6600. return d3_ease_sin;
  6601. },
  6602. exp: function() {
  6603. return d3_ease_exp;
  6604. },
  6605. circle: function() {
  6606. return d3_ease_circle;
  6607. },
  6608. elastic: d3_ease_elastic,
  6609. back: d3_ease_back,
  6610. bounce: function() {
  6611. return d3_ease_bounce;
  6612. }
  6613. });
  6614. var d3_ease_mode = d3.map({
  6615. "in": d3_identity,
  6616. out: d3_ease_reverse,
  6617. "in-out": d3_ease_reflect,
  6618. "out-in": function(f) {
  6619. return d3_ease_reflect(d3_ease_reverse(f));
  6620. }
  6621. });
  6622. d3.ease = function(name) {
  6623. var i = name.indexOf("-"), t = i >= 0 ? name.slice(0, i) : name, m = i >= 0 ? name.slice(i + 1) : "in";
  6624. t = d3_ease.get(t) || d3_ease_default;
  6625. m = d3_ease_mode.get(m) || d3_identity;
  6626. return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1))));
  6627. };
  6628. function d3_ease_clamp(f) {
  6629. return function(t) {
  6630. return t <= 0 ? 0 : t >= 1 ? 1 : f(t);
  6631. };
  6632. }
  6633. function d3_ease_reverse(f) {
  6634. return function(t) {
  6635. return 1 - f(1 - t);
  6636. };
  6637. }
  6638. function d3_ease_reflect(f) {
  6639. return function(t) {
  6640. return .5 * (t < .5 ? f(2 * t) : 2 - f(2 - 2 * t));
  6641. };
  6642. }
  6643. function d3_ease_quad(t) {
  6644. return t * t;
  6645. }
  6646. function d3_ease_cubic(t) {
  6647. return t * t * t;
  6648. }
  6649. function d3_ease_cubicInOut(t) {
  6650. if (t <= 0) return 0;
  6651. if (t >= 1) return 1;
  6652. var t2 = t * t, t3 = t2 * t;
  6653. return 4 * (t < .5 ? t3 : 3 * (t - t2) + t3 - .75);
  6654. }
  6655. function d3_ease_poly(e) {
  6656. return function(t) {
  6657. return Math.pow(t, e);
  6658. };
  6659. }
  6660. function d3_ease_sin(t) {
  6661. return 1 - Math.cos(t * halfπ);
  6662. }
  6663. function d3_ease_exp(t) {
  6664. return Math.pow(2, 10 * (t - 1));
  6665. }
  6666. function d3_ease_circle(t) {
  6667. return 1 - Math.sqrt(1 - t * t);
  6668. }
  6669. function d3_ease_elastic(a, p) {
  6670. var s;
  6671. if (arguments.length < 2) p = .45;
  6672. if (arguments.length) s = p / τ * Math.asin(1 / a); else a = 1, s = p / 4;
  6673. return function(t) {
  6674. return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p);
  6675. };
  6676. }
  6677. function d3_ease_back(s) {
  6678. if (!s) s = 1.70158;
  6679. return function(t) {
  6680. return t * t * ((s + 1) * t - s);
  6681. };
  6682. }
  6683. function d3_ease_bounce(t) {
  6684. return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + .75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + .9375 : 7.5625 * (t -= 2.625 / 2.75) * t + .984375;
  6685. }
  6686. d3.interpolateHcl = d3_interpolateHcl;
  6687. function d3_interpolateHcl(a, b) {
  6688. a = d3.hcl(a);
  6689. b = d3.hcl(b);
  6690. var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al;
  6691. if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac;
  6692. if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360;
  6693. return function(t) {
  6694. return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + "";
  6695. };
  6696. }
  6697. d3.interpolateHsl = d3_interpolateHsl;
  6698. function d3_interpolateHsl(a, b) {
  6699. a = d3.hsl(a);
  6700. b = d3.hsl(b);
  6701. var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al;
  6702. if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as;
  6703. if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; else if (bh > 180) bh -= 360; else if (bh < -180) bh += 360;
  6704. return function(t) {
  6705. return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + "";
  6706. };
  6707. }
  6708. d3.interpolateLab = d3_interpolateLab;
  6709. function d3_interpolateLab(a, b) {
  6710. a = d3.lab(a);
  6711. b = d3.lab(b);
  6712. var al = a.l, aa = a.a, ab = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab;
  6713. return function(t) {
  6714. return d3_lab_rgb(al + bl * t, aa + ba * t, ab + bb * t) + "";
  6715. };
  6716. }
  6717. d3.interpolateRound = d3_interpolateRound;
  6718. function d3_interpolateRound(a, b) {
  6719. b -= a;
  6720. return function(t) {
  6721. return Math.round(a + b * t);
  6722. };
  6723. }
  6724. d3.transform = function(string) {
  6725. var g = d3_document.createElementNS(d3.ns.prefix.svg, "g");
  6726. return (d3.transform = function(string) {
  6727. if (string != null) {
  6728. g.setAttribute("transform", string);
  6729. var t = g.transform.baseVal.consolidate();
  6730. }
  6731. return new d3_transform(t ? t.matrix : d3_transformIdentity);
  6732. })(string);
  6733. };
  6734. function d3_transform(m) {
  6735. var r0 = [ m.a, m.b ], r1 = [ m.c, m.d ], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0;
  6736. if (r0[0] * r1[1] < r1[0] * r0[1]) {
  6737. r0[0] *= -1;
  6738. r0[1] *= -1;
  6739. kx *= -1;
  6740. kz *= -1;
  6741. }
  6742. this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees;
  6743. this.translate = [ m.e, m.f ];
  6744. this.scale = [ kx, ky ];
  6745. this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0;
  6746. }
  6747. d3_transform.prototype.toString = function() {
  6748. return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")";
  6749. };
  6750. function d3_transformDot(a, b) {
  6751. return a[0] * b[0] + a[1] * b[1];
  6752. }
  6753. function d3_transformNormalize(a) {
  6754. var k = Math.sqrt(d3_transformDot(a, a));
  6755. if (k) {
  6756. a[0] /= k;
  6757. a[1] /= k;
  6758. }
  6759. return k;
  6760. }
  6761. function d3_transformCombine(a, b, k) {
  6762. a[0] += k * b[0];
  6763. a[1] += k * b[1];
  6764. return a;
  6765. }
  6766. var d3_transformIdentity = {
  6767. a: 1,
  6768. b: 0,
  6769. c: 0,
  6770. d: 1,
  6771. e: 0,
  6772. f: 0
  6773. };
  6774. d3.interpolateTransform = d3_interpolateTransform;
  6775. function d3_interpolateTransformPop(s) {
  6776. return s.length ? s.pop() + "," : "";
  6777. }
  6778. function d3_interpolateTranslate(ta, tb, s, q) {
  6779. if (ta[0] !== tb[0] || ta[1] !== tb[1]) {
  6780. var i = s.push("translate(", null, ",", null, ")");
  6781. q.push({
  6782. i: i - 4,
  6783. x: d3_interpolateNumber(ta[0], tb[0])
  6784. }, {
  6785. i: i - 2,
  6786. x: d3_interpolateNumber(ta[1], tb[1])
  6787. });
  6788. } else if (tb[0] || tb[1]) {
  6789. s.push("translate(" + tb + ")");
  6790. }
  6791. }
  6792. function d3_interpolateRotate(ra, rb, s, q) {
  6793. if (ra !== rb) {
  6794. if (ra - rb > 180) rb += 360; else if (rb - ra > 180) ra += 360;
  6795. q.push({
  6796. i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2,
  6797. x: d3_interpolateNumber(ra, rb)
  6798. });
  6799. } else if (rb) {
  6800. s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")");
  6801. }
  6802. }
  6803. function d3_interpolateSkew(wa, wb, s, q) {
  6804. if (wa !== wb) {
  6805. q.push({
  6806. i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2,
  6807. x: d3_interpolateNumber(wa, wb)
  6808. });
  6809. } else if (wb) {
  6810. s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")");
  6811. }
  6812. }
  6813. function d3_interpolateScale(ka, kb, s, q) {
  6814. if (ka[0] !== kb[0] || ka[1] !== kb[1]) {
  6815. var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")");
  6816. q.push({
  6817. i: i - 4,
  6818. x: d3_interpolateNumber(ka[0], kb[0])
  6819. }, {
  6820. i: i - 2,
  6821. x: d3_interpolateNumber(ka[1], kb[1])
  6822. });
  6823. } else if (kb[0] !== 1 || kb[1] !== 1) {
  6824. s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")");
  6825. }
  6826. }
  6827. function d3_interpolateTransform(a, b) {
  6828. var s = [], q = [];
  6829. a = d3.transform(a), b = d3.transform(b);
  6830. d3_interpolateTranslate(a.translate, b.translate, s, q);
  6831. d3_interpolateRotate(a.rotate, b.rotate, s, q);
  6832. d3_interpolateSkew(a.skew, b.skew, s, q);
  6833. d3_interpolateScale(a.scale, b.scale, s, q);
  6834. a = b = null;
  6835. return function(t) {
  6836. var i = -1, n = q.length, o;
  6837. while (++i < n) s[(o = q[i]).i] = o.x(t);
  6838. return s.join("");
  6839. };
  6840. }
  6841. function d3_uninterpolateNumber(a, b) {
  6842. b = (b -= a = +a) || 1 / b;
  6843. return function(x) {
  6844. return (x - a) / b;
  6845. };
  6846. }
  6847. function d3_uninterpolateClamp(a, b) {
  6848. b = (b -= a = +a) || 1 / b;
  6849. return function(x) {
  6850. return Math.max(0, Math.min(1, (x - a) / b));
  6851. };
  6852. }
  6853. d3.layout = {};
  6854. d3.layout.bundle = function() {
  6855. return function(links) {
  6856. var paths = [], i = -1, n = links.length;
  6857. while (++i < n) paths.push(d3_layout_bundlePath(links[i]));
  6858. return paths;
  6859. };
  6860. };
  6861. function d3_layout_bundlePath(link) {
  6862. var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [ start ];
  6863. while (start !== lca) {
  6864. start = start.parent;
  6865. points.push(start);
  6866. }
  6867. var k = points.length;
  6868. while (end !== lca) {
  6869. points.splice(k, 0, end);
  6870. end = end.parent;
  6871. }
  6872. return points;
  6873. }
  6874. function d3_layout_bundleAncestors(node) {
  6875. var ancestors = [], parent = node.parent;
  6876. while (parent != null) {
  6877. ancestors.push(node);
  6878. node = parent;
  6879. parent = parent.parent;
  6880. }
  6881. ancestors.push(node);
  6882. return ancestors;
  6883. }
  6884. function d3_layout_bundleLeastCommonAncestor(a, b) {
  6885. if (a === b) return a;
  6886. var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null;
  6887. while (aNode === bNode) {
  6888. sharedNode = aNode;
  6889. aNode = aNodes.pop();
  6890. bNode = bNodes.pop();
  6891. }
  6892. return sharedNode;
  6893. }
  6894. d3.layout.chord = function() {
  6895. var chord = {}, chords, groups, matrix, n, padding = 0, sortGroups, sortSubgroups, sortChords;
  6896. function relayout() {
  6897. var subgroups = {}, groupSums = [], groupIndex = d3.range(n), subgroupIndex = [], k, x, x0, i, j;
  6898. chords = [];
  6899. groups = [];
  6900. k = 0, i = -1;
  6901. while (++i < n) {
  6902. x = 0, j = -1;
  6903. while (++j < n) {
  6904. x += matrix[i][j];
  6905. }
  6906. groupSums.push(x);
  6907. subgroupIndex.push(d3.range(n));
  6908. k += x;
  6909. }
  6910. if (sortGroups) {
  6911. groupIndex.sort(function(a, b) {
  6912. return sortGroups(groupSums[a], groupSums[b]);
  6913. });
  6914. }
  6915. if (sortSubgroups) {
  6916. subgroupIndex.forEach(function(d, i) {
  6917. d.sort(function(a, b) {
  6918. return sortSubgroups(matrix[i][a], matrix[i][b]);
  6919. });
  6920. });
  6921. }
  6922. k = (τ - padding * n) / k;
  6923. x = 0, i = -1;
  6924. while (++i < n) {
  6925. x0 = x, j = -1;
  6926. while (++j < n) {
  6927. var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix[di][dj], a0 = x, a1 = x += v * k;
  6928. subgroups[di + "-" + dj] = {
  6929. index: di,
  6930. subindex: dj,
  6931. startAngle: a0,
  6932. endAngle: a1,
  6933. value: v
  6934. };
  6935. }
  6936. groups[di] = {
  6937. index: di,
  6938. startAngle: x0,
  6939. endAngle: x,
  6940. value: groupSums[di]
  6941. };
  6942. x += padding;
  6943. }
  6944. i = -1;
  6945. while (++i < n) {
  6946. j = i - 1;
  6947. while (++j < n) {
  6948. var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i];
  6949. if (source.value || target.value) {
  6950. chords.push(source.value < target.value ? {
  6951. source: target,
  6952. target: source
  6953. } : {
  6954. source: source,
  6955. target: target
  6956. });
  6957. }
  6958. }
  6959. }
  6960. if (sortChords) resort();
  6961. }
  6962. function resort() {
  6963. chords.sort(function(a, b) {
  6964. return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2);
  6965. });
  6966. }
  6967. chord.matrix = function(x) {
  6968. if (!arguments.length) return matrix;
  6969. n = (matrix = x) && matrix.length;
  6970. chords = groups = null;
  6971. return chord;
  6972. };
  6973. chord.padding = function(x) {
  6974. if (!arguments.length) return padding;
  6975. padding = x;
  6976. chords = groups = null;
  6977. return chord;
  6978. };
  6979. chord.sortGroups = function(x) {
  6980. if (!arguments.length) return sortGroups;
  6981. sortGroups = x;
  6982. chords = groups = null;
  6983. return chord;
  6984. };
  6985. chord.sortSubgroups = function(x) {
  6986. if (!arguments.length) return sortSubgroups;
  6987. sortSubgroups = x;
  6988. chords = null;
  6989. return chord;
  6990. };
  6991. chord.sortChords = function(x) {
  6992. if (!arguments.length) return sortChords;
  6993. sortChords = x;
  6994. if (chords) resort();
  6995. return chord;
  6996. };
  6997. chord.chords = function() {
  6998. if (!chords) relayout();
  6999. return chords;
  7000. };
  7001. chord.groups = function() {
  7002. if (!groups) relayout();
  7003. return groups;
  7004. };
  7005. return chord;
  7006. };
  7007. d3.layout.force = function() {
  7008. var force = {}, event = d3.dispatch("start", "tick", "end"), timer, size = [ 1, 1 ], drag, alpha, friction = .9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = .1, theta2 = .64, nodes = [], links = [], distances, strengths, charges;
  7009. function repulse(node) {
  7010. return function(quad, x1, _, x2) {
  7011. if (quad.point !== node) {
  7012. var dx = quad.cx - node.x, dy = quad.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy;
  7013. if (dw * dw / theta2 < dn) {
  7014. if (dn < chargeDistance2) {
  7015. var k = quad.charge / dn;
  7016. node.px -= dx * k;
  7017. node.py -= dy * k;
  7018. }
  7019. return true;
  7020. }
  7021. if (quad.point && dn && dn < chargeDistance2) {
  7022. var k = quad.pointCharge / dn;
  7023. node.px -= dx * k;
  7024. node.py -= dy * k;
  7025. }
  7026. }
  7027. return !quad.charge;
  7028. };
  7029. }
  7030. force.tick = function() {
  7031. if ((alpha *= .99) < .005) {
  7032. timer = null;
  7033. event.end({
  7034. type: "end",
  7035. alpha: alpha = 0
  7036. });
  7037. return true;
  7038. }
  7039. var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y;
  7040. for (i = 0; i < m; ++i) {
  7041. o = links[i];
  7042. s = o.source;
  7043. t = o.target;
  7044. x = t.x - s.x;
  7045. y = t.y - s.y;
  7046. if (l = x * x + y * y) {
  7047. l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l;
  7048. x *= l;
  7049. y *= l;
  7050. t.x -= x * (k = s.weight + t.weight ? s.weight / (s.weight + t.weight) : .5);
  7051. t.y -= y * k;
  7052. s.x += x * (k = 1 - k);
  7053. s.y += y * k;
  7054. }
  7055. }
  7056. if (k = alpha * gravity) {
  7057. x = size[0] / 2;
  7058. y = size[1] / 2;
  7059. i = -1;
  7060. if (k) while (++i < n) {
  7061. o = nodes[i];
  7062. o.x += (x - o.x) * k;
  7063. o.y += (y - o.y) * k;
  7064. }
  7065. }
  7066. if (charge) {
  7067. d3_layout_forceAccumulate(q = d3.geom.quadtree(nodes), alpha, charges);
  7068. i = -1;
  7069. while (++i < n) {
  7070. if (!(o = nodes[i]).fixed) {
  7071. q.visit(repulse(o));
  7072. }
  7073. }
  7074. }
  7075. i = -1;
  7076. while (++i < n) {
  7077. o = nodes[i];
  7078. if (o.fixed) {
  7079. o.x = o.px;
  7080. o.y = o.py;
  7081. } else {
  7082. o.x -= (o.px - (o.px = o.x)) * friction;
  7083. o.y -= (o.py - (o.py = o.y)) * friction;
  7084. }
  7085. }
  7086. event.tick({
  7087. type: "tick",
  7088. alpha: alpha
  7089. });
  7090. };
  7091. force.nodes = function(x) {
  7092. if (!arguments.length) return nodes;
  7093. nodes = x;
  7094. return force;
  7095. };
  7096. force.links = function(x) {
  7097. if (!arguments.length) return links;
  7098. links = x;
  7099. return force;
  7100. };
  7101. force.size = function(x) {
  7102. if (!arguments.length) return size;
  7103. size = x;
  7104. return force;
  7105. };
  7106. force.linkDistance = function(x) {
  7107. if (!arguments.length) return linkDistance;
  7108. linkDistance = typeof x === "function" ? x : +x;
  7109. return force;
  7110. };
  7111. force.distance = force.linkDistance;
  7112. force.linkStrength = function(x) {
  7113. if (!arguments.length) return linkStrength;
  7114. linkStrength = typeof x === "function" ? x : +x;
  7115. return force;
  7116. };
  7117. force.friction = function(x) {
  7118. if (!arguments.length) return friction;
  7119. friction = +x;
  7120. return force;
  7121. };
  7122. force.charge = function(x) {
  7123. if (!arguments.length) return charge;
  7124. charge = typeof x === "function" ? x : +x;
  7125. return force;
  7126. };
  7127. force.chargeDistance = function(x) {
  7128. if (!arguments.length) return Math.sqrt(chargeDistance2);
  7129. chargeDistance2 = x * x;
  7130. return force;
  7131. };
  7132. force.gravity = function(x) {
  7133. if (!arguments.length) return gravity;
  7134. gravity = +x;
  7135. return force;
  7136. };
  7137. force.theta = function(x) {
  7138. if (!arguments.length) return Math.sqrt(theta2);
  7139. theta2 = x * x;
  7140. return force;
  7141. };
  7142. force.alpha = function(x) {
  7143. if (!arguments.length) return alpha;
  7144. x = +x;
  7145. if (alpha) {
  7146. if (x > 0) {
  7147. alpha = x;
  7148. } else {
  7149. timer.c = null, timer.t = NaN, timer = null;
  7150. event.end({
  7151. type: "end",
  7152. alpha: alpha = 0
  7153. });
  7154. }
  7155. } else if (x > 0) {
  7156. event.start({
  7157. type: "start",
  7158. alpha: alpha = x
  7159. });
  7160. timer = d3_timer(force.tick);
  7161. }
  7162. return force;
  7163. };
  7164. force.start = function() {
  7165. var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o;
  7166. for (i = 0; i < n; ++i) {
  7167. (o = nodes[i]).index = i;
  7168. o.weight = 0;
  7169. }
  7170. for (i = 0; i < m; ++i) {
  7171. o = links[i];
  7172. if (typeof o.source == "number") o.source = nodes[o.source];
  7173. if (typeof o.target == "number") o.target = nodes[o.target];
  7174. ++o.source.weight;
  7175. ++o.target.weight;
  7176. }
  7177. for (i = 0; i < n; ++i) {
  7178. o = nodes[i];
  7179. if (isNaN(o.x)) o.x = position("x", w);
  7180. if (isNaN(o.y)) o.y = position("y", h);
  7181. if (isNaN(o.px)) o.px = o.x;
  7182. if (isNaN(o.py)) o.py = o.y;
  7183. }
  7184. distances = [];
  7185. if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); else for (i = 0; i < m; ++i) distances[i] = linkDistance;
  7186. strengths = [];
  7187. if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); else for (i = 0; i < m; ++i) strengths[i] = linkStrength;
  7188. charges = [];
  7189. if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); else for (i = 0; i < n; ++i) charges[i] = charge;
  7190. function position(dimension, size) {
  7191. if (!neighbors) {
  7192. neighbors = new Array(n);
  7193. for (j = 0; j < n; ++j) {
  7194. neighbors[j] = [];
  7195. }
  7196. for (j = 0; j < m; ++j) {
  7197. var o = links[j];
  7198. neighbors[o.source.index].push(o.target);
  7199. neighbors[o.target.index].push(o.source);
  7200. }
  7201. }
  7202. var candidates = neighbors[i], j = -1, l = candidates.length, x;
  7203. while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x;
  7204. return Math.random() * size;
  7205. }
  7206. return force.resume();
  7207. };
  7208. force.resume = function() {
  7209. return force.alpha(.1);
  7210. };
  7211. force.stop = function() {
  7212. return force.alpha(0);
  7213. };
  7214. force.drag = function() {
  7215. if (!drag) drag = d3.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend);
  7216. if (!arguments.length) return drag;
  7217. this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag);
  7218. };
  7219. function dragmove(d) {
  7220. d.px = d3.event.x, d.py = d3.event.y;
  7221. force.resume();
  7222. }
  7223. return d3.rebind(force, event, "on");
  7224. };
  7225. function d3_layout_forceDragstart(d) {
  7226. d.fixed |= 2;
  7227. }
  7228. function d3_layout_forceDragend(d) {
  7229. d.fixed &= ~6;
  7230. }
  7231. function d3_layout_forceMouseover(d) {
  7232. d.fixed |= 4;
  7233. d.px = d.x, d.py = d.y;
  7234. }
  7235. function d3_layout_forceMouseout(d) {
  7236. d.fixed &= ~4;
  7237. }
  7238. function d3_layout_forceAccumulate(quad, alpha, charges) {
  7239. var cx = 0, cy = 0;
  7240. quad.charge = 0;
  7241. if (!quad.leaf) {
  7242. var nodes = quad.nodes, n = nodes.length, i = -1, c;
  7243. while (++i < n) {
  7244. c = nodes[i];
  7245. if (c == null) continue;
  7246. d3_layout_forceAccumulate(c, alpha, charges);
  7247. quad.charge += c.charge;
  7248. cx += c.charge * c.cx;
  7249. cy += c.charge * c.cy;
  7250. }
  7251. }
  7252. if (quad.point) {
  7253. if (!quad.leaf) {
  7254. quad.point.x += Math.random() - .5;
  7255. quad.point.y += Math.random() - .5;
  7256. }
  7257. var k = alpha * charges[quad.point.index];
  7258. quad.charge += quad.pointCharge = k;
  7259. cx += k * quad.point.x;
  7260. cy += k * quad.point.y;
  7261. }
  7262. quad.cx = cx / quad.charge;
  7263. quad.cy = cy / quad.charge;
  7264. }
  7265. var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity;
  7266. d3.layout.hierarchy = function() {
  7267. var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value = d3_layout_hierarchyValue;
  7268. function hierarchy(root) {
  7269. var stack = [ root ], nodes = [], node;
  7270. root.depth = 0;
  7271. while ((node = stack.pop()) != null) {
  7272. nodes.push(node);
  7273. if ((childs = children.call(hierarchy, node, node.depth)) && (n = childs.length)) {
  7274. var n, childs, child;
  7275. while (--n >= 0) {
  7276. stack.push(child = childs[n]);
  7277. child.parent = node;
  7278. child.depth = node.depth + 1;
  7279. }
  7280. if (value) node.value = 0;
  7281. node.children = childs;
  7282. } else {
  7283. if (value) node.value = +value.call(hierarchy, node, node.depth) || 0;
  7284. delete node.children;
  7285. }
  7286. }
  7287. d3_layout_hierarchyVisitAfter(root, function(node) {
  7288. var childs, parent;
  7289. if (sort && (childs = node.children)) childs.sort(sort);
  7290. if (value && (parent = node.parent)) parent.value += node.value;
  7291. });
  7292. return nodes;
  7293. }
  7294. hierarchy.sort = function(x) {
  7295. if (!arguments.length) return sort;
  7296. sort = x;
  7297. return hierarchy;
  7298. };
  7299. hierarchy.children = function(x) {
  7300. if (!arguments.length) return children;
  7301. children = x;
  7302. return hierarchy;
  7303. };
  7304. hierarchy.value = function(x) {
  7305. if (!arguments.length) return value;
  7306. value = x;
  7307. return hierarchy;
  7308. };
  7309. hierarchy.revalue = function(root) {
  7310. if (value) {
  7311. d3_layout_hierarchyVisitBefore(root, function(node) {
  7312. if (node.children) node.value = 0;
  7313. });
  7314. d3_layout_hierarchyVisitAfter(root, function(node) {
  7315. var parent;
  7316. if (!node.children) node.value = +value.call(hierarchy, node, node.depth) || 0;
  7317. if (parent = node.parent) parent.value += node.value;
  7318. });
  7319. }
  7320. return root;
  7321. };
  7322. return hierarchy;
  7323. };
  7324. function d3_layout_hierarchyRebind(object, hierarchy) {
  7325. d3.rebind(object, hierarchy, "sort", "children", "value");
  7326. object.nodes = object;
  7327. object.links = d3_layout_hierarchyLinks;
  7328. return object;
  7329. }
  7330. function d3_layout_hierarchyVisitBefore(node, callback) {
  7331. var nodes = [ node ];
  7332. while ((node = nodes.pop()) != null) {
  7333. callback(node);
  7334. if ((children = node.children) && (n = children.length)) {
  7335. var n, children;
  7336. while (--n >= 0) nodes.push(children[n]);
  7337. }
  7338. }
  7339. }
  7340. function d3_layout_hierarchyVisitAfter(node, callback) {
  7341. var nodes = [ node ], nodes2 = [];
  7342. while ((node = nodes.pop()) != null) {
  7343. nodes2.push(node);
  7344. if ((children = node.children) && (n = children.length)) {
  7345. var i = -1, n, children;
  7346. while (++i < n) nodes.push(children[i]);
  7347. }
  7348. }
  7349. while ((node = nodes2.pop()) != null) {
  7350. callback(node);
  7351. }
  7352. }
  7353. function d3_layout_hierarchyChildren(d) {
  7354. return d.children;
  7355. }
  7356. function d3_layout_hierarchyValue(d) {
  7357. return d.value;
  7358. }
  7359. function d3_layout_hierarchySort(a, b) {
  7360. return b.value - a.value;
  7361. }
  7362. function d3_layout_hierarchyLinks(nodes) {
  7363. return d3.merge(nodes.map(function(parent) {
  7364. return (parent.children || []).map(function(child) {
  7365. return {
  7366. source: parent,
  7367. target: child
  7368. };
  7369. });
  7370. }));
  7371. }
  7372. d3.layout.partition = function() {
  7373. var hierarchy = d3.layout.hierarchy(), size = [ 1, 1 ];
  7374. function position(node, x, dx, dy) {
  7375. var children = node.children;
  7376. node.x = x;
  7377. node.y = node.depth * dy;
  7378. node.dx = dx;
  7379. node.dy = dy;
  7380. if (children && (n = children.length)) {
  7381. var i = -1, n, c, d;
  7382. dx = node.value ? dx / node.value : 0;
  7383. while (++i < n) {
  7384. position(c = children[i], x, d = c.value * dx, dy);
  7385. x += d;
  7386. }
  7387. }
  7388. }
  7389. function depth(node) {
  7390. var children = node.children, d = 0;
  7391. if (children && (n = children.length)) {
  7392. var i = -1, n;
  7393. while (++i < n) d = Math.max(d, depth(children[i]));
  7394. }
  7395. return 1 + d;
  7396. }
  7397. function partition(d, i) {
  7398. var nodes = hierarchy.call(this, d, i);
  7399. position(nodes[0], 0, size[0], size[1] / depth(nodes[0]));
  7400. return nodes;
  7401. }
  7402. partition.size = function(x) {
  7403. if (!arguments.length) return size;
  7404. size = x;
  7405. return partition;
  7406. };
  7407. return d3_layout_hierarchyRebind(partition, hierarchy);
  7408. };
  7409. d3.layout.pie = function() {
  7410. var value = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0;
  7411. function pie(data) {
  7412. var n = data.length, values = data.map(function(d, i) {
  7413. return +value.call(pie, d, i);
  7414. }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d3.sum(values), k = sum ? (da - n * pa) / sum : 0, index = d3.range(n), arcs = [], v;
  7415. if (sort != null) index.sort(sort === d3_layout_pieSortByValue ? function(i, j) {
  7416. return values[j] - values[i];
  7417. } : function(i, j) {
  7418. return sort(data[i], data[j]);
  7419. });
  7420. index.forEach(function(i) {
  7421. arcs[i] = {
  7422. data: data[i],
  7423. value: v = values[i],
  7424. startAngle: a,
  7425. endAngle: a += v * k + pa,
  7426. padAngle: p
  7427. };
  7428. });
  7429. return arcs;
  7430. }
  7431. pie.value = function(_) {
  7432. if (!arguments.length) return value;
  7433. value = _;
  7434. return pie;
  7435. };
  7436. pie.sort = function(_) {
  7437. if (!arguments.length) return sort;
  7438. sort = _;
  7439. return pie;
  7440. };
  7441. pie.startAngle = function(_) {
  7442. if (!arguments.length) return startAngle;
  7443. startAngle = _;
  7444. return pie;
  7445. };
  7446. pie.endAngle = function(_) {
  7447. if (!arguments.length) return endAngle;
  7448. endAngle = _;
  7449. return pie;
  7450. };
  7451. pie.padAngle = function(_) {
  7452. if (!arguments.length) return padAngle;
  7453. padAngle = _;
  7454. return pie;
  7455. };
  7456. return pie;
  7457. };
  7458. var d3_layout_pieSortByValue = {};
  7459. d3.layout.stack = function() {
  7460. var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY;
  7461. function stack(data, index) {
  7462. if (!(n = data.length)) return data;
  7463. var series = data.map(function(d, i) {
  7464. return values.call(stack, d, i);
  7465. });
  7466. var points = series.map(function(d) {
  7467. return d.map(function(v, i) {
  7468. return [ x.call(stack, v, i), y.call(stack, v, i) ];
  7469. });
  7470. });
  7471. var orders = order.call(stack, points, index);
  7472. series = d3.permute(series, orders);
  7473. points = d3.permute(points, orders);
  7474. var offsets = offset.call(stack, points, index);
  7475. var m = series[0].length, n, i, j, o;
  7476. for (j = 0; j < m; ++j) {
  7477. out.call(stack, series[0][j], o = offsets[j], points[0][j][1]);
  7478. for (i = 1; i < n; ++i) {
  7479. out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]);
  7480. }
  7481. }
  7482. return data;
  7483. }
  7484. stack.values = function(x) {
  7485. if (!arguments.length) return values;
  7486. values = x;
  7487. return stack;
  7488. };
  7489. stack.order = function(x) {
  7490. if (!arguments.length) return order;
  7491. order = typeof x === "function" ? x : d3_layout_stackOrders.get(x) || d3_layout_stackOrderDefault;
  7492. return stack;
  7493. };
  7494. stack.offset = function(x) {
  7495. if (!arguments.length) return offset;
  7496. offset = typeof x === "function" ? x : d3_layout_stackOffsets.get(x) || d3_layout_stackOffsetZero;
  7497. return stack;
  7498. };
  7499. stack.x = function(z) {
  7500. if (!arguments.length) return x;
  7501. x = z;
  7502. return stack;
  7503. };
  7504. stack.y = function(z) {
  7505. if (!arguments.length) return y;
  7506. y = z;
  7507. return stack;
  7508. };
  7509. stack.out = function(z) {
  7510. if (!arguments.length) return out;
  7511. out = z;
  7512. return stack;
  7513. };
  7514. return stack;
  7515. };
  7516. function d3_layout_stackX(d) {
  7517. return d.x;
  7518. }
  7519. function d3_layout_stackY(d) {
  7520. return d.y;
  7521. }
  7522. function d3_layout_stackOut(d, y0, y) {
  7523. d.y0 = y0;
  7524. d.y = y;
  7525. }
  7526. var d3_layout_stackOrders = d3.map({
  7527. "inside-out": function(data) {
  7528. var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index = d3.range(n).sort(function(a, b) {
  7529. return max[a] - max[b];
  7530. }), top = 0, bottom = 0, tops = [], bottoms = [];
  7531. for (i = 0; i < n; ++i) {
  7532. j = index[i];
  7533. if (top < bottom) {
  7534. top += sums[j];
  7535. tops.push(j);
  7536. } else {
  7537. bottom += sums[j];
  7538. bottoms.push(j);
  7539. }
  7540. }
  7541. return bottoms.reverse().concat(tops);
  7542. },
  7543. reverse: function(data) {
  7544. return d3.range(data.length).reverse();
  7545. },
  7546. "default": d3_layout_stackOrderDefault
  7547. });
  7548. var d3_layout_stackOffsets = d3.map({
  7549. silhouette: function(data) {
  7550. var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = [];
  7551. for (j = 0; j < m; ++j) {
  7552. for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
  7553. if (o > max) max = o;
  7554. sums.push(o);
  7555. }
  7556. for (j = 0; j < m; ++j) {
  7557. y0[j] = (max - sums[j]) / 2;
  7558. }
  7559. return y0;
  7560. },
  7561. wiggle: function(data) {
  7562. var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = [];
  7563. y0[0] = o = o0 = 0;
  7564. for (j = 1; j < m; ++j) {
  7565. for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1];
  7566. for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) {
  7567. for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) {
  7568. s3 += (data[k][j][1] - data[k][j - 1][1]) / dx;
  7569. }
  7570. s2 += s3 * data[i][j][1];
  7571. }
  7572. y0[j] = o -= s1 ? s2 / s1 * dx : 0;
  7573. if (o < o0) o0 = o;
  7574. }
  7575. for (j = 0; j < m; ++j) y0[j] -= o0;
  7576. return y0;
  7577. },
  7578. expand: function(data) {
  7579. var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = [];
  7580. for (j = 0; j < m; ++j) {
  7581. for (i = 0, o = 0; i < n; i++) o += data[i][j][1];
  7582. if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; else for (i = 0; i < n; i++) data[i][j][1] = k;
  7583. }
  7584. for (j = 0; j < m; ++j) y0[j] = 0;
  7585. return y0;
  7586. },
  7587. zero: d3_layout_stackOffsetZero
  7588. });
  7589. function d3_layout_stackOrderDefault(data) {
  7590. return d3.range(data.length);
  7591. }
  7592. function d3_layout_stackOffsetZero(data) {
  7593. var j = -1, m = data[0].length, y0 = [];
  7594. while (++j < m) y0[j] = 0;
  7595. return y0;
  7596. }
  7597. function d3_layout_stackMaxIndex(array) {
  7598. var i = 1, j = 0, v = array[0][1], k, n = array.length;
  7599. for (;i < n; ++i) {
  7600. if ((k = array[i][1]) > v) {
  7601. j = i;
  7602. v = k;
  7603. }
  7604. }
  7605. return j;
  7606. }
  7607. function d3_layout_stackReduceSum(d) {
  7608. return d.reduce(d3_layout_stackSum, 0);
  7609. }
  7610. function d3_layout_stackSum(p, d) {
  7611. return p + d[1];
  7612. }
  7613. d3.layout.histogram = function() {
  7614. var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges;
  7615. function histogram(data, i) {
  7616. var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x;
  7617. while (++i < m) {
  7618. bin = bins[i] = [];
  7619. bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]);
  7620. bin.y = 0;
  7621. }
  7622. if (m > 0) {
  7623. i = -1;
  7624. while (++i < n) {
  7625. x = values[i];
  7626. if (x >= range[0] && x <= range[1]) {
  7627. bin = bins[d3.bisect(thresholds, x, 1, m) - 1];
  7628. bin.y += k;
  7629. bin.push(data[i]);
  7630. }
  7631. }
  7632. }
  7633. return bins;
  7634. }
  7635. histogram.value = function(x) {
  7636. if (!arguments.length) return valuer;
  7637. valuer = x;
  7638. return histogram;
  7639. };
  7640. histogram.range = function(x) {
  7641. if (!arguments.length) return ranger;
  7642. ranger = d3_functor(x);
  7643. return histogram;
  7644. };
  7645. histogram.bins = function(x) {
  7646. if (!arguments.length) return binner;
  7647. binner = typeof x === "number" ? function(range) {
  7648. return d3_layout_histogramBinFixed(range, x);
  7649. } : d3_functor(x);
  7650. return histogram;
  7651. };
  7652. histogram.frequency = function(x) {
  7653. if (!arguments.length) return frequency;
  7654. frequency = !!x;
  7655. return histogram;
  7656. };
  7657. return histogram;
  7658. };
  7659. function d3_layout_histogramBinSturges(range, values) {
  7660. return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1));
  7661. }
  7662. function d3_layout_histogramBinFixed(range, n) {
  7663. var x = -1, b = +range[0], m = (range[1] - b) / n, f = [];
  7664. while (++x <= n) f[x] = m * x + b;
  7665. return f;
  7666. }
  7667. function d3_layout_histogramRange(values) {
  7668. return [ d3.min(values), d3.max(values) ];
  7669. }
  7670. d3.layout.pack = function() {
  7671. var hierarchy = d3.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [ 1, 1 ], radius;
  7672. function pack(d, i) {
  7673. var nodes = hierarchy.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() {
  7674. return radius;
  7675. };
  7676. root.x = root.y = 0;
  7677. d3_layout_hierarchyVisitAfter(root, function(d) {
  7678. d.r = +r(d.value);
  7679. });
  7680. d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings);
  7681. if (padding) {
  7682. var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2;
  7683. d3_layout_hierarchyVisitAfter(root, function(d) {
  7684. d.r += dr;
  7685. });
  7686. d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings);
  7687. d3_layout_hierarchyVisitAfter(root, function(d) {
  7688. d.r -= dr;
  7689. });
  7690. }
  7691. d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h));
  7692. return nodes;
  7693. }
  7694. pack.size = function(_) {
  7695. if (!arguments.length) return size;
  7696. size = _;
  7697. return pack;
  7698. };
  7699. pack.radius = function(_) {
  7700. if (!arguments.length) return radius;
  7701. radius = _ == null || typeof _ === "function" ? _ : +_;
  7702. return pack;
  7703. };
  7704. pack.padding = function(_) {
  7705. if (!arguments.length) return padding;
  7706. padding = +_;
  7707. return pack;
  7708. };
  7709. return d3_layout_hierarchyRebind(pack, hierarchy);
  7710. };
  7711. function d3_layout_packSort(a, b) {
  7712. return a.value - b.value;
  7713. }
  7714. function d3_layout_packInsert(a, b) {
  7715. var c = a._pack_next;
  7716. a._pack_next = b;
  7717. b._pack_prev = a;
  7718. b._pack_next = c;
  7719. c._pack_prev = b;
  7720. }
  7721. function d3_layout_packSplice(a, b) {
  7722. a._pack_next = b;
  7723. b._pack_prev = a;
  7724. }
  7725. function d3_layout_packIntersects(a, b) {
  7726. var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r;
  7727. return .999 * dr * dr > dx * dx + dy * dy;
  7728. }
  7729. function d3_layout_packSiblings(node) {
  7730. if (!(nodes = node.children) || !(n = nodes.length)) return;
  7731. var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n;
  7732. function bound(node) {
  7733. xMin = Math.min(node.x - node.r, xMin);
  7734. xMax = Math.max(node.x + node.r, xMax);
  7735. yMin = Math.min(node.y - node.r, yMin);
  7736. yMax = Math.max(node.y + node.r, yMax);
  7737. }
  7738. nodes.forEach(d3_layout_packLink);
  7739. a = nodes[0];
  7740. a.x = -a.r;
  7741. a.y = 0;
  7742. bound(a);
  7743. if (n > 1) {
  7744. b = nodes[1];
  7745. b.x = b.r;
  7746. b.y = 0;
  7747. bound(b);
  7748. if (n > 2) {
  7749. c = nodes[2];
  7750. d3_layout_packPlace(a, b, c);
  7751. bound(c);
  7752. d3_layout_packInsert(a, c);
  7753. a._pack_prev = c;
  7754. d3_layout_packInsert(c, b);
  7755. b = a._pack_next;
  7756. for (i = 3; i < n; i++) {
  7757. d3_layout_packPlace(a, b, c = nodes[i]);
  7758. var isect = 0, s1 = 1, s2 = 1;
  7759. for (j = b._pack_next; j !== b; j = j._pack_next, s1++) {
  7760. if (d3_layout_packIntersects(j, c)) {
  7761. isect = 1;
  7762. break;
  7763. }
  7764. }
  7765. if (isect == 1) {
  7766. for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) {
  7767. if (d3_layout_packIntersects(k, c)) {
  7768. break;
  7769. }
  7770. }
  7771. }
  7772. if (isect) {
  7773. if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); else d3_layout_packSplice(a = k, b);
  7774. i--;
  7775. } else {
  7776. d3_layout_packInsert(a, c);
  7777. b = c;
  7778. bound(c);
  7779. }
  7780. }
  7781. }
  7782. }
  7783. var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0;
  7784. for (i = 0; i < n; i++) {
  7785. c = nodes[i];
  7786. c.x -= cx;
  7787. c.y -= cy;
  7788. cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y));
  7789. }
  7790. node.r = cr;
  7791. nodes.forEach(d3_layout_packUnlink);
  7792. }
  7793. function d3_layout_packLink(node) {
  7794. node._pack_next = node._pack_prev = node;
  7795. }
  7796. function d3_layout_packUnlink(node) {
  7797. delete node._pack_next;
  7798. delete node._pack_prev;
  7799. }
  7800. function d3_layout_packTransform(node, x, y, k) {
  7801. var children = node.children;
  7802. node.x = x += k * node.x;
  7803. node.y = y += k * node.y;
  7804. node.r *= k;
  7805. if (children) {
  7806. var i = -1, n = children.length;
  7807. while (++i < n) d3_layout_packTransform(children[i], x, y, k);
  7808. }
  7809. }
  7810. function d3_layout_packPlace(a, b, c) {
  7811. var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y;
  7812. if (db && (dx || dy)) {
  7813. var da = b.r + c.r, dc = dx * dx + dy * dy;
  7814. da *= da;
  7815. db *= db;
  7816. var x = .5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc);
  7817. c.x = a.x + x * dx + y * dy;
  7818. c.y = a.y + x * dy - y * dx;
  7819. } else {
  7820. c.x = a.x + db;
  7821. c.y = a.y;
  7822. }
  7823. }
  7824. d3.layout.tree = function() {
  7825. var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = null;
  7826. function tree(d, i) {
  7827. var nodes = hierarchy.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0);
  7828. d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z;
  7829. d3_layout_hierarchyVisitBefore(root1, secondWalk);
  7830. if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); else {
  7831. var left = root0, right = root0, bottom = root0;
  7832. d3_layout_hierarchyVisitBefore(root0, function(node) {
  7833. if (node.x < left.x) left = node;
  7834. if (node.x > right.x) right = node;
  7835. if (node.depth > bottom.depth) bottom = node;
  7836. });
  7837. var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1);
  7838. d3_layout_hierarchyVisitBefore(root0, function(node) {
  7839. node.x = (node.x + tx) * kx;
  7840. node.y = node.depth * ky;
  7841. });
  7842. }
  7843. return nodes;
  7844. }
  7845. function wrapTree(root0) {
  7846. var root1 = {
  7847. A: null,
  7848. children: [ root0 ]
  7849. }, queue = [ root1 ], node1;
  7850. while ((node1 = queue.pop()) != null) {
  7851. for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) {
  7852. queue.push((children[i] = child = {
  7853. _: children[i],
  7854. parent: node1,
  7855. children: (child = children[i].children) && child.slice() || [],
  7856. A: null,
  7857. a: null,
  7858. z: 0,
  7859. m: 0,
  7860. c: 0,
  7861. s: 0,
  7862. t: null,
  7863. i: i
  7864. }).a = child);
  7865. }
  7866. }
  7867. return root1.children[0];
  7868. }
  7869. function firstWalk(v) {
  7870. var children = v.children, siblings = v.parent.children, w = v.i ? siblings[v.i - 1] : null;
  7871. if (children.length) {
  7872. d3_layout_treeShift(v);
  7873. var midpoint = (children[0].z + children[children.length - 1].z) / 2;
  7874. if (w) {
  7875. v.z = w.z + separation(v._, w._);
  7876. v.m = v.z - midpoint;
  7877. } else {
  7878. v.z = midpoint;
  7879. }
  7880. } else if (w) {
  7881. v.z = w.z + separation(v._, w._);
  7882. }
  7883. v.parent.A = apportion(v, w, v.parent.A || siblings[0]);
  7884. }
  7885. function secondWalk(v) {
  7886. v._.x = v.z + v.parent.m;
  7887. v.m += v.parent.m;
  7888. }
  7889. function apportion(v, w, ancestor) {
  7890. if (w) {
  7891. var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift;
  7892. while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) {
  7893. vom = d3_layout_treeLeft(vom);
  7894. vop = d3_layout_treeRight(vop);
  7895. vop.a = v;
  7896. shift = vim.z + sim - vip.z - sip + separation(vim._, vip._);
  7897. if (shift > 0) {
  7898. d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift);
  7899. sip += shift;
  7900. sop += shift;
  7901. }
  7902. sim += vim.m;
  7903. sip += vip.m;
  7904. som += vom.m;
  7905. sop += vop.m;
  7906. }
  7907. if (vim && !d3_layout_treeRight(vop)) {
  7908. vop.t = vim;
  7909. vop.m += sim - sop;
  7910. }
  7911. if (vip && !d3_layout_treeLeft(vom)) {
  7912. vom.t = vip;
  7913. vom.m += sip - som;
  7914. ancestor = v;
  7915. }
  7916. }
  7917. return ancestor;
  7918. }
  7919. function sizeNode(node) {
  7920. node.x *= size[0];
  7921. node.y = node.depth * size[1];
  7922. }
  7923. tree.separation = function(x) {
  7924. if (!arguments.length) return separation;
  7925. separation = x;
  7926. return tree;
  7927. };
  7928. tree.size = function(x) {
  7929. if (!arguments.length) return nodeSize ? null : size;
  7930. nodeSize = (size = x) == null ? sizeNode : null;
  7931. return tree;
  7932. };
  7933. tree.nodeSize = function(x) {
  7934. if (!arguments.length) return nodeSize ? size : null;
  7935. nodeSize = (size = x) == null ? null : sizeNode;
  7936. return tree;
  7937. };
  7938. return d3_layout_hierarchyRebind(tree, hierarchy);
  7939. };
  7940. function d3_layout_treeSeparation(a, b) {
  7941. return a.parent == b.parent ? 1 : 2;
  7942. }
  7943. function d3_layout_treeLeft(v) {
  7944. var children = v.children;
  7945. return children.length ? children[0] : v.t;
  7946. }
  7947. function d3_layout_treeRight(v) {
  7948. var children = v.children, n;
  7949. return (n = children.length) ? children[n - 1] : v.t;
  7950. }
  7951. function d3_layout_treeMove(wm, wp, shift) {
  7952. var change = shift / (wp.i - wm.i);
  7953. wp.c -= change;
  7954. wp.s += shift;
  7955. wm.c += change;
  7956. wp.z += shift;
  7957. wp.m += shift;
  7958. }
  7959. function d3_layout_treeShift(v) {
  7960. var shift = 0, change = 0, children = v.children, i = children.length, w;
  7961. while (--i >= 0) {
  7962. w = children[i];
  7963. w.z += shift;
  7964. w.m += shift;
  7965. shift += w.s + (change += w.c);
  7966. }
  7967. }
  7968. function d3_layout_treeAncestor(vim, v, ancestor) {
  7969. return vim.a.parent === v.parent ? vim.a : ancestor;
  7970. }
  7971. d3.layout.cluster = function() {
  7972. var hierarchy = d3.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [ 1, 1 ], nodeSize = false;
  7973. function cluster(d, i) {
  7974. var nodes = hierarchy.call(this, d, i), root = nodes[0], previousNode, x = 0;
  7975. d3_layout_hierarchyVisitAfter(root, function(node) {
  7976. var children = node.children;
  7977. if (children && children.length) {
  7978. node.x = d3_layout_clusterX(children);
  7979. node.y = d3_layout_clusterY(children);
  7980. } else {
  7981. node.x = previousNode ? x += separation(node, previousNode) : 0;
  7982. node.y = 0;
  7983. previousNode = node;
  7984. }
  7985. });
  7986. var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2;
  7987. d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) {
  7988. node.x = (node.x - root.x) * size[0];
  7989. node.y = (root.y - node.y) * size[1];
  7990. } : function(node) {
  7991. node.x = (node.x - x0) / (x1 - x0) * size[0];
  7992. node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1];
  7993. });
  7994. return nodes;
  7995. }
  7996. cluster.separation = function(x) {
  7997. if (!arguments.length) return separation;
  7998. separation = x;
  7999. return cluster;
  8000. };
  8001. cluster.size = function(x) {
  8002. if (!arguments.length) return nodeSize ? null : size;
  8003. nodeSize = (size = x) == null;
  8004. return cluster;
  8005. };
  8006. cluster.nodeSize = function(x) {
  8007. if (!arguments.length) return nodeSize ? size : null;
  8008. nodeSize = (size = x) != null;
  8009. return cluster;
  8010. };
  8011. return d3_layout_hierarchyRebind(cluster, hierarchy);
  8012. };
  8013. function d3_layout_clusterY(children) {
  8014. return 1 + d3.max(children, function(child) {
  8015. return child.y;
  8016. });
  8017. }
  8018. function d3_layout_clusterX(children) {
  8019. return children.reduce(function(x, child) {
  8020. return x + child.x;
  8021. }, 0) / children.length;
  8022. }
  8023. function d3_layout_clusterLeft(node) {
  8024. var children = node.children;
  8025. return children && children.length ? d3_layout_clusterLeft(children[0]) : node;
  8026. }
  8027. function d3_layout_clusterRight(node) {
  8028. var children = node.children, n;
  8029. return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node;
  8030. }
  8031. d3.layout.treemap = function() {
  8032. var hierarchy = d3.layout.hierarchy(), round = Math.round, size = [ 1, 1 ], padding = null, pad = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = .5 * (1 + Math.sqrt(5));
  8033. function scale(children, k) {
  8034. var i = -1, n = children.length, child, area;
  8035. while (++i < n) {
  8036. area = (child = children[i]).value * (k < 0 ? 0 : k);
  8037. child.area = isNaN(area) || area <= 0 ? 0 : area;
  8038. }
  8039. }
  8040. function squarify(node) {
  8041. var children = node.children;
  8042. if (children && children.length) {
  8043. var rect = pad(node), row = [], remaining = children.slice(), child, best = Infinity, score, u = mode === "slice" ? rect.dx : mode === "dice" ? rect.dy : mode === "slice-dice" ? node.depth & 1 ? rect.dy : rect.dx : Math.min(rect.dx, rect.dy), n;
  8044. scale(remaining, rect.dx * rect.dy / node.value);
  8045. row.area = 0;
  8046. while ((n = remaining.length) > 0) {
  8047. row.push(child = remaining[n - 1]);
  8048. row.area += child.area;
  8049. if (mode !== "squarify" || (score = worst(row, u)) <= best) {
  8050. remaining.pop();
  8051. best = score;
  8052. } else {
  8053. row.area -= row.pop().area;
  8054. position(row, u, rect, false);
  8055. u = Math.min(rect.dx, rect.dy);
  8056. row.length = row.area = 0;
  8057. best = Infinity;
  8058. }
  8059. }
  8060. if (row.length) {
  8061. position(row, u, rect, true);
  8062. row.length = row.area = 0;
  8063. }
  8064. children.forEach(squarify);
  8065. }
  8066. }
  8067. function stickify(node) {
  8068. var children = node.children;
  8069. if (children && children.length) {
  8070. var rect = pad(node), remaining = children.slice(), child, row = [];
  8071. scale(remaining, rect.dx * rect.dy / node.value);
  8072. row.area = 0;
  8073. while (child = remaining.pop()) {
  8074. row.push(child);
  8075. row.area += child.area;
  8076. if (child.z != null) {
  8077. position(row, child.z ? rect.dx : rect.dy, rect, !remaining.length);
  8078. row.length = row.area = 0;
  8079. }
  8080. }
  8081. children.forEach(stickify);
  8082. }
  8083. }
  8084. function worst(row, u) {
  8085. var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length;
  8086. while (++i < n) {
  8087. if (!(r = row[i].area)) continue;
  8088. if (r < rmin) rmin = r;
  8089. if (r > rmax) rmax = r;
  8090. }
  8091. s *= s;
  8092. u *= u;
  8093. return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity;
  8094. }
  8095. function position(row, u, rect, flush) {
  8096. var i = -1, n = row.length, x = rect.x, y = rect.y, v = u ? round(row.area / u) : 0, o;
  8097. if (u == rect.dx) {
  8098. if (flush || v > rect.dy) v = rect.dy;
  8099. while (++i < n) {
  8100. o = row[i];
  8101. o.x = x;
  8102. o.y = y;
  8103. o.dy = v;
  8104. x += o.dx = Math.min(rect.x + rect.dx - x, v ? round(o.area / v) : 0);
  8105. }
  8106. o.z = true;
  8107. o.dx += rect.x + rect.dx - x;
  8108. rect.y += v;
  8109. rect.dy -= v;
  8110. } else {
  8111. if (flush || v > rect.dx) v = rect.dx;
  8112. while (++i < n) {
  8113. o = row[i];
  8114. o.x = x;
  8115. o.y = y;
  8116. o.dx = v;
  8117. y += o.dy = Math.min(rect.y + rect.dy - y, v ? round(o.area / v) : 0);
  8118. }
  8119. o.z = false;
  8120. o.dy += rect.y + rect.dy - y;
  8121. rect.x += v;
  8122. rect.dx -= v;
  8123. }
  8124. }
  8125. function treemap(d) {
  8126. var nodes = stickies || hierarchy(d), root = nodes[0];
  8127. root.x = root.y = 0;
  8128. if (root.value) root.dx = size[0], root.dy = size[1]; else root.dx = root.dy = 0;
  8129. if (stickies) hierarchy.revalue(root);
  8130. scale([ root ], root.dx * root.dy / root.value);
  8131. (stickies ? stickify : squarify)(root);
  8132. if (sticky) stickies = nodes;
  8133. return nodes;
  8134. }
  8135. treemap.size = function(x) {
  8136. if (!arguments.length) return size;
  8137. size = x;
  8138. return treemap;
  8139. };
  8140. treemap.padding = function(x) {
  8141. if (!arguments.length) return padding;
  8142. function padFunction(node) {
  8143. var p = x.call(treemap, node, node.depth);
  8144. return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [ p, p, p, p ] : p);
  8145. }
  8146. function padConstant(node) {
  8147. return d3_layout_treemapPad(node, x);
  8148. }
  8149. var type;
  8150. pad = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [ x, x, x, x ],
  8151. padConstant) : padConstant;
  8152. return treemap;
  8153. };
  8154. treemap.round = function(x) {
  8155. if (!arguments.length) return round != Number;
  8156. round = x ? Math.round : Number;
  8157. return treemap;
  8158. };
  8159. treemap.sticky = function(x) {
  8160. if (!arguments.length) return sticky;
  8161. sticky = x;
  8162. stickies = null;
  8163. return treemap;
  8164. };
  8165. treemap.ratio = function(x) {
  8166. if (!arguments.length) return ratio;
  8167. ratio = x;
  8168. return treemap;
  8169. };
  8170. treemap.mode = function(x) {
  8171. if (!arguments.length) return mode;
  8172. mode = x + "";
  8173. return treemap;
  8174. };
  8175. return d3_layout_hierarchyRebind(treemap, hierarchy);
  8176. };
  8177. function d3_layout_treemapPadNull(node) {
  8178. return {
  8179. x: node.x,
  8180. y: node.y,
  8181. dx: node.dx,
  8182. dy: node.dy
  8183. };
  8184. }
  8185. function d3_layout_treemapPad(node, padding) {
  8186. var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2];
  8187. if (dx < 0) {
  8188. x += dx / 2;
  8189. dx = 0;
  8190. }
  8191. if (dy < 0) {
  8192. y += dy / 2;
  8193. dy = 0;
  8194. }
  8195. return {
  8196. x: x,
  8197. y: y,
  8198. dx: dx,
  8199. dy: dy
  8200. };
  8201. }
  8202. d3.random = {
  8203. normal: function(µ, σ) {
  8204. var n = arguments.length;
  8205. if (n < 2) σ = 1;
  8206. if (n < 1) µ = 0;
  8207. return function() {
  8208. var x, y, r;
  8209. do {
  8210. x = Math.random() * 2 - 1;
  8211. y = Math.random() * 2 - 1;
  8212. r = x * x + y * y;
  8213. } while (!r || r > 1);
  8214. return µ + σ * x * Math.sqrt(-2 * Math.log(r) / r);
  8215. };
  8216. },
  8217. logNormal: function() {
  8218. var random = d3.random.normal.apply(d3, arguments);
  8219. return function() {
  8220. return Math.exp(random());
  8221. };
  8222. },
  8223. bates: function(m) {
  8224. var random = d3.random.irwinHall(m);
  8225. return function() {
  8226. return random() / m;
  8227. };
  8228. },
  8229. irwinHall: function(m) {
  8230. return function() {
  8231. for (var s = 0, j = 0; j < m; j++) s += Math.random();
  8232. return s;
  8233. };
  8234. }
  8235. };
  8236. d3.scale = {};
  8237. function d3_scaleExtent(domain) {
  8238. var start = domain[0], stop = domain[domain.length - 1];
  8239. return start < stop ? [ start, stop ] : [ stop, start ];
  8240. }
  8241. function d3_scaleRange(scale) {
  8242. return scale.rangeExtent ? scale.rangeExtent() : d3_scaleExtent(scale.range());
  8243. }
  8244. function d3_scale_bilinear(domain, range, uninterpolate, interpolate) {
  8245. var u = uninterpolate(domain[0], domain[1]), i = interpolate(range[0], range[1]);
  8246. return function(x) {
  8247. return i(u(x));
  8248. };
  8249. }
  8250. function d3_scale_nice(domain, nice) {
  8251. var i0 = 0, i1 = domain.length - 1, x0 = domain[i0], x1 = domain[i1], dx;
  8252. if (x1 < x0) {
  8253. dx = i0, i0 = i1, i1 = dx;
  8254. dx = x0, x0 = x1, x1 = dx;
  8255. }
  8256. domain[i0] = nice.floor(x0);
  8257. domain[i1] = nice.ceil(x1);
  8258. return domain;
  8259. }
  8260. function d3_scale_niceStep(step) {
  8261. return step ? {
  8262. floor: function(x) {
  8263. return Math.floor(x / step) * step;
  8264. },
  8265. ceil: function(x) {
  8266. return Math.ceil(x / step) * step;
  8267. }
  8268. } : d3_scale_niceIdentity;
  8269. }
  8270. var d3_scale_niceIdentity = {
  8271. floor: d3_identity,
  8272. ceil: d3_identity
  8273. };
  8274. function d3_scale_polylinear(domain, range, uninterpolate, interpolate) {
  8275. var u = [], i = [], j = 0, k = Math.min(domain.length, range.length) - 1;
  8276. if (domain[k] < domain[0]) {
  8277. domain = domain.slice().reverse();
  8278. range = range.slice().reverse();
  8279. }
  8280. while (++j <= k) {
  8281. u.push(uninterpolate(domain[j - 1], domain[j]));
  8282. i.push(interpolate(range[j - 1], range[j]));
  8283. }
  8284. return function(x) {
  8285. var j = d3.bisect(domain, x, 1, k) - 1;
  8286. return i[j](u[j](x));
  8287. };
  8288. }
  8289. d3.scale.linear = function() {
  8290. return d3_scale_linear([ 0, 1 ], [ 0, 1 ], d3_interpolate, false);
  8291. };
  8292. function d3_scale_linear(domain, range, interpolate, clamp) {
  8293. var output, input;
  8294. function rescale() {
  8295. var linear = Math.min(domain.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp ? d3_uninterpolateClamp : d3_uninterpolateNumber;
  8296. output = linear(domain, range, uninterpolate, interpolate);
  8297. input = linear(range, domain, uninterpolate, d3_interpolate);
  8298. return scale;
  8299. }
  8300. function scale(x) {
  8301. return output(x);
  8302. }
  8303. scale.invert = function(y) {
  8304. return input(y);
  8305. };
  8306. scale.domain = function(x) {
  8307. if (!arguments.length) return domain;
  8308. domain = x.map(Number);
  8309. return rescale();
  8310. };
  8311. scale.range = function(x) {
  8312. if (!arguments.length) return range;
  8313. range = x;
  8314. return rescale();
  8315. };
  8316. scale.rangeRound = function(x) {
  8317. return scale.range(x).interpolate(d3_interpolateRound);
  8318. };
  8319. scale.clamp = function(x) {
  8320. if (!arguments.length) return clamp;
  8321. clamp = x;
  8322. return rescale();
  8323. };
  8324. scale.interpolate = function(x) {
  8325. if (!arguments.length) return interpolate;
  8326. interpolate = x;
  8327. return rescale();
  8328. };
  8329. scale.ticks = function(m) {
  8330. return d3_scale_linearTicks(domain, m);
  8331. };
  8332. scale.tickFormat = function(m, format) {
  8333. return d3_scale_linearTickFormat(domain, m, format);
  8334. };
  8335. scale.nice = function(m) {
  8336. d3_scale_linearNice(domain, m);
  8337. return rescale();
  8338. };
  8339. scale.copy = function() {
  8340. return d3_scale_linear(domain, range, interpolate, clamp);
  8341. };
  8342. return rescale();
  8343. }
  8344. function d3_scale_linearRebind(scale, linear) {
  8345. return d3.rebind(scale, linear, "range", "rangeRound", "interpolate", "clamp");
  8346. }
  8347. function d3_scale_linearNice(domain, m) {
  8348. d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
  8349. d3_scale_nice(domain, d3_scale_niceStep(d3_scale_linearTickRange(domain, m)[2]));
  8350. return domain;
  8351. }
  8352. function d3_scale_linearTickRange(domain, m) {
  8353. if (m == null) m = 10;
  8354. var extent = d3_scaleExtent(domain), span = extent[1] - extent[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step;
  8355. if (err <= .15) step *= 10; else if (err <= .35) step *= 5; else if (err <= .75) step *= 2;
  8356. extent[0] = Math.ceil(extent[0] / step) * step;
  8357. extent[1] = Math.floor(extent[1] / step) * step + step * .5;
  8358. extent[2] = step;
  8359. return extent;
  8360. }
  8361. function d3_scale_linearTicks(domain, m) {
  8362. return d3.range.apply(d3, d3_scale_linearTickRange(domain, m));
  8363. }
  8364. function d3_scale_linearTickFormat(domain, m, format) {
  8365. var range = d3_scale_linearTickRange(domain, m);
  8366. if (format) {
  8367. var match = d3_format_re.exec(format);
  8368. match.shift();
  8369. if (match[8] === "s") {
  8370. var prefix = d3.formatPrefix(Math.max(abs(range[0]), abs(range[1])));
  8371. if (!match[7]) match[7] = "." + d3_scale_linearPrecision(prefix.scale(range[2]));
  8372. match[8] = "f";
  8373. format = d3.format(match.join(""));
  8374. return function(d) {
  8375. return format(prefix.scale(d)) + prefix.symbol;
  8376. };
  8377. }
  8378. if (!match[7]) match[7] = "." + d3_scale_linearFormatPrecision(match[8], range);
  8379. format = match.join("");
  8380. } else {
  8381. format = ",." + d3_scale_linearPrecision(range[2]) + "f";
  8382. }
  8383. return d3.format(format);
  8384. }
  8385. var d3_scale_linearFormatSignificant = {
  8386. s: 1,
  8387. g: 1,
  8388. p: 1,
  8389. r: 1,
  8390. e: 1
  8391. };
  8392. function d3_scale_linearPrecision(value) {
  8393. return -Math.floor(Math.log(value) / Math.LN10 + .01);
  8394. }
  8395. function d3_scale_linearFormatPrecision(type, range) {
  8396. var p = d3_scale_linearPrecision(range[2]);
  8397. return type in d3_scale_linearFormatSignificant ? Math.abs(p - d3_scale_linearPrecision(Math.max(abs(range[0]), abs(range[1])))) + +(type !== "e") : p - (type === "%") * 2;
  8398. }
  8399. d3.scale.log = function() {
  8400. return d3_scale_log(d3.scale.linear().domain([ 0, 1 ]), 10, true, [ 1, 10 ]);
  8401. };
  8402. function d3_scale_log(linear, base, positive, domain) {
  8403. function log(x) {
  8404. return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base);
  8405. }
  8406. function pow(x) {
  8407. return positive ? Math.pow(base, x) : -Math.pow(base, -x);
  8408. }
  8409. function scale(x) {
  8410. return linear(log(x));
  8411. }
  8412. scale.invert = function(x) {
  8413. return pow(linear.invert(x));
  8414. };
  8415. scale.domain = function(x) {
  8416. if (!arguments.length) return domain;
  8417. positive = x[0] >= 0;
  8418. linear.domain((domain = x.map(Number)).map(log));
  8419. return scale;
  8420. };
  8421. scale.base = function(_) {
  8422. if (!arguments.length) return base;
  8423. base = +_;
  8424. linear.domain(domain.map(log));
  8425. return scale;
  8426. };
  8427. scale.nice = function() {
  8428. var niced = d3_scale_nice(domain.map(log), positive ? Math : d3_scale_logNiceNegative);
  8429. linear.domain(niced);
  8430. domain = niced.map(pow);
  8431. return scale;
  8432. };
  8433. scale.ticks = function() {
  8434. var extent = d3_scaleExtent(domain), ticks = [], u = extent[0], v = extent[1], i = Math.floor(log(u)), j = Math.ceil(log(v)), n = base % 1 ? 2 : base;
  8435. if (isFinite(j - i)) {
  8436. if (positive) {
  8437. for (;i < j; i++) for (var k = 1; k < n; k++) ticks.push(pow(i) * k);
  8438. ticks.push(pow(i));
  8439. } else {
  8440. ticks.push(pow(i));
  8441. for (;i++ < j; ) for (var k = n - 1; k > 0; k--) ticks.push(pow(i) * k);
  8442. }
  8443. for (i = 0; ticks[i] < u; i++) {}
  8444. for (j = ticks.length; ticks[j - 1] > v; j--) {}
  8445. ticks = ticks.slice(i, j);
  8446. }
  8447. return ticks;
  8448. };
  8449. scale.tickFormat = function(n, format) {
  8450. if (!arguments.length) return d3_scale_logFormat;
  8451. if (arguments.length < 2) format = d3_scale_logFormat; else if (typeof format !== "function") format = d3.format(format);
  8452. var k = Math.max(1, base * n / scale.ticks().length);
  8453. return function(d) {
  8454. var i = d / pow(Math.round(log(d)));
  8455. if (i * base < base - .5) i *= base;
  8456. return i <= k ? format(d) : "";
  8457. };
  8458. };
  8459. scale.copy = function() {
  8460. return d3_scale_log(linear.copy(), base, positive, domain);
  8461. };
  8462. return d3_scale_linearRebind(scale, linear);
  8463. }
  8464. var d3_scale_logFormat = d3.format(".0e"), d3_scale_logNiceNegative = {
  8465. floor: function(x) {
  8466. return -Math.ceil(-x);
  8467. },
  8468. ceil: function(x) {
  8469. return -Math.floor(-x);
  8470. }
  8471. };
  8472. d3.scale.pow = function() {
  8473. return d3_scale_pow(d3.scale.linear(), 1, [ 0, 1 ]);
  8474. };
  8475. function d3_scale_pow(linear, exponent, domain) {
  8476. var powp = d3_scale_powPow(exponent), powb = d3_scale_powPow(1 / exponent);
  8477. function scale(x) {
  8478. return linear(powp(x));
  8479. }
  8480. scale.invert = function(x) {
  8481. return powb(linear.invert(x));
  8482. };
  8483. scale.domain = function(x) {
  8484. if (!arguments.length) return domain;
  8485. linear.domain((domain = x.map(Number)).map(powp));
  8486. return scale;
  8487. };
  8488. scale.ticks = function(m) {
  8489. return d3_scale_linearTicks(domain, m);
  8490. };
  8491. scale.tickFormat = function(m, format) {
  8492. return d3_scale_linearTickFormat(domain, m, format);
  8493. };
  8494. scale.nice = function(m) {
  8495. return scale.domain(d3_scale_linearNice(domain, m));
  8496. };
  8497. scale.exponent = function(x) {
  8498. if (!arguments.length) return exponent;
  8499. powp = d3_scale_powPow(exponent = x);
  8500. powb = d3_scale_powPow(1 / exponent);
  8501. linear.domain(domain.map(powp));
  8502. return scale;
  8503. };
  8504. scale.copy = function() {
  8505. return d3_scale_pow(linear.copy(), exponent, domain);
  8506. };
  8507. return d3_scale_linearRebind(scale, linear);
  8508. }
  8509. function d3_scale_powPow(e) {
  8510. return function(x) {
  8511. return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e);
  8512. };
  8513. }
  8514. d3.scale.sqrt = function() {
  8515. return d3.scale.pow().exponent(.5);
  8516. };
  8517. d3.scale.ordinal = function() {
  8518. return d3_scale_ordinal([], {
  8519. t: "range",
  8520. a: [ [] ]
  8521. });
  8522. };
  8523. function d3_scale_ordinal(domain, ranger) {
  8524. var index, range, rangeBand;
  8525. function scale(x) {
  8526. return range[((index.get(x) || (ranger.t === "range" ? index.set(x, domain.push(x)) : NaN)) - 1) % range.length];
  8527. }
  8528. function steps(start, step) {
  8529. return d3.range(domain.length).map(function(i) {
  8530. return start + step * i;
  8531. });
  8532. }
  8533. scale.domain = function(x) {
  8534. if (!arguments.length) return domain;
  8535. domain = [];
  8536. index = new d3_Map();
  8537. var i = -1, n = x.length, xi;
  8538. while (++i < n) if (!index.has(xi = x[i])) index.set(xi, domain.push(xi));
  8539. return scale[ranger.t].apply(scale, ranger.a);
  8540. };
  8541. scale.range = function(x) {
  8542. if (!arguments.length) return range;
  8543. range = x;
  8544. rangeBand = 0;
  8545. ranger = {
  8546. t: "range",
  8547. a: arguments
  8548. };
  8549. return scale;
  8550. };
  8551. scale.rangePoints = function(x, padding) {
  8552. if (arguments.length < 2) padding = 0;
  8553. var start = x[0], stop = x[1], step = domain.length < 2 ? (start = (start + stop) / 2,
  8554. 0) : (stop - start) / (domain.length - 1 + padding);
  8555. range = steps(start + step * padding / 2, step);
  8556. rangeBand = 0;
  8557. ranger = {
  8558. t: "rangePoints",
  8559. a: arguments
  8560. };
  8561. return scale;
  8562. };
  8563. scale.rangeRoundPoints = function(x, padding) {
  8564. if (arguments.length < 2) padding = 0;
  8565. var start = x[0], stop = x[1], step = domain.length < 2 ? (start = stop = Math.round((start + stop) / 2),
  8566. 0) : (stop - start) / (domain.length - 1 + padding) | 0;
  8567. range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain.length - 1 + padding) * step) / 2), step);
  8568. rangeBand = 0;
  8569. ranger = {
  8570. t: "rangeRoundPoints",
  8571. a: arguments
  8572. };
  8573. return scale;
  8574. };
  8575. scale.rangeBands = function(x, padding, outerPadding) {
  8576. if (arguments.length < 2) padding = 0;
  8577. if (arguments.length < 3) outerPadding = padding;
  8578. var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain.length - padding + 2 * outerPadding);
  8579. range = steps(start + step * outerPadding, step);
  8580. if (reverse) range.reverse();
  8581. rangeBand = step * (1 - padding);
  8582. ranger = {
  8583. t: "rangeBands",
  8584. a: arguments
  8585. };
  8586. return scale;
  8587. };
  8588. scale.rangeRoundBands = function(x, padding, outerPadding) {
  8589. if (arguments.length < 2) padding = 0;
  8590. if (arguments.length < 3) outerPadding = padding;
  8591. var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain.length - padding + 2 * outerPadding));
  8592. range = steps(start + Math.round((stop - start - (domain.length - padding) * step) / 2), step);
  8593. if (reverse) range.reverse();
  8594. rangeBand = Math.round(step * (1 - padding));
  8595. ranger = {
  8596. t: "rangeRoundBands",
  8597. a: arguments
  8598. };
  8599. return scale;
  8600. };
  8601. scale.rangeBand = function() {
  8602. return rangeBand;
  8603. };
  8604. scale.rangeExtent = function() {
  8605. return d3_scaleExtent(ranger.a[0]);
  8606. };
  8607. scale.copy = function() {
  8608. return d3_scale_ordinal(domain, ranger);
  8609. };
  8610. return scale.domain(domain);
  8611. }
  8612. d3.scale.category10 = function() {
  8613. return d3.scale.ordinal().range(d3_category10);
  8614. };
  8615. d3.scale.category20 = function() {
  8616. return d3.scale.ordinal().range(d3_category20);
  8617. };
  8618. d3.scale.category20b = function() {
  8619. return d3.scale.ordinal().range(d3_category20b);
  8620. };
  8621. d3.scale.category20c = function() {
  8622. return d3.scale.ordinal().range(d3_category20c);
  8623. };
  8624. var d3_category10 = [ 2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175 ].map(d3_rgbString);
  8625. var d3_category20 = [ 2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725 ].map(d3_rgbString);
  8626. var d3_category20b = [ 3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654 ].map(d3_rgbString);
  8627. var d3_category20c = [ 3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081 ].map(d3_rgbString);
  8628. d3.scale.quantile = function() {
  8629. return d3_scale_quantile([], []);
  8630. };
  8631. function d3_scale_quantile(domain, range) {
  8632. var thresholds;
  8633. function rescale() {
  8634. var k = 0, q = range.length;
  8635. thresholds = [];
  8636. while (++k < q) thresholds[k - 1] = d3.quantile(domain, k / q);
  8637. return scale;
  8638. }
  8639. function scale(x) {
  8640. if (!isNaN(x = +x)) return range[d3.bisect(thresholds, x)];
  8641. }
  8642. scale.domain = function(x) {
  8643. if (!arguments.length) return domain;
  8644. domain = x.map(d3_number).filter(d3_numeric).sort(d3_ascending);
  8645. return rescale();
  8646. };
  8647. scale.range = function(x) {
  8648. if (!arguments.length) return range;
  8649. range = x;
  8650. return rescale();
  8651. };
  8652. scale.quantiles = function() {
  8653. return thresholds;
  8654. };
  8655. scale.invertExtent = function(y) {
  8656. y = range.indexOf(y);
  8657. return y < 0 ? [ NaN, NaN ] : [ y > 0 ? thresholds[y - 1] : domain[0], y < thresholds.length ? thresholds[y] : domain[domain.length - 1] ];
  8658. };
  8659. scale.copy = function() {
  8660. return d3_scale_quantile(domain, range);
  8661. };
  8662. return rescale();
  8663. }
  8664. d3.scale.quantize = function() {
  8665. return d3_scale_quantize(0, 1, [ 0, 1 ]);
  8666. };
  8667. function d3_scale_quantize(x0, x1, range) {
  8668. var kx, i;
  8669. function scale(x) {
  8670. return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))];
  8671. }
  8672. function rescale() {
  8673. kx = range.length / (x1 - x0);
  8674. i = range.length - 1;
  8675. return scale;
  8676. }
  8677. scale.domain = function(x) {
  8678. if (!arguments.length) return [ x0, x1 ];
  8679. x0 = +x[0];
  8680. x1 = +x[x.length - 1];
  8681. return rescale();
  8682. };
  8683. scale.range = function(x) {
  8684. if (!arguments.length) return range;
  8685. range = x;
  8686. return rescale();
  8687. };
  8688. scale.invertExtent = function(y) {
  8689. y = range.indexOf(y);
  8690. y = y < 0 ? NaN : y / kx + x0;
  8691. return [ y, y + 1 / kx ];
  8692. };
  8693. scale.copy = function() {
  8694. return d3_scale_quantize(x0, x1, range);
  8695. };
  8696. return rescale();
  8697. }
  8698. d3.scale.threshold = function() {
  8699. return d3_scale_threshold([ .5 ], [ 0, 1 ]);
  8700. };
  8701. function d3_scale_threshold(domain, range) {
  8702. function scale(x) {
  8703. if (x <= x) return range[d3.bisect(domain, x)];
  8704. }
  8705. scale.domain = function(_) {
  8706. if (!arguments.length) return domain;
  8707. domain = _;
  8708. return scale;
  8709. };
  8710. scale.range = function(_) {
  8711. if (!arguments.length) return range;
  8712. range = _;
  8713. return scale;
  8714. };
  8715. scale.invertExtent = function(y) {
  8716. y = range.indexOf(y);
  8717. return [ domain[y - 1], domain[y] ];
  8718. };
  8719. scale.copy = function() {
  8720. return d3_scale_threshold(domain, range);
  8721. };
  8722. return scale;
  8723. }
  8724. d3.scale.identity = function() {
  8725. return d3_scale_identity([ 0, 1 ]);
  8726. };
  8727. function d3_scale_identity(domain) {
  8728. function identity(x) {
  8729. return +x;
  8730. }
  8731. identity.invert = identity;
  8732. identity.domain = identity.range = function(x) {
  8733. if (!arguments.length) return domain;
  8734. domain = x.map(identity);
  8735. return identity;
  8736. };
  8737. identity.ticks = function(m) {
  8738. return d3_scale_linearTicks(domain, m);
  8739. };
  8740. identity.tickFormat = function(m, format) {
  8741. return d3_scale_linearTickFormat(domain, m, format);
  8742. };
  8743. identity.copy = function() {
  8744. return d3_scale_identity(domain);
  8745. };
  8746. return identity;
  8747. }
  8748. d3.svg = {};
  8749. function d3_zero() {
  8750. return 0;
  8751. }
  8752. d3.svg.arc = function() {
  8753. var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle;
  8754. function arc() {
  8755. var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfπ, a1 = endAngle.apply(this, arguments) - halfπ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1;
  8756. if (r1 < r0) rc = r1, r1 = r0, r0 = rc;
  8757. if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z";
  8758. var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = [];
  8759. if (ap = (+padAngle.apply(this, arguments) || 0) / 2) {
  8760. rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments);
  8761. if (!cw) p1 *= -1;
  8762. if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap));
  8763. if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap));
  8764. }
  8765. if (r1) {
  8766. x0 = r1 * Math.cos(a0 + p1);
  8767. y0 = r1 * Math.sin(a0 + p1);
  8768. x1 = r1 * Math.cos(a1 - p1);
  8769. y1 = r1 * Math.sin(a1 - p1);
  8770. var l1 = Math.abs(a1 - a0 - 2 * p1) <= π ? 0 : 1;
  8771. if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) {
  8772. var h1 = (a0 + a1) / 2;
  8773. x0 = r1 * Math.cos(h1);
  8774. y0 = r1 * Math.sin(h1);
  8775. x1 = y1 = null;
  8776. }
  8777. } else {
  8778. x0 = y0 = 0;
  8779. }
  8780. if (r0) {
  8781. x2 = r0 * Math.cos(a1 - p0);
  8782. y2 = r0 * Math.sin(a1 - p0);
  8783. x3 = r0 * Math.cos(a0 + p0);
  8784. y3 = r0 * Math.sin(a0 + p0);
  8785. var l0 = Math.abs(a0 - a1 + 2 * p0) <= π ? 0 : 1;
  8786. if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) {
  8787. var h0 = (a0 + a1) / 2;
  8788. x2 = r0 * Math.cos(h0);
  8789. y2 = r0 * Math.sin(h0);
  8790. x3 = y3 = null;
  8791. }
  8792. } else {
  8793. x2 = y2 = 0;
  8794. }
  8795. if (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > .001) {
  8796. cr = r0 < r1 ^ cw ? 0 : 1;
  8797. var rc1 = rc, rc0 = rc;
  8798. if (da < π) {
  8799. var oc = x3 == null ? [ x2, y2 ] : x1 == null ? [ x0, y0 ] : d3_geom_polygonIntersect([ x0, y0 ], [ x3, y3 ], [ x1, y1 ], [ x2, y2 ]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]);
  8800. rc0 = Math.min(rc, (r0 - lc) / (kc - 1));
  8801. rc1 = Math.min(rc, (r1 - lc) / (kc + 1));
  8802. }
  8803. if (x1 != null) {
  8804. var t30 = d3_svg_arcCornerTangents(x3 == null ? [ x2, y2 ] : [ x3, y3 ], [ x0, y0 ], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([ x1, y1 ], [ x2, y2 ], r1, rc1, cw);
  8805. if (rc === rc1) {
  8806. path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]);
  8807. } else {
  8808. path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]);
  8809. }
  8810. } else {
  8811. path.push("M", x0, ",", y0);
  8812. }
  8813. if (x3 != null) {
  8814. var t03 = d3_svg_arcCornerTangents([ x0, y0 ], [ x3, y3 ], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([ x2, y2 ], x1 == null ? [ x0, y0 ] : [ x1, y1 ], r0, -rc0, cw);
  8815. if (rc === rc0) {
  8816. path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]);
  8817. } else {
  8818. path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]);
  8819. }
  8820. } else {
  8821. path.push("L", x2, ",", y2);
  8822. }
  8823. } else {
  8824. path.push("M", x0, ",", y0);
  8825. if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1);
  8826. path.push("L", x2, ",", y2);
  8827. if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3);
  8828. }
  8829. path.push("Z");
  8830. return path.join("");
  8831. }
  8832. function circleSegment(r1, cw) {
  8833. return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1;
  8834. }
  8835. arc.innerRadius = function(v) {
  8836. if (!arguments.length) return innerRadius;
  8837. innerRadius = d3_functor(v);
  8838. return arc;
  8839. };
  8840. arc.outerRadius = function(v) {
  8841. if (!arguments.length) return outerRadius;
  8842. outerRadius = d3_functor(v);
  8843. return arc;
  8844. };
  8845. arc.cornerRadius = function(v) {
  8846. if (!arguments.length) return cornerRadius;
  8847. cornerRadius = d3_functor(v);
  8848. return arc;
  8849. };
  8850. arc.padRadius = function(v) {
  8851. if (!arguments.length) return padRadius;
  8852. padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v);
  8853. return arc;
  8854. };
  8855. arc.startAngle = function(v) {
  8856. if (!arguments.length) return startAngle;
  8857. startAngle = d3_functor(v);
  8858. return arc;
  8859. };
  8860. arc.endAngle = function(v) {
  8861. if (!arguments.length) return endAngle;
  8862. endAngle = d3_functor(v);
  8863. return arc;
  8864. };
  8865. arc.padAngle = function(v) {
  8866. if (!arguments.length) return padAngle;
  8867. padAngle = d3_functor(v);
  8868. return arc;
  8869. };
  8870. arc.centroid = function() {
  8871. var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ;
  8872. return [ Math.cos(a) * r, Math.sin(a) * r ];
  8873. };
  8874. return arc;
  8875. };
  8876. var d3_svg_arcAuto = "auto";
  8877. function d3_svg_arcInnerRadius(d) {
  8878. return d.innerRadius;
  8879. }
  8880. function d3_svg_arcOuterRadius(d) {
  8881. return d.outerRadius;
  8882. }
  8883. function d3_svg_arcStartAngle(d) {
  8884. return d.startAngle;
  8885. }
  8886. function d3_svg_arcEndAngle(d) {
  8887. return d.endAngle;
  8888. }
  8889. function d3_svg_arcPadAngle(d) {
  8890. return d && d.padAngle;
  8891. }
  8892. function d3_svg_arcSweep(x0, y0, x1, y1) {
  8893. return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1;
  8894. }
  8895. function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) {
  8896. var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D * D)), cx0 = (D * dy - dx * d) / d2, cy0 = (-D * dx - dy * d) / d2, cx1 = (D * dy + dx * d) / d2, cy1 = (-D * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3;
  8897. if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1;
  8898. return [ [ cx0 - ox, cy0 - oy ], [ cx0 * r1 / r, cy0 * r1 / r ] ];
  8899. }
  8900. function d3_svg_line(projection) {
  8901. var x = d3_geom_pointX, y = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, tension = .7;
  8902. function line(data) {
  8903. var segments = [], points = [], i = -1, n = data.length, d, fx = d3_functor(x), fy = d3_functor(y);
  8904. function segment() {
  8905. segments.push("M", interpolate(projection(points), tension));
  8906. }
  8907. while (++i < n) {
  8908. if (defined.call(this, d = data[i], i)) {
  8909. points.push([ +fx.call(this, d, i), +fy.call(this, d, i) ]);
  8910. } else if (points.length) {
  8911. segment();
  8912. points = [];
  8913. }
  8914. }
  8915. if (points.length) segment();
  8916. return segments.length ? segments.join("") : null;
  8917. }
  8918. line.x = function(_) {
  8919. if (!arguments.length) return x;
  8920. x = _;
  8921. return line;
  8922. };
  8923. line.y = function(_) {
  8924. if (!arguments.length) return y;
  8925. y = _;
  8926. return line;
  8927. };
  8928. line.defined = function(_) {
  8929. if (!arguments.length) return defined;
  8930. defined = _;
  8931. return line;
  8932. };
  8933. line.interpolate = function(_) {
  8934. if (!arguments.length) return interpolateKey;
  8935. if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
  8936. return line;
  8937. };
  8938. line.tension = function(_) {
  8939. if (!arguments.length) return tension;
  8940. tension = _;
  8941. return line;
  8942. };
  8943. return line;
  8944. }
  8945. d3.svg.line = function() {
  8946. return d3_svg_line(d3_identity);
  8947. };
  8948. var d3_svg_lineInterpolators = d3.map({
  8949. linear: d3_svg_lineLinear,
  8950. "linear-closed": d3_svg_lineLinearClosed,
  8951. step: d3_svg_lineStep,
  8952. "step-before": d3_svg_lineStepBefore,
  8953. "step-after": d3_svg_lineStepAfter,
  8954. basis: d3_svg_lineBasis,
  8955. "basis-open": d3_svg_lineBasisOpen,
  8956. "basis-closed": d3_svg_lineBasisClosed,
  8957. bundle: d3_svg_lineBundle,
  8958. cardinal: d3_svg_lineCardinal,
  8959. "cardinal-open": d3_svg_lineCardinalOpen,
  8960. "cardinal-closed": d3_svg_lineCardinalClosed,
  8961. monotone: d3_svg_lineMonotone
  8962. });
  8963. d3_svg_lineInterpolators.forEach(function(key, value) {
  8964. value.key = key;
  8965. value.closed = /-closed$/.test(key);
  8966. });
  8967. function d3_svg_lineLinear(points) {
  8968. return points.length > 1 ? points.join("L") : points + "Z";
  8969. }
  8970. function d3_svg_lineLinearClosed(points) {
  8971. return points.join("L") + "Z";
  8972. }
  8973. function d3_svg_lineStep(points) {
  8974. var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
  8975. while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]);
  8976. if (n > 1) path.push("H", p[0]);
  8977. return path.join("");
  8978. }
  8979. function d3_svg_lineStepBefore(points) {
  8980. var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
  8981. while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]);
  8982. return path.join("");
  8983. }
  8984. function d3_svg_lineStepAfter(points) {
  8985. var i = 0, n = points.length, p = points[0], path = [ p[0], ",", p[1] ];
  8986. while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]);
  8987. return path.join("");
  8988. }
  8989. function d3_svg_lineCardinalOpen(points, tension) {
  8990. return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension));
  8991. }
  8992. function d3_svg_lineCardinalClosed(points, tension) {
  8993. return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]),
  8994. points), d3_svg_lineCardinalTangents([ points[points.length - 2] ].concat(points, [ points[1] ]), tension));
  8995. }
  8996. function d3_svg_lineCardinal(points, tension) {
  8997. return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension));
  8998. }
  8999. function d3_svg_lineHermite(points, tangents) {
  9000. if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) {
  9001. return d3_svg_lineLinear(points);
  9002. }
  9003. var quad = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t0 = tangents[0], t = t0, pi = 1;
  9004. if (quad) {
  9005. path += "Q" + (p[0] - t0[0] * 2 / 3) + "," + (p[1] - t0[1] * 2 / 3) + "," + p[0] + "," + p[1];
  9006. p0 = points[1];
  9007. pi = 2;
  9008. }
  9009. if (tangents.length > 1) {
  9010. t = tangents[1];
  9011. p = points[pi];
  9012. pi++;
  9013. path += "C" + (p0[0] + t0[0]) + "," + (p0[1] + t0[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
  9014. for (var i = 2; i < tangents.length; i++, pi++) {
  9015. p = points[pi];
  9016. t = tangents[i];
  9017. path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1];
  9018. }
  9019. }
  9020. if (quad) {
  9021. var lp = points[pi];
  9022. path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1];
  9023. }
  9024. return path;
  9025. }
  9026. function d3_svg_lineCardinalTangents(points, tension) {
  9027. var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length;
  9028. while (++i < n) {
  9029. p0 = p1;
  9030. p1 = p2;
  9031. p2 = points[i];
  9032. tangents.push([ a * (p2[0] - p0[0]), a * (p2[1] - p0[1]) ]);
  9033. }
  9034. return tangents;
  9035. }
  9036. function d3_svg_lineBasis(points) {
  9037. if (points.length < 3) return d3_svg_lineLinear(points);
  9038. var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px = [ x0, x0, x0, (pi = points[1])[0] ], py = [ y0, y0, y0, pi[1] ], path = [ x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
  9039. points.push(points[n - 1]);
  9040. while (++i <= n) {
  9041. pi = points[i];
  9042. px.shift();
  9043. px.push(pi[0]);
  9044. py.shift();
  9045. py.push(pi[1]);
  9046. d3_svg_lineBasisBezier(path, px, py);
  9047. }
  9048. points.pop();
  9049. path.push("L", pi);
  9050. return path.join("");
  9051. }
  9052. function d3_svg_lineBasisOpen(points) {
  9053. if (points.length < 4) return d3_svg_lineLinear(points);
  9054. var path = [], i = -1, n = points.length, pi, px = [ 0 ], py = [ 0 ];
  9055. while (++i < 3) {
  9056. pi = points[i];
  9057. px.push(pi[0]);
  9058. py.push(pi[1]);
  9059. }
  9060. path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py));
  9061. --i;
  9062. while (++i < n) {
  9063. pi = points[i];
  9064. px.shift();
  9065. px.push(pi[0]);
  9066. py.shift();
  9067. py.push(pi[1]);
  9068. d3_svg_lineBasisBezier(path, px, py);
  9069. }
  9070. return path.join("");
  9071. }
  9072. function d3_svg_lineBasisClosed(points) {
  9073. var path, i = -1, n = points.length, m = n + 4, pi, px = [], py = [];
  9074. while (++i < 4) {
  9075. pi = points[i % n];
  9076. px.push(pi[0]);
  9077. py.push(pi[1]);
  9078. }
  9079. path = [ d3_svg_lineDot4(d3_svg_lineBasisBezier3, px), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py) ];
  9080. --i;
  9081. while (++i < m) {
  9082. pi = points[i % n];
  9083. px.shift();
  9084. px.push(pi[0]);
  9085. py.shift();
  9086. py.push(pi[1]);
  9087. d3_svg_lineBasisBezier(path, px, py);
  9088. }
  9089. return path.join("");
  9090. }
  9091. function d3_svg_lineBundle(points, tension) {
  9092. var n = points.length - 1;
  9093. if (n) {
  9094. var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t;
  9095. while (++i <= n) {
  9096. p = points[i];
  9097. t = i / n;
  9098. p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx);
  9099. p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy);
  9100. }
  9101. }
  9102. return d3_svg_lineBasis(points);
  9103. }
  9104. function d3_svg_lineDot4(a, b) {
  9105. return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3];
  9106. }
  9107. var d3_svg_lineBasisBezier1 = [ 0, 2 / 3, 1 / 3, 0 ], d3_svg_lineBasisBezier2 = [ 0, 1 / 3, 2 / 3, 0 ], d3_svg_lineBasisBezier3 = [ 0, 1 / 6, 2 / 3, 1 / 6 ];
  9108. function d3_svg_lineBasisBezier(path, x, y) {
  9109. path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y));
  9110. }
  9111. function d3_svg_lineSlope(p0, p1) {
  9112. return (p1[1] - p0[1]) / (p1[0] - p0[0]);
  9113. }
  9114. function d3_svg_lineFiniteDifferences(points) {
  9115. var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1);
  9116. while (++i < j) {
  9117. m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2;
  9118. }
  9119. m[i] = d;
  9120. return m;
  9121. }
  9122. function d3_svg_lineMonotoneTangents(points) {
  9123. var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1;
  9124. while (++i < j) {
  9125. d = d3_svg_lineSlope(points[i], points[i + 1]);
  9126. if (abs(d) < ε) {
  9127. m[i] = m[i + 1] = 0;
  9128. } else {
  9129. a = m[i] / d;
  9130. b = m[i + 1] / d;
  9131. s = a * a + b * b;
  9132. if (s > 9) {
  9133. s = d * 3 / Math.sqrt(s);
  9134. m[i] = s * a;
  9135. m[i + 1] = s * b;
  9136. }
  9137. }
  9138. }
  9139. i = -1;
  9140. while (++i <= j) {
  9141. s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i]));
  9142. tangents.push([ s || 0, m[i] * s || 0 ]);
  9143. }
  9144. return tangents;
  9145. }
  9146. function d3_svg_lineMonotone(points) {
  9147. return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points));
  9148. }
  9149. d3.svg.line.radial = function() {
  9150. var line = d3_svg_line(d3_svg_lineRadial);
  9151. line.radius = line.x, delete line.x;
  9152. line.angle = line.y, delete line.y;
  9153. return line;
  9154. };
  9155. function d3_svg_lineRadial(points) {
  9156. var point, i = -1, n = points.length, r, a;
  9157. while (++i < n) {
  9158. point = points[i];
  9159. r = point[0];
  9160. a = point[1] - halfπ;
  9161. point[0] = r * Math.cos(a);
  9162. point[1] = r * Math.sin(a);
  9163. }
  9164. return points;
  9165. }
  9166. function d3_svg_area(projection) {
  9167. var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined = d3_true, interpolate = d3_svg_lineLinear, interpolateKey = interpolate.key, interpolateReverse = interpolate, L = "L", tension = .7;
  9168. function area(data) {
  9169. var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() {
  9170. return x;
  9171. } : d3_functor(x1), fy1 = y0 === y1 ? function() {
  9172. return y;
  9173. } : d3_functor(y1), x, y;
  9174. function segment() {
  9175. segments.push("M", interpolate(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z");
  9176. }
  9177. while (++i < n) {
  9178. if (defined.call(this, d = data[i], i)) {
  9179. points0.push([ x = +fx0.call(this, d, i), y = +fy0.call(this, d, i) ]);
  9180. points1.push([ +fx1.call(this, d, i), +fy1.call(this, d, i) ]);
  9181. } else if (points0.length) {
  9182. segment();
  9183. points0 = [];
  9184. points1 = [];
  9185. }
  9186. }
  9187. if (points0.length) segment();
  9188. return segments.length ? segments.join("") : null;
  9189. }
  9190. area.x = function(_) {
  9191. if (!arguments.length) return x1;
  9192. x0 = x1 = _;
  9193. return area;
  9194. };
  9195. area.x0 = function(_) {
  9196. if (!arguments.length) return x0;
  9197. x0 = _;
  9198. return area;
  9199. };
  9200. area.x1 = function(_) {
  9201. if (!arguments.length) return x1;
  9202. x1 = _;
  9203. return area;
  9204. };
  9205. area.y = function(_) {
  9206. if (!arguments.length) return y1;
  9207. y0 = y1 = _;
  9208. return area;
  9209. };
  9210. area.y0 = function(_) {
  9211. if (!arguments.length) return y0;
  9212. y0 = _;
  9213. return area;
  9214. };
  9215. area.y1 = function(_) {
  9216. if (!arguments.length) return y1;
  9217. y1 = _;
  9218. return area;
  9219. };
  9220. area.defined = function(_) {
  9221. if (!arguments.length) return defined;
  9222. defined = _;
  9223. return area;
  9224. };
  9225. area.interpolate = function(_) {
  9226. if (!arguments.length) return interpolateKey;
  9227. if (typeof _ === "function") interpolateKey = interpolate = _; else interpolateKey = (interpolate = d3_svg_lineInterpolators.get(_) || d3_svg_lineLinear).key;
  9228. interpolateReverse = interpolate.reverse || interpolate;
  9229. L = interpolate.closed ? "M" : "L";
  9230. return area;
  9231. };
  9232. area.tension = function(_) {
  9233. if (!arguments.length) return tension;
  9234. tension = _;
  9235. return area;
  9236. };
  9237. return area;
  9238. }
  9239. d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter;
  9240. d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore;
  9241. d3.svg.area = function() {
  9242. return d3_svg_area(d3_identity);
  9243. };
  9244. d3.svg.area.radial = function() {
  9245. var area = d3_svg_area(d3_svg_lineRadial);
  9246. area.radius = area.x, delete area.x;
  9247. area.innerRadius = area.x0, delete area.x0;
  9248. area.outerRadius = area.x1, delete area.x1;
  9249. area.angle = area.y, delete area.y;
  9250. area.startAngle = area.y0, delete area.y0;
  9251. area.endAngle = area.y1, delete area.y1;
  9252. return area;
  9253. };
  9254. d3.svg.chord = function() {
  9255. var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle;
  9256. function chord(d, i) {
  9257. var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i);
  9258. return "M" + s.p0 + arc(s.r, s.p1, s.a1 - s.a0) + (equals(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z";
  9259. }
  9260. function subgroup(self, f, d, i) {
  9261. var subgroup = f.call(self, d, i), r = radius.call(self, subgroup, i), a0 = startAngle.call(self, subgroup, i) - halfπ, a1 = endAngle.call(self, subgroup, i) - halfπ;
  9262. return {
  9263. r: r,
  9264. a0: a0,
  9265. a1: a1,
  9266. p0: [ r * Math.cos(a0), r * Math.sin(a0) ],
  9267. p1: [ r * Math.cos(a1), r * Math.sin(a1) ]
  9268. };
  9269. }
  9270. function equals(a, b) {
  9271. return a.a0 == b.a0 && a.a1 == b.a1;
  9272. }
  9273. function arc(r, p, a) {
  9274. return "A" + r + "," + r + " 0 " + +(a > π) + ",1 " + p;
  9275. }
  9276. function curve(r0, p0, r1, p1) {
  9277. return "Q 0,0 " + p1;
  9278. }
  9279. chord.radius = function(v) {
  9280. if (!arguments.length) return radius;
  9281. radius = d3_functor(v);
  9282. return chord;
  9283. };
  9284. chord.source = function(v) {
  9285. if (!arguments.length) return source;
  9286. source = d3_functor(v);
  9287. return chord;
  9288. };
  9289. chord.target = function(v) {
  9290. if (!arguments.length) return target;
  9291. target = d3_functor(v);
  9292. return chord;
  9293. };
  9294. chord.startAngle = function(v) {
  9295. if (!arguments.length) return startAngle;
  9296. startAngle = d3_functor(v);
  9297. return chord;
  9298. };
  9299. chord.endAngle = function(v) {
  9300. if (!arguments.length) return endAngle;
  9301. endAngle = d3_functor(v);
  9302. return chord;
  9303. };
  9304. return chord;
  9305. };
  9306. function d3_svg_chordRadius(d) {
  9307. return d.radius;
  9308. }
  9309. d3.svg.diagonal = function() {
  9310. var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection;
  9311. function diagonal(d, i) {
  9312. var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [ p0, {
  9313. x: p0.x,
  9314. y: m
  9315. }, {
  9316. x: p3.x,
  9317. y: m
  9318. }, p3 ];
  9319. p = p.map(projection);
  9320. return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3];
  9321. }
  9322. diagonal.source = function(x) {
  9323. if (!arguments.length) return source;
  9324. source = d3_functor(x);
  9325. return diagonal;
  9326. };
  9327. diagonal.target = function(x) {
  9328. if (!arguments.length) return target;
  9329. target = d3_functor(x);
  9330. return diagonal;
  9331. };
  9332. diagonal.projection = function(x) {
  9333. if (!arguments.length) return projection;
  9334. projection = x;
  9335. return diagonal;
  9336. };
  9337. return diagonal;
  9338. };
  9339. function d3_svg_diagonalProjection(d) {
  9340. return [ d.x, d.y ];
  9341. }
  9342. d3.svg.diagonal.radial = function() {
  9343. var diagonal = d3.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection;
  9344. diagonal.projection = function(x) {
  9345. return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection;
  9346. };
  9347. return diagonal;
  9348. };
  9349. function d3_svg_diagonalRadialProjection(projection) {
  9350. return function() {
  9351. var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ;
  9352. return [ r * Math.cos(a), r * Math.sin(a) ];
  9353. };
  9354. }
  9355. d3.svg.symbol = function() {
  9356. var type = d3_svg_symbolType, size = d3_svg_symbolSize;
  9357. function symbol(d, i) {
  9358. return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i));
  9359. }
  9360. symbol.type = function(x) {
  9361. if (!arguments.length) return type;
  9362. type = d3_functor(x);
  9363. return symbol;
  9364. };
  9365. symbol.size = function(x) {
  9366. if (!arguments.length) return size;
  9367. size = d3_functor(x);
  9368. return symbol;
  9369. };
  9370. return symbol;
  9371. };
  9372. function d3_svg_symbolSize() {
  9373. return 64;
  9374. }
  9375. function d3_svg_symbolType() {
  9376. return "circle";
  9377. }
  9378. function d3_svg_symbolCircle(size) {
  9379. var r = Math.sqrt(size / π);
  9380. return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z";
  9381. }
  9382. var d3_svg_symbols = d3.map({
  9383. circle: d3_svg_symbolCircle,
  9384. cross: function(size) {
  9385. var r = Math.sqrt(size / 5) / 2;
  9386. return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z";
  9387. },
  9388. diamond: function(size) {
  9389. var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30;
  9390. return "M0," + -ry + "L" + rx + ",0" + " 0," + ry + " " + -rx + ",0" + "Z";
  9391. },
  9392. square: function(size) {
  9393. var r = Math.sqrt(size) / 2;
  9394. return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z";
  9395. },
  9396. "triangle-down": function(size) {
  9397. var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
  9398. return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z";
  9399. },
  9400. "triangle-up": function(size) {
  9401. var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2;
  9402. return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z";
  9403. }
  9404. });
  9405. d3.svg.symbolTypes = d3_svg_symbols.keys();
  9406. var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians);
  9407. d3_selectionPrototype.transition = function(name) {
  9408. var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name), subgroups = [], subgroup, node, transition = d3_transitionInherit || {
  9409. time: Date.now(),
  9410. ease: d3_ease_cubicInOut,
  9411. delay: 0,
  9412. duration: 250
  9413. };
  9414. for (var j = -1, m = this.length; ++j < m; ) {
  9415. subgroups.push(subgroup = []);
  9416. for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
  9417. if (node = group[i]) d3_transitionNode(node, i, ns, id, transition);
  9418. subgroup.push(node);
  9419. }
  9420. }
  9421. return d3_transition(subgroups, ns, id);
  9422. };
  9423. d3_selectionPrototype.interrupt = function(name) {
  9424. return this.each(name == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name)));
  9425. };
  9426. var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace());
  9427. function d3_selection_interruptNS(ns) {
  9428. return function() {
  9429. var lock, activeId, active;
  9430. if ((lock = this[ns]) && (active = lock[activeId = lock.active])) {
  9431. active.timer.c = null;
  9432. active.timer.t = NaN;
  9433. if (--lock.count) delete lock[activeId]; else delete this[ns];
  9434. lock.active += .5;
  9435. active.event && active.event.interrupt.call(this, this.__data__, active.index);
  9436. }
  9437. };
  9438. }
  9439. function d3_transition(groups, ns, id) {
  9440. d3_subclass(groups, d3_transitionPrototype);
  9441. groups.namespace = ns;
  9442. groups.id = id;
  9443. return groups;
  9444. }
  9445. var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit;
  9446. d3_transitionPrototype.call = d3_selectionPrototype.call;
  9447. d3_transitionPrototype.empty = d3_selectionPrototype.empty;
  9448. d3_transitionPrototype.node = d3_selectionPrototype.node;
  9449. d3_transitionPrototype.size = d3_selectionPrototype.size;
  9450. d3.transition = function(selection, name) {
  9451. return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name) : selection : d3.selection().transition(selection);
  9452. };
  9453. d3.transition.prototype = d3_transitionPrototype;
  9454. d3_transitionPrototype.select = function(selector) {
  9455. var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node;
  9456. selector = d3_selection_selector(selector);
  9457. for (var j = -1, m = this.length; ++j < m; ) {
  9458. subgroups.push(subgroup = []);
  9459. for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
  9460. if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) {
  9461. if ("__data__" in node) subnode.__data__ = node.__data__;
  9462. d3_transitionNode(subnode, i, ns, id, node[ns][id]);
  9463. subgroup.push(subnode);
  9464. } else {
  9465. subgroup.push(null);
  9466. }
  9467. }
  9468. }
  9469. return d3_transition(subgroups, ns, id);
  9470. };
  9471. d3_transitionPrototype.selectAll = function(selector) {
  9472. var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition;
  9473. selector = d3_selection_selectorAll(selector);
  9474. for (var j = -1, m = this.length; ++j < m; ) {
  9475. for (var group = this[j], i = -1, n = group.length; ++i < n; ) {
  9476. if (node = group[i]) {
  9477. transition = node[ns][id];
  9478. subnodes = selector.call(node, node.__data__, i, j);
  9479. subgroups.push(subgroup = []);
  9480. for (var k = -1, o = subnodes.length; ++k < o; ) {
  9481. if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition);
  9482. subgroup.push(subnode);
  9483. }
  9484. }
  9485. }
  9486. }
  9487. return d3_transition(subgroups, ns, id);
  9488. };
  9489. d3_transitionPrototype.filter = function(filter) {
  9490. var subgroups = [], subgroup, group, node;
  9491. if (typeof filter !== "function") filter = d3_selection_filter(filter);
  9492. for (var j = 0, m = this.length; j < m; j++) {
  9493. subgroups.push(subgroup = []);
  9494. for (var group = this[j], i = 0, n = group.length; i < n; i++) {
  9495. if ((node = group[i]) && filter.call(node, node.__data__, i, j)) {
  9496. subgroup.push(node);
  9497. }
  9498. }
  9499. }
  9500. return d3_transition(subgroups, this.namespace, this.id);
  9501. };
  9502. d3_transitionPrototype.tween = function(name, tween) {
  9503. var id = this.id, ns = this.namespace;
  9504. if (arguments.length < 2) return this.node()[ns][id].tween.get(name);
  9505. return d3_selection_each(this, tween == null ? function(node) {
  9506. node[ns][id].tween.remove(name);
  9507. } : function(node) {
  9508. node[ns][id].tween.set(name, tween);
  9509. });
  9510. };
  9511. function d3_transition_tween(groups, name, value, tween) {
  9512. var id = groups.id, ns = groups.namespace;
  9513. return d3_selection_each(groups, typeof value === "function" ? function(node, i, j) {
  9514. node[ns][id].tween.set(name, tween(value.call(node, node.__data__, i, j)));
  9515. } : (value = tween(value), function(node) {
  9516. node[ns][id].tween.set(name, value);
  9517. }));
  9518. }
  9519. d3_transitionPrototype.attr = function(nameNS, value) {
  9520. if (arguments.length < 2) {
  9521. for (value in nameNS) this.attr(value, nameNS[value]);
  9522. return this;
  9523. }
  9524. var interpolate = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name = d3.ns.qualify(nameNS);
  9525. function attrNull() {
  9526. this.removeAttribute(name);
  9527. }
  9528. function attrNullNS() {
  9529. this.removeAttributeNS(name.space, name.local);
  9530. }
  9531. function attrTween(b) {
  9532. return b == null ? attrNull : (b += "", function() {
  9533. var a = this.getAttribute(name), i;
  9534. return a !== b && (i = interpolate(a, b), function(t) {
  9535. this.setAttribute(name, i(t));
  9536. });
  9537. });
  9538. }
  9539. function attrTweenNS(b) {
  9540. return b == null ? attrNullNS : (b += "", function() {
  9541. var a = this.getAttributeNS(name.space, name.local), i;
  9542. return a !== b && (i = interpolate(a, b), function(t) {
  9543. this.setAttributeNS(name.space, name.local, i(t));
  9544. });
  9545. });
  9546. }
  9547. return d3_transition_tween(this, "attr." + nameNS, value, name.local ? attrTweenNS : attrTween);
  9548. };
  9549. d3_transitionPrototype.attrTween = function(nameNS, tween) {
  9550. var name = d3.ns.qualify(nameNS);
  9551. function attrTween(d, i) {
  9552. var f = tween.call(this, d, i, this.getAttribute(name));
  9553. return f && function(t) {
  9554. this.setAttribute(name, f(t));
  9555. };
  9556. }
  9557. function attrTweenNS(d, i) {
  9558. var f = tween.call(this, d, i, this.getAttributeNS(name.space, name.local));
  9559. return f && function(t) {
  9560. this.setAttributeNS(name.space, name.local, f(t));
  9561. };
  9562. }
  9563. return this.tween("attr." + nameNS, name.local ? attrTweenNS : attrTween);
  9564. };
  9565. d3_transitionPrototype.style = function(name, value, priority) {
  9566. var n = arguments.length;
  9567. if (n < 3) {
  9568. if (typeof name !== "string") {
  9569. if (n < 2) value = "";
  9570. for (priority in name) this.style(priority, name[priority], value);
  9571. return this;
  9572. }
  9573. priority = "";
  9574. }
  9575. function styleNull() {
  9576. this.style.removeProperty(name);
  9577. }
  9578. function styleString(b) {
  9579. return b == null ? styleNull : (b += "", function() {
  9580. var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name), i;
  9581. return a !== b && (i = d3_interpolate(a, b), function(t) {
  9582. this.style.setProperty(name, i(t), priority);
  9583. });
  9584. });
  9585. }
  9586. return d3_transition_tween(this, "style." + name, value, styleString);
  9587. };
  9588. d3_transitionPrototype.styleTween = function(name, tween, priority) {
  9589. if (arguments.length < 3) priority = "";
  9590. function styleTween(d, i) {
  9591. var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name));
  9592. return f && function(t) {
  9593. this.style.setProperty(name, f(t), priority);
  9594. };
  9595. }
  9596. return this.tween("style." + name, styleTween);
  9597. };
  9598. d3_transitionPrototype.text = function(value) {
  9599. return d3_transition_tween(this, "text", value, d3_transition_text);
  9600. };
  9601. function d3_transition_text(b) {
  9602. if (b == null) b = "";
  9603. return function() {
  9604. this.textContent = b;
  9605. };
  9606. }
  9607. d3_transitionPrototype.remove = function() {
  9608. var ns = this.namespace;
  9609. return this.each("end.transition", function() {
  9610. var p;
  9611. if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this);
  9612. });
  9613. };
  9614. d3_transitionPrototype.ease = function(value) {
  9615. var id = this.id, ns = this.namespace;
  9616. if (arguments.length < 1) return this.node()[ns][id].ease;
  9617. if (typeof value !== "function") value = d3.ease.apply(d3, arguments);
  9618. return d3_selection_each(this, function(node) {
  9619. node[ns][id].ease = value;
  9620. });
  9621. };
  9622. d3_transitionPrototype.delay = function(value) {
  9623. var id = this.id, ns = this.namespace;
  9624. if (arguments.length < 1) return this.node()[ns][id].delay;
  9625. return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
  9626. node[ns][id].delay = +value.call(node, node.__data__, i, j);
  9627. } : (value = +value, function(node) {
  9628. node[ns][id].delay = value;
  9629. }));
  9630. };
  9631. d3_transitionPrototype.duration = function(value) {
  9632. var id = this.id, ns = this.namespace;
  9633. if (arguments.length < 1) return this.node()[ns][id].duration;
  9634. return d3_selection_each(this, typeof value === "function" ? function(node, i, j) {
  9635. node[ns][id].duration = Math.max(1, value.call(node, node.__data__, i, j));
  9636. } : (value = Math.max(1, value), function(node) {
  9637. node[ns][id].duration = value;
  9638. }));
  9639. };
  9640. d3_transitionPrototype.each = function(type, listener) {
  9641. var id = this.id, ns = this.namespace;
  9642. if (arguments.length < 2) {
  9643. var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId;
  9644. try {
  9645. d3_transitionInheritId = id;
  9646. d3_selection_each(this, function(node, i, j) {
  9647. d3_transitionInherit = node[ns][id];
  9648. type.call(node, node.__data__, i, j);
  9649. });
  9650. } finally {
  9651. d3_transitionInherit = inherit;
  9652. d3_transitionInheritId = inheritId;
  9653. }
  9654. } else {
  9655. d3_selection_each(this, function(node) {
  9656. var transition = node[ns][id];
  9657. (transition.event || (transition.event = d3.dispatch("start", "end", "interrupt"))).on(type, listener);
  9658. });
  9659. }
  9660. return this;
  9661. };
  9662. d3_transitionPrototype.transition = function() {
  9663. var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition;
  9664. for (var j = 0, m = this.length; j < m; j++) {
  9665. subgroups.push(subgroup = []);
  9666. for (var group = this[j], i = 0, n = group.length; i < n; i++) {
  9667. if (node = group[i]) {
  9668. transition = node[ns][id0];
  9669. d3_transitionNode(node, i, ns, id1, {
  9670. time: transition.time,
  9671. ease: transition.ease,
  9672. delay: transition.delay + transition.duration,
  9673. duration: transition.duration
  9674. });
  9675. }
  9676. subgroup.push(node);
  9677. }
  9678. }
  9679. return d3_transition(subgroups, ns, id1);
  9680. };
  9681. function d3_transitionNamespace(name) {
  9682. return name == null ? "__transition__" : "__transition_" + name + "__";
  9683. }
  9684. function d3_transitionNode(node, i, ns, id, inherit) {
  9685. var lock = node[ns] || (node[ns] = {
  9686. active: 0,
  9687. count: 0
  9688. }), transition = lock[id], time, timer, duration, ease, tweens;
  9689. function schedule(elapsed) {
  9690. var delay = transition.delay;
  9691. timer.t = delay + time;
  9692. if (delay <= elapsed) return start(elapsed - delay);
  9693. timer.c = start;
  9694. }
  9695. function start(elapsed) {
  9696. var activeId = lock.active, active = lock[activeId];
  9697. if (active) {
  9698. active.timer.c = null;
  9699. active.timer.t = NaN;
  9700. --lock.count;
  9701. delete lock[activeId];
  9702. active.event && active.event.interrupt.call(node, node.__data__, active.index);
  9703. }
  9704. for (var cancelId in lock) {
  9705. if (+cancelId < id) {
  9706. var cancel = lock[cancelId];
  9707. cancel.timer.c = null;
  9708. cancel.timer.t = NaN;
  9709. --lock.count;
  9710. delete lock[cancelId];
  9711. }
  9712. }
  9713. timer.c = tick;
  9714. d3_timer(function() {
  9715. if (timer.c && tick(elapsed || 1)) {
  9716. timer.c = null;
  9717. timer.t = NaN;
  9718. }
  9719. return 1;
  9720. }, 0, time);
  9721. lock.active = id;
  9722. transition.event && transition.event.start.call(node, node.__data__, i);
  9723. tweens = [];
  9724. transition.tween.forEach(function(key, value) {
  9725. if (value = value.call(node, node.__data__, i)) {
  9726. tweens.push(value);
  9727. }
  9728. });
  9729. ease = transition.ease;
  9730. duration = transition.duration;
  9731. }
  9732. function tick(elapsed) {
  9733. var t = elapsed / duration, e = ease(t), n = tweens.length;
  9734. while (n > 0) {
  9735. tweens[--n].call(node, e);
  9736. }
  9737. if (t >= 1) {
  9738. transition.event && transition.event.end.call(node, node.__data__, i);
  9739. if (--lock.count) delete lock[id]; else delete node[ns];
  9740. return 1;
  9741. }
  9742. }
  9743. if (!transition) {
  9744. time = inherit.time;
  9745. timer = d3_timer(schedule, 0, time);
  9746. transition = lock[id] = {
  9747. tween: new d3_Map(),
  9748. time: time,
  9749. timer: timer,
  9750. delay: inherit.delay,
  9751. duration: inherit.duration,
  9752. ease: inherit.ease,
  9753. index: i
  9754. };
  9755. inherit = null;
  9756. ++lock.count;
  9757. }
  9758. }
  9759. d3.svg.axis = function() {
  9760. var scale = d3.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [ 10 ], tickValues = null, tickFormat_;
  9761. function axis(g) {
  9762. g.each(function() {
  9763. var g = d3.select(this);
  9764. var scale0 = this.__chart__ || scale, scale1 = this.__chart__ = scale.copy();
  9765. var ticks = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g.selectAll(".tick").data(ticks, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d3.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d3.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform;
  9766. var range = d3_scaleRange(scale1), path = g.selectAll(".domain").data([ 0 ]), pathUpdate = (path.enter().append("path").attr("class", "domain"),
  9767. d3.transition(path));
  9768. tickEnter.append("line");
  9769. tickEnter.append("text");
  9770. var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2;
  9771. if (orient === "bottom" || orient === "top") {
  9772. tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2";
  9773. text.attr("dy", sign < 0 ? "0em" : ".71em").style("text-anchor", "middle");
  9774. pathUpdate.attr("d", "M" + range[0] + "," + sign * outerTickSize + "V0H" + range[1] + "V" + sign * outerTickSize);
  9775. } else {
  9776. tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2";
  9777. text.attr("dy", ".32em").style("text-anchor", sign < 0 ? "end" : "start");
  9778. pathUpdate.attr("d", "M" + sign * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign * outerTickSize);
  9779. }
  9780. lineEnter.attr(y2, sign * innerTickSize);
  9781. textEnter.attr(y1, sign * tickSpacing);
  9782. lineUpdate.attr(x2, 0).attr(y2, sign * innerTickSize);
  9783. textUpdate.attr(x1, 0).attr(y1, sign * tickSpacing);
  9784. if (scale1.rangeBand) {
  9785. var x = scale1, dx = x.rangeBand() / 2;
  9786. scale0 = scale1 = function(d) {
  9787. return x(d) + dx;
  9788. };
  9789. } else if (scale0.rangeBand) {
  9790. scale0 = scale1;
  9791. } else {
  9792. tickExit.call(tickTransform, scale1, scale0);
  9793. }
  9794. tickEnter.call(tickTransform, scale0, scale1);
  9795. tickUpdate.call(tickTransform, scale1, scale1);
  9796. });
  9797. }
  9798. axis.scale = function(x) {
  9799. if (!arguments.length) return scale;
  9800. scale = x;
  9801. return axis;
  9802. };
  9803. axis.orient = function(x) {
  9804. if (!arguments.length) return orient;
  9805. orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient;
  9806. return axis;
  9807. };
  9808. axis.ticks = function() {
  9809. if (!arguments.length) return tickArguments_;
  9810. tickArguments_ = d3_array(arguments);
  9811. return axis;
  9812. };
  9813. axis.tickValues = function(x) {
  9814. if (!arguments.length) return tickValues;
  9815. tickValues = x;
  9816. return axis;
  9817. };
  9818. axis.tickFormat = function(x) {
  9819. if (!arguments.length) return tickFormat_;
  9820. tickFormat_ = x;
  9821. return axis;
  9822. };
  9823. axis.tickSize = function(x) {
  9824. var n = arguments.length;
  9825. if (!n) return innerTickSize;
  9826. innerTickSize = +x;
  9827. outerTickSize = +arguments[n - 1];
  9828. return axis;
  9829. };
  9830. axis.innerTickSize = function(x) {
  9831. if (!arguments.length) return innerTickSize;
  9832. innerTickSize = +x;
  9833. return axis;
  9834. };
  9835. axis.outerTickSize = function(x) {
  9836. if (!arguments.length) return outerTickSize;
  9837. outerTickSize = +x;
  9838. return axis;
  9839. };
  9840. axis.tickPadding = function(x) {
  9841. if (!arguments.length) return tickPadding;
  9842. tickPadding = +x;
  9843. return axis;
  9844. };
  9845. axis.tickSubdivide = function() {
  9846. return arguments.length && axis;
  9847. };
  9848. return axis;
  9849. };
  9850. var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = {
  9851. top: 1,
  9852. right: 1,
  9853. bottom: 1,
  9854. left: 1
  9855. };
  9856. function d3_svg_axisX(selection, x0, x1) {
  9857. selection.attr("transform", function(d) {
  9858. var v0 = x0(d);
  9859. return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)";
  9860. });
  9861. }
  9862. function d3_svg_axisY(selection, y0, y1) {
  9863. selection.attr("transform", function(d) {
  9864. var v0 = y0(d);
  9865. return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")";
  9866. });
  9867. }
  9868. d3.svg.brush = function() {
  9869. var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [ 0, 0 ], yExtent = [ 0, 0 ], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0];
  9870. function brush(g) {
  9871. g.each(function() {
  9872. var g = d3.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart);
  9873. var background = g.selectAll(".background").data([ 0 ]);
  9874. background.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair");
  9875. g.selectAll(".extent").data([ 0 ]).enter().append("rect").attr("class", "extent").style("cursor", "move");
  9876. var resize = g.selectAll(".resize").data(resizes, d3_identity);
  9877. resize.exit().remove();
  9878. resize.enter().append("g").attr("class", function(d) {
  9879. return "resize " + d;
  9880. }).style("cursor", function(d) {
  9881. return d3_svg_brushCursor[d];
  9882. }).append("rect").attr("x", function(d) {
  9883. return /[ew]$/.test(d) ? -3 : null;
  9884. }).attr("y", function(d) {
  9885. return /^[ns]/.test(d) ? -3 : null;
  9886. }).attr("width", 6).attr("height", 6).style("visibility", "hidden");
  9887. resize.style("display", brush.empty() ? "none" : null);
  9888. var gUpdate = d3.transition(g), backgroundUpdate = d3.transition(background), range;
  9889. if (x) {
  9890. range = d3_scaleRange(x);
  9891. backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]);
  9892. redrawX(gUpdate);
  9893. }
  9894. if (y) {
  9895. range = d3_scaleRange(y);
  9896. backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]);
  9897. redrawY(gUpdate);
  9898. }
  9899. redraw(gUpdate);
  9900. });
  9901. }
  9902. brush.event = function(g) {
  9903. g.each(function() {
  9904. var event_ = event.of(this, arguments), extent1 = {
  9905. x: xExtent,
  9906. y: yExtent,
  9907. i: xExtentDomain,
  9908. j: yExtentDomain
  9909. }, extent0 = this.__chart__ || extent1;
  9910. this.__chart__ = extent1;
  9911. if (d3_transitionInheritId) {
  9912. d3.select(this).transition().each("start.brush", function() {
  9913. xExtentDomain = extent0.i;
  9914. yExtentDomain = extent0.j;
  9915. xExtent = extent0.x;
  9916. yExtent = extent0.y;
  9917. event_({
  9918. type: "brushstart"
  9919. });
  9920. }).tween("brush:brush", function() {
  9921. var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y);
  9922. xExtentDomain = yExtentDomain = null;
  9923. return function(t) {
  9924. xExtent = extent1.x = xi(t);
  9925. yExtent = extent1.y = yi(t);
  9926. event_({
  9927. type: "brush",
  9928. mode: "resize"
  9929. });
  9930. };
  9931. }).each("end.brush", function() {
  9932. xExtentDomain = extent1.i;
  9933. yExtentDomain = extent1.j;
  9934. event_({
  9935. type: "brush",
  9936. mode: "resize"
  9937. });
  9938. event_({
  9939. type: "brushend"
  9940. });
  9941. });
  9942. } else {
  9943. event_({
  9944. type: "brushstart"
  9945. });
  9946. event_({
  9947. type: "brush",
  9948. mode: "resize"
  9949. });
  9950. event_({
  9951. type: "brushend"
  9952. });
  9953. }
  9954. });
  9955. };
  9956. function redraw(g) {
  9957. g.selectAll(".resize").attr("transform", function(d) {
  9958. return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")";
  9959. });
  9960. }
  9961. function redrawX(g) {
  9962. g.select(".extent").attr("x", xExtent[0]);
  9963. g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]);
  9964. }
  9965. function redrawY(g) {
  9966. g.select(".extent").attr("y", yExtent[0]);
  9967. g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]);
  9968. }
  9969. function brushstart() {
  9970. var target = this, eventTarget = d3.select(d3.event.target), event_ = event.of(target, arguments), g = d3.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d3.mouse(target), offset;
  9971. var w = d3.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup);
  9972. if (d3.event.changedTouches) {
  9973. w.on("touchmove.brush", brushmove).on("touchend.brush", brushend);
  9974. } else {
  9975. w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend);
  9976. }
  9977. g.interrupt().selectAll("*").interrupt();
  9978. if (dragging) {
  9979. origin[0] = xExtent[0] - origin[0];
  9980. origin[1] = yExtent[0] - origin[1];
  9981. } else if (resizing) {
  9982. var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing);
  9983. offset = [ xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1] ];
  9984. origin[0] = xExtent[ex];
  9985. origin[1] = yExtent[ey];
  9986. } else if (d3.event.altKey) center = origin.slice();
  9987. g.style("pointer-events", "none").selectAll(".resize").style("display", null);
  9988. d3.select("body").style("cursor", eventTarget.style("cursor"));
  9989. event_({
  9990. type: "brushstart"
  9991. });
  9992. brushmove();
  9993. function keydown() {
  9994. if (d3.event.keyCode == 32) {
  9995. if (!dragging) {
  9996. center = null;
  9997. origin[0] -= xExtent[1];
  9998. origin[1] -= yExtent[1];
  9999. dragging = 2;
  10000. }
  10001. d3_eventPreventDefault();
  10002. }
  10003. }
  10004. function keyup() {
  10005. if (d3.event.keyCode == 32 && dragging == 2) {
  10006. origin[0] += xExtent[1];
  10007. origin[1] += yExtent[1];
  10008. dragging = 0;
  10009. d3_eventPreventDefault();
  10010. }
  10011. }
  10012. function brushmove() {
  10013. var point = d3.mouse(target), moved = false;
  10014. if (offset) {
  10015. point[0] += offset[0];
  10016. point[1] += offset[1];
  10017. }
  10018. if (!dragging) {
  10019. if (d3.event.altKey) {
  10020. if (!center) center = [ (xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2 ];
  10021. origin[0] = xExtent[+(point[0] < center[0])];
  10022. origin[1] = yExtent[+(point[1] < center[1])];
  10023. } else center = null;
  10024. }
  10025. if (resizingX && move1(point, x, 0)) {
  10026. redrawX(g);
  10027. moved = true;
  10028. }
  10029. if (resizingY && move1(point, y, 1)) {
  10030. redrawY(g);
  10031. moved = true;
  10032. }
  10033. if (moved) {
  10034. redraw(g);
  10035. event_({
  10036. type: "brush",
  10037. mode: dragging ? "move" : "resize"
  10038. });
  10039. }
  10040. }
  10041. function move1(point, scale, i) {
  10042. var range = d3_scaleRange(scale), r0 = range[0], r1 = range[1], position = origin[i], extent = i ? yExtent : xExtent, size = extent[1] - extent[0], min, max;
  10043. if (dragging) {
  10044. r0 -= position;
  10045. r1 -= size + position;
  10046. }
  10047. min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i];
  10048. if (dragging) {
  10049. max = (min += position) + size;
  10050. } else {
  10051. if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min));
  10052. if (position < min) {
  10053. max = min;
  10054. min = position;
  10055. } else {
  10056. max = position;
  10057. }
  10058. }
  10059. if (extent[0] != min || extent[1] != max) {
  10060. if (i) yExtentDomain = null; else xExtentDomain = null;
  10061. extent[0] = min;
  10062. extent[1] = max;
  10063. return true;
  10064. }
  10065. }
  10066. function brushend() {
  10067. brushmove();
  10068. g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null);
  10069. d3.select("body").style("cursor", null);
  10070. w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null);
  10071. dragRestore();
  10072. event_({
  10073. type: "brushend"
  10074. });
  10075. }
  10076. }
  10077. brush.x = function(z) {
  10078. if (!arguments.length) return x;
  10079. x = z;
  10080. resizes = d3_svg_brushResizes[!x << 1 | !y];
  10081. return brush;
  10082. };
  10083. brush.y = function(z) {
  10084. if (!arguments.length) return y;
  10085. y = z;
  10086. resizes = d3_svg_brushResizes[!x << 1 | !y];
  10087. return brush;
  10088. };
  10089. brush.clamp = function(z) {
  10090. if (!arguments.length) return x && y ? [ xClamp, yClamp ] : x ? xClamp : y ? yClamp : null;
  10091. if (x && y) xClamp = !!z[0], yClamp = !!z[1]; else if (x) xClamp = !!z; else if (y) yClamp = !!z;
  10092. return brush;
  10093. };
  10094. brush.extent = function(z) {
  10095. var x0, x1, y0, y1, t;
  10096. if (!arguments.length) {
  10097. if (x) {
  10098. if (xExtentDomain) {
  10099. x0 = xExtentDomain[0], x1 = xExtentDomain[1];
  10100. } else {
  10101. x0 = xExtent[0], x1 = xExtent[1];
  10102. if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1);
  10103. if (x1 < x0) t = x0, x0 = x1, x1 = t;
  10104. }
  10105. }
  10106. if (y) {
  10107. if (yExtentDomain) {
  10108. y0 = yExtentDomain[0], y1 = yExtentDomain[1];
  10109. } else {
  10110. y0 = yExtent[0], y1 = yExtent[1];
  10111. if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1);
  10112. if (y1 < y0) t = y0, y0 = y1, y1 = t;
  10113. }
  10114. }
  10115. return x && y ? [ [ x0, y0 ], [ x1, y1 ] ] : x ? [ x0, x1 ] : y && [ y0, y1 ];
  10116. }
  10117. if (x) {
  10118. x0 = z[0], x1 = z[1];
  10119. if (y) x0 = x0[0], x1 = x1[0];
  10120. xExtentDomain = [ x0, x1 ];
  10121. if (x.invert) x0 = x(x0), x1 = x(x1);
  10122. if (x1 < x0) t = x0, x0 = x1, x1 = t;
  10123. if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [ x0, x1 ];
  10124. }
  10125. if (y) {
  10126. y0 = z[0], y1 = z[1];
  10127. if (x) y0 = y0[1], y1 = y1[1];
  10128. yExtentDomain = [ y0, y1 ];
  10129. if (y.invert) y0 = y(y0), y1 = y(y1);
  10130. if (y1 < y0) t = y0, y0 = y1, y1 = t;
  10131. if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [ y0, y1 ];
  10132. }
  10133. return brush;
  10134. };
  10135. brush.clear = function() {
  10136. if (!brush.empty()) {
  10137. xExtent = [ 0, 0 ], yExtent = [ 0, 0 ];
  10138. xExtentDomain = yExtentDomain = null;
  10139. }
  10140. return brush;
  10141. };
  10142. brush.empty = function() {
  10143. return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1];
  10144. };
  10145. return d3.rebind(brush, event, "on");
  10146. };
  10147. var d3_svg_brushCursor = {
  10148. n: "ns-resize",
  10149. e: "ew-resize",
  10150. s: "ns-resize",
  10151. w: "ew-resize",
  10152. nw: "nwse-resize",
  10153. ne: "nesw-resize",
  10154. se: "nwse-resize",
  10155. sw: "nesw-resize"
  10156. };
  10157. var d3_svg_brushResizes = [ [ "n", "e", "s", "w", "nw", "ne", "se", "sw" ], [ "e", "w" ], [ "n", "s" ], [] ];
  10158. var d3_time_format = d3_time.format = d3_locale_enUS.timeFormat;
  10159. var d3_time_formatUtc = d3_time_format.utc;
  10160. var d3_time_formatIso = d3_time_formatUtc("%Y-%m-%dT%H:%M:%S.%LZ");
  10161. d3_time_format.iso = Date.prototype.toISOString && +new Date("2000-01-01T00:00:00.000Z") ? d3_time_formatIsoNative : d3_time_formatIso;
  10162. function d3_time_formatIsoNative(date) {
  10163. return date.toISOString();
  10164. }
  10165. d3_time_formatIsoNative.parse = function(string) {
  10166. var date = new Date(string);
  10167. return isNaN(date) ? null : date;
  10168. };
  10169. d3_time_formatIsoNative.toString = d3_time_formatIso.toString;
  10170. d3_time.second = d3_time_interval(function(date) {
  10171. return new d3_date(Math.floor(date / 1e3) * 1e3);
  10172. }, function(date, offset) {
  10173. date.setTime(date.getTime() + Math.floor(offset) * 1e3);
  10174. }, function(date) {
  10175. return date.getSeconds();
  10176. });
  10177. d3_time.seconds = d3_time.second.range;
  10178. d3_time.seconds.utc = d3_time.second.utc.range;
  10179. d3_time.minute = d3_time_interval(function(date) {
  10180. return new d3_date(Math.floor(date / 6e4) * 6e4);
  10181. }, function(date, offset) {
  10182. date.setTime(date.getTime() + Math.floor(offset) * 6e4);
  10183. }, function(date) {
  10184. return date.getMinutes();
  10185. });
  10186. d3_time.minutes = d3_time.minute.range;
  10187. d3_time.minutes.utc = d3_time.minute.utc.range;
  10188. d3_time.hour = d3_time_interval(function(date) {
  10189. var timezone = date.getTimezoneOffset() / 60;
  10190. return new d3_date((Math.floor(date / 36e5 - timezone) + timezone) * 36e5);
  10191. }, function(date, offset) {
  10192. date.setTime(date.getTime() + Math.floor(offset) * 36e5);
  10193. }, function(date) {
  10194. return date.getHours();
  10195. });
  10196. d3_time.hours = d3_time.hour.range;
  10197. d3_time.hours.utc = d3_time.hour.utc.range;
  10198. d3_time.month = d3_time_interval(function(date) {
  10199. date = d3_time.day(date);
  10200. date.setDate(1);
  10201. return date;
  10202. }, function(date, offset) {
  10203. date.setMonth(date.getMonth() + offset);
  10204. }, function(date) {
  10205. return date.getMonth();
  10206. });
  10207. d3_time.months = d3_time.month.range;
  10208. d3_time.months.utc = d3_time.month.utc.range;
  10209. function d3_time_scale(linear, methods, format) {
  10210. function scale(x) {
  10211. return linear(x);
  10212. }
  10213. scale.invert = function(x) {
  10214. return d3_time_scaleDate(linear.invert(x));
  10215. };
  10216. scale.domain = function(x) {
  10217. if (!arguments.length) return linear.domain().map(d3_time_scaleDate);
  10218. linear.domain(x);
  10219. return scale;
  10220. };
  10221. function tickMethod(extent, count) {
  10222. var span = extent[1] - extent[0], target = span / count, i = d3.bisect(d3_time_scaleSteps, target);
  10223. return i == d3_time_scaleSteps.length ? [ methods.year, d3_scale_linearTickRange(extent.map(function(d) {
  10224. return d / 31536e6;
  10225. }), count)[2] ] : !i ? [ d3_time_scaleMilliseconds, d3_scale_linearTickRange(extent, count)[2] ] : methods[target / d3_time_scaleSteps[i - 1] < d3_time_scaleSteps[i] / target ? i - 1 : i];
  10226. }
  10227. scale.nice = function(interval, skip) {
  10228. var domain = scale.domain(), extent = d3_scaleExtent(domain), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" && tickMethod(extent, interval);
  10229. if (method) interval = method[0], skip = method[1];
  10230. function skipped(date) {
  10231. return !isNaN(date) && !interval.range(date, d3_time_scaleDate(+date + 1), skip).length;
  10232. }
  10233. return scale.domain(d3_scale_nice(domain, skip > 1 ? {
  10234. floor: function(date) {
  10235. while (skipped(date = interval.floor(date))) date = d3_time_scaleDate(date - 1);
  10236. return date;
  10237. },
  10238. ceil: function(date) {
  10239. while (skipped(date = interval.ceil(date))) date = d3_time_scaleDate(+date + 1);
  10240. return date;
  10241. }
  10242. } : interval));
  10243. };
  10244. scale.ticks = function(interval, skip) {
  10245. var extent = d3_scaleExtent(scale.domain()), method = interval == null ? tickMethod(extent, 10) : typeof interval === "number" ? tickMethod(extent, interval) : !interval.range && [ {
  10246. range: interval
  10247. }, skip ];
  10248. if (method) interval = method[0], skip = method[1];
  10249. return interval.range(extent[0], d3_time_scaleDate(+extent[1] + 1), skip < 1 ? 1 : skip);
  10250. };
  10251. scale.tickFormat = function() {
  10252. return format;
  10253. };
  10254. scale.copy = function() {
  10255. return d3_time_scale(linear.copy(), methods, format);
  10256. };
  10257. return d3_scale_linearRebind(scale, linear);
  10258. }
  10259. function d3_time_scaleDate(t) {
  10260. return new Date(t);
  10261. }
  10262. var d3_time_scaleSteps = [ 1e3, 5e3, 15e3, 3e4, 6e4, 3e5, 9e5, 18e5, 36e5, 108e5, 216e5, 432e5, 864e5, 1728e5, 6048e5, 2592e6, 7776e6, 31536e6 ];
  10263. var d3_time_scaleLocalMethods = [ [ d3_time.second, 1 ], [ d3_time.second, 5 ], [ d3_time.second, 15 ], [ d3_time.second, 30 ], [ d3_time.minute, 1 ], [ d3_time.minute, 5 ], [ d3_time.minute, 15 ], [ d3_time.minute, 30 ], [ d3_time.hour, 1 ], [ d3_time.hour, 3 ], [ d3_time.hour, 6 ], [ d3_time.hour, 12 ], [ d3_time.day, 1 ], [ d3_time.day, 2 ], [ d3_time.week, 1 ], [ d3_time.month, 1 ], [ d3_time.month, 3 ], [ d3_time.year, 1 ] ];
  10264. var d3_time_scaleLocalFormat = d3_time_format.multi([ [ ".%L", function(d) {
  10265. return d.getMilliseconds();
  10266. } ], [ ":%S", function(d) {
  10267. return d.getSeconds();
  10268. } ], [ "%I:%M", function(d) {
  10269. return d.getMinutes();
  10270. } ], [ "%I %p", function(d) {
  10271. return d.getHours();
  10272. } ], [ "%a %d", function(d) {
  10273. return d.getDay() && d.getDate() != 1;
  10274. } ], [ "%b %d", function(d) {
  10275. return d.getDate() != 1;
  10276. } ], [ "%B", function(d) {
  10277. return d.getMonth();
  10278. } ], [ "%Y", d3_true ] ]);
  10279. var d3_time_scaleMilliseconds = {
  10280. range: function(start, stop, step) {
  10281. return d3.range(Math.ceil(start / step) * step, +stop, step).map(d3_time_scaleDate);
  10282. },
  10283. floor: d3_identity,
  10284. ceil: d3_identity
  10285. };
  10286. d3_time_scaleLocalMethods.year = d3_time.year;
  10287. d3_time.scale = function() {
  10288. return d3_time_scale(d3.scale.linear(), d3_time_scaleLocalMethods, d3_time_scaleLocalFormat);
  10289. };
  10290. var d3_time_scaleUtcMethods = d3_time_scaleLocalMethods.map(function(m) {
  10291. return [ m[0].utc, m[1] ];
  10292. });
  10293. var d3_time_scaleUtcFormat = d3_time_formatUtc.multi([ [ ".%L", function(d) {
  10294. return d.getUTCMilliseconds();
  10295. } ], [ ":%S", function(d) {
  10296. return d.getUTCSeconds();
  10297. } ], [ "%I:%M", function(d) {
  10298. return d.getUTCMinutes();
  10299. } ], [ "%I %p", function(d) {
  10300. return d.getUTCHours();
  10301. } ], [ "%a %d", function(d) {
  10302. return d.getUTCDay() && d.getUTCDate() != 1;
  10303. } ], [ "%b %d", function(d) {
  10304. return d.getUTCDate() != 1;
  10305. } ], [ "%B", function(d) {
  10306. return d.getUTCMonth();
  10307. } ], [ "%Y", d3_true ] ]);
  10308. d3_time_scaleUtcMethods.year = d3_time.year.utc;
  10309. d3_time.scale.utc = function() {
  10310. return d3_time_scale(d3.scale.linear(), d3_time_scaleUtcMethods, d3_time_scaleUtcFormat);
  10311. };
  10312. d3.text = d3_xhrType(function(request) {
  10313. return request.responseText;
  10314. });
  10315. d3.json = function(url, callback) {
  10316. return d3_xhr(url, "application/json", d3_json, callback);
  10317. };
  10318. function d3_json(request) {
  10319. return JSON.parse(request.responseText);
  10320. }
  10321. d3.html = function(url, callback) {
  10322. return d3_xhr(url, "text/html", d3_html, callback);
  10323. };
  10324. function d3_html(request) {
  10325. var range = d3_document.createRange();
  10326. range.selectNode(d3_document.body);
  10327. return range.createContextualFragment(request.responseText);
  10328. }
  10329. d3.xml = d3_xhrType(function(request) {
  10330. return request.responseXML;
  10331. });
  10332. if (typeof define === "function" && define.amd) this.d3 = d3, define(d3); else if (typeof module === "object" && module.exports) module.exports = d3; else this.d3 = d3;
  10333. }();
  10334. },{}],17:[function(_dereq_,module,exports){
  10335. (function (process,global){
  10336. /*!
  10337. * @overview es6-promise - a tiny implementation of Promises/A+.
  10338. * @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
  10339. * @license Licensed under MIT license
  10340. * See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
  10341. * @version 3.3.1
  10342. */
  10343. (function (global, factory) {
  10344. typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
  10345. typeof define === 'function' && define.amd ? define(factory) :
  10346. (global.ES6Promise = factory());
  10347. }(this, (function () { 'use strict';
  10348. function objectOrFunction(x) {
  10349. return typeof x === 'function' || typeof x === 'object' && x !== null;
  10350. }
  10351. function isFunction(x) {
  10352. return typeof x === 'function';
  10353. }
  10354. var _isArray = undefined;
  10355. if (!Array.isArray) {
  10356. _isArray = function (x) {
  10357. return Object.prototype.toString.call(x) === '[object Array]';
  10358. };
  10359. } else {
  10360. _isArray = Array.isArray;
  10361. }
  10362. var isArray = _isArray;
  10363. var len = 0;
  10364. var vertxNext = undefined;
  10365. var customSchedulerFn = undefined;
  10366. var asap = function asap(callback, arg) {
  10367. queue[len] = callback;
  10368. queue[len + 1] = arg;
  10369. len += 2;
  10370. if (len === 2) {
  10371. // If len is 2, that means that we need to schedule an async flush.
  10372. // If additional callbacks are queued before the queue is flushed, they
  10373. // will be processed by this flush that we are scheduling.
  10374. if (customSchedulerFn) {
  10375. customSchedulerFn(flush);
  10376. } else {
  10377. scheduleFlush();
  10378. }
  10379. }
  10380. };
  10381. function setScheduler(scheduleFn) {
  10382. customSchedulerFn = scheduleFn;
  10383. }
  10384. function setAsap(asapFn) {
  10385. asap = asapFn;
  10386. }
  10387. var browserWindow = typeof window !== 'undefined' ? window : undefined;
  10388. var browserGlobal = browserWindow || {};
  10389. var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
  10390. var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && ({}).toString.call(process) === '[object process]';
  10391. // test for web worker but not in IE10
  10392. var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
  10393. // node
  10394. function useNextTick() {
  10395. // node version 0.10.x displays a deprecation warning when nextTick is used recursively
  10396. // see https://github.com/cujojs/when/issues/410 for details
  10397. return function () {
  10398. return process.nextTick(flush);
  10399. };
  10400. }
  10401. // vertx
  10402. function useVertxTimer() {
  10403. return function () {
  10404. vertxNext(flush);
  10405. };
  10406. }
  10407. function useMutationObserver() {
  10408. var iterations = 0;
  10409. var observer = new BrowserMutationObserver(flush);
  10410. var node = document.createTextNode('');
  10411. observer.observe(node, { characterData: true });
  10412. return function () {
  10413. node.data = iterations = ++iterations % 2;
  10414. };
  10415. }
  10416. // web worker
  10417. function useMessageChannel() {
  10418. var channel = new MessageChannel();
  10419. channel.port1.onmessage = flush;
  10420. return function () {
  10421. return channel.port2.postMessage(0);
  10422. };
  10423. }
  10424. function useSetTimeout() {
  10425. // Store setTimeout reference so es6-promise will be unaffected by
  10426. // other code modifying setTimeout (like sinon.useFakeTimers())
  10427. var globalSetTimeout = setTimeout;
  10428. return function () {
  10429. return globalSetTimeout(flush, 1);
  10430. };
  10431. }
  10432. var queue = new Array(1000);
  10433. function flush() {
  10434. for (var i = 0; i < len; i += 2) {
  10435. var callback = queue[i];
  10436. var arg = queue[i + 1];
  10437. callback(arg);
  10438. queue[i] = undefined;
  10439. queue[i + 1] = undefined;
  10440. }
  10441. len = 0;
  10442. }
  10443. function attemptVertx() {
  10444. try {
  10445. var r = _dereq_;
  10446. var vertx = r('vertx');
  10447. vertxNext = vertx.runOnLoop || vertx.runOnContext;
  10448. return useVertxTimer();
  10449. } catch (e) {
  10450. return useSetTimeout();
  10451. }
  10452. }
  10453. var scheduleFlush = undefined;
  10454. // Decide what async method to use to triggering processing of queued callbacks:
  10455. if (isNode) {
  10456. scheduleFlush = useNextTick();
  10457. } else if (BrowserMutationObserver) {
  10458. scheduleFlush = useMutationObserver();
  10459. } else if (isWorker) {
  10460. scheduleFlush = useMessageChannel();
  10461. } else if (browserWindow === undefined && typeof _dereq_ === 'function') {
  10462. scheduleFlush = attemptVertx();
  10463. } else {
  10464. scheduleFlush = useSetTimeout();
  10465. }
  10466. function then(onFulfillment, onRejection) {
  10467. var _arguments = arguments;
  10468. var parent = this;
  10469. var child = new this.constructor(noop);
  10470. if (child[PROMISE_ID] === undefined) {
  10471. makePromise(child);
  10472. }
  10473. var _state = parent._state;
  10474. if (_state) {
  10475. (function () {
  10476. var callback = _arguments[_state - 1];
  10477. asap(function () {
  10478. return invokeCallback(_state, child, callback, parent._result);
  10479. });
  10480. })();
  10481. } else {
  10482. subscribe(parent, child, onFulfillment, onRejection);
  10483. }
  10484. return child;
  10485. }
  10486. /**
  10487. `Promise.resolve` returns a promise that will become resolved with the
  10488. passed `value`. It is shorthand for the following:
  10489. ```javascript
  10490. let promise = new Promise(function(resolve, reject){
  10491. resolve(1);
  10492. });
  10493. promise.then(function(value){
  10494. // value === 1
  10495. });
  10496. ```
  10497. Instead of writing the above, your code now simply becomes the following:
  10498. ```javascript
  10499. let promise = Promise.resolve(1);
  10500. promise.then(function(value){
  10501. // value === 1
  10502. });
  10503. ```
  10504. @method resolve
  10505. @static
  10506. @param {Any} value value that the returned promise will be resolved with
  10507. Useful for tooling.
  10508. @return {Promise} a promise that will become fulfilled with the given
  10509. `value`
  10510. */
  10511. function resolve(object) {
  10512. /*jshint validthis:true */
  10513. var Constructor = this;
  10514. if (object && typeof object === 'object' && object.constructor === Constructor) {
  10515. return object;
  10516. }
  10517. var promise = new Constructor(noop);
  10518. _resolve(promise, object);
  10519. return promise;
  10520. }
  10521. var PROMISE_ID = Math.random().toString(36).substring(16);
  10522. function noop() {}
  10523. var PENDING = void 0;
  10524. var FULFILLED = 1;
  10525. var REJECTED = 2;
  10526. var GET_THEN_ERROR = new ErrorObject();
  10527. function selfFulfillment() {
  10528. return new TypeError("You cannot resolve a promise with itself");
  10529. }
  10530. function cannotReturnOwn() {
  10531. return new TypeError('A promises callback cannot return that same promise.');
  10532. }
  10533. function getThen(promise) {
  10534. try {
  10535. return promise.then;
  10536. } catch (error) {
  10537. GET_THEN_ERROR.error = error;
  10538. return GET_THEN_ERROR;
  10539. }
  10540. }
  10541. function tryThen(then, value, fulfillmentHandler, rejectionHandler) {
  10542. try {
  10543. then.call(value, fulfillmentHandler, rejectionHandler);
  10544. } catch (e) {
  10545. return e;
  10546. }
  10547. }
  10548. function handleForeignThenable(promise, thenable, then) {
  10549. asap(function (promise) {
  10550. var sealed = false;
  10551. var error = tryThen(then, thenable, function (value) {
  10552. if (sealed) {
  10553. return;
  10554. }
  10555. sealed = true;
  10556. if (thenable !== value) {
  10557. _resolve(promise, value);
  10558. } else {
  10559. fulfill(promise, value);
  10560. }
  10561. }, function (reason) {
  10562. if (sealed) {
  10563. return;
  10564. }
  10565. sealed = true;
  10566. _reject(promise, reason);
  10567. }, 'Settle: ' + (promise._label || ' unknown promise'));
  10568. if (!sealed && error) {
  10569. sealed = true;
  10570. _reject(promise, error);
  10571. }
  10572. }, promise);
  10573. }
  10574. function handleOwnThenable(promise, thenable) {
  10575. if (thenable._state === FULFILLED) {
  10576. fulfill(promise, thenable._result);
  10577. } else if (thenable._state === REJECTED) {
  10578. _reject(promise, thenable._result);
  10579. } else {
  10580. subscribe(thenable, undefined, function (value) {
  10581. return _resolve(promise, value);
  10582. }, function (reason) {
  10583. return _reject(promise, reason);
  10584. });
  10585. }
  10586. }
  10587. function handleMaybeThenable(promise, maybeThenable, then$$) {
  10588. if (maybeThenable.constructor === promise.constructor && then$$ === then && maybeThenable.constructor.resolve === resolve) {
  10589. handleOwnThenable(promise, maybeThenable);
  10590. } else {
  10591. if (then$$ === GET_THEN_ERROR) {
  10592. _reject(promise, GET_THEN_ERROR.error);
  10593. } else if (then$$ === undefined) {
  10594. fulfill(promise, maybeThenable);
  10595. } else if (isFunction(then$$)) {
  10596. handleForeignThenable(promise, maybeThenable, then$$);
  10597. } else {
  10598. fulfill(promise, maybeThenable);
  10599. }
  10600. }
  10601. }
  10602. function _resolve(promise, value) {
  10603. if (promise === value) {
  10604. _reject(promise, selfFulfillment());
  10605. } else if (objectOrFunction(value)) {
  10606. handleMaybeThenable(promise, value, getThen(value));
  10607. } else {
  10608. fulfill(promise, value);
  10609. }
  10610. }
  10611. function publishRejection(promise) {
  10612. if (promise._onerror) {
  10613. promise._onerror(promise._result);
  10614. }
  10615. publish(promise);
  10616. }
  10617. function fulfill(promise, value) {
  10618. if (promise._state !== PENDING) {
  10619. return;
  10620. }
  10621. promise._result = value;
  10622. promise._state = FULFILLED;
  10623. if (promise._subscribers.length !== 0) {
  10624. asap(publish, promise);
  10625. }
  10626. }
  10627. function _reject(promise, reason) {
  10628. if (promise._state !== PENDING) {
  10629. return;
  10630. }
  10631. promise._state = REJECTED;
  10632. promise._result = reason;
  10633. asap(publishRejection, promise);
  10634. }
  10635. function subscribe(parent, child, onFulfillment, onRejection) {
  10636. var _subscribers = parent._subscribers;
  10637. var length = _subscribers.length;
  10638. parent._onerror = null;
  10639. _subscribers[length] = child;
  10640. _subscribers[length + FULFILLED] = onFulfillment;
  10641. _subscribers[length + REJECTED] = onRejection;
  10642. if (length === 0 && parent._state) {
  10643. asap(publish, parent);
  10644. }
  10645. }
  10646. function publish(promise) {
  10647. var subscribers = promise._subscribers;
  10648. var settled = promise._state;
  10649. if (subscribers.length === 0) {
  10650. return;
  10651. }
  10652. var child = undefined,
  10653. callback = undefined,
  10654. detail = promise._result;
  10655. for (var i = 0; i < subscribers.length; i += 3) {
  10656. child = subscribers[i];
  10657. callback = subscribers[i + settled];
  10658. if (child) {
  10659. invokeCallback(settled, child, callback, detail);
  10660. } else {
  10661. callback(detail);
  10662. }
  10663. }
  10664. promise._subscribers.length = 0;
  10665. }
  10666. function ErrorObject() {
  10667. this.error = null;
  10668. }
  10669. var TRY_CATCH_ERROR = new ErrorObject();
  10670. function tryCatch(callback, detail) {
  10671. try {
  10672. return callback(detail);
  10673. } catch (e) {
  10674. TRY_CATCH_ERROR.error = e;
  10675. return TRY_CATCH_ERROR;
  10676. }
  10677. }
  10678. function invokeCallback(settled, promise, callback, detail) {
  10679. var hasCallback = isFunction(callback),
  10680. value = undefined,
  10681. error = undefined,
  10682. succeeded = undefined,
  10683. failed = undefined;
  10684. if (hasCallback) {
  10685. value = tryCatch(callback, detail);
  10686. if (value === TRY_CATCH_ERROR) {
  10687. failed = true;
  10688. error = value.error;
  10689. value = null;
  10690. } else {
  10691. succeeded = true;
  10692. }
  10693. if (promise === value) {
  10694. _reject(promise, cannotReturnOwn());
  10695. return;
  10696. }
  10697. } else {
  10698. value = detail;
  10699. succeeded = true;
  10700. }
  10701. if (promise._state !== PENDING) {
  10702. // noop
  10703. } else if (hasCallback && succeeded) {
  10704. _resolve(promise, value);
  10705. } else if (failed) {
  10706. _reject(promise, error);
  10707. } else if (settled === FULFILLED) {
  10708. fulfill(promise, value);
  10709. } else if (settled === REJECTED) {
  10710. _reject(promise, value);
  10711. }
  10712. }
  10713. function initializePromise(promise, resolver) {
  10714. try {
  10715. resolver(function resolvePromise(value) {
  10716. _resolve(promise, value);
  10717. }, function rejectPromise(reason) {
  10718. _reject(promise, reason);
  10719. });
  10720. } catch (e) {
  10721. _reject(promise, e);
  10722. }
  10723. }
  10724. var id = 0;
  10725. function nextId() {
  10726. return id++;
  10727. }
  10728. function makePromise(promise) {
  10729. promise[PROMISE_ID] = id++;
  10730. promise._state = undefined;
  10731. promise._result = undefined;
  10732. promise._subscribers = [];
  10733. }
  10734. function Enumerator(Constructor, input) {
  10735. this._instanceConstructor = Constructor;
  10736. this.promise = new Constructor(noop);
  10737. if (!this.promise[PROMISE_ID]) {
  10738. makePromise(this.promise);
  10739. }
  10740. if (isArray(input)) {
  10741. this._input = input;
  10742. this.length = input.length;
  10743. this._remaining = input.length;
  10744. this._result = new Array(this.length);
  10745. if (this.length === 0) {
  10746. fulfill(this.promise, this._result);
  10747. } else {
  10748. this.length = this.length || 0;
  10749. this._enumerate();
  10750. if (this._remaining === 0) {
  10751. fulfill(this.promise, this._result);
  10752. }
  10753. }
  10754. } else {
  10755. _reject(this.promise, validationError());
  10756. }
  10757. }
  10758. function validationError() {
  10759. return new Error('Array Methods must be provided an Array');
  10760. };
  10761. Enumerator.prototype._enumerate = function () {
  10762. var length = this.length;
  10763. var _input = this._input;
  10764. for (var i = 0; this._state === PENDING && i < length; i++) {
  10765. this._eachEntry(_input[i], i);
  10766. }
  10767. };
  10768. Enumerator.prototype._eachEntry = function (entry, i) {
  10769. var c = this._instanceConstructor;
  10770. var resolve$$ = c.resolve;
  10771. if (resolve$$ === resolve) {
  10772. var _then = getThen(entry);
  10773. if (_then === then && entry._state !== PENDING) {
  10774. this._settledAt(entry._state, i, entry._result);
  10775. } else if (typeof _then !== 'function') {
  10776. this._remaining--;
  10777. this._result[i] = entry;
  10778. } else if (c === Promise) {
  10779. var promise = new c(noop);
  10780. handleMaybeThenable(promise, entry, _then);
  10781. this._willSettleAt(promise, i);
  10782. } else {
  10783. this._willSettleAt(new c(function (resolve$$) {
  10784. return resolve$$(entry);
  10785. }), i);
  10786. }
  10787. } else {
  10788. this._willSettleAt(resolve$$(entry), i);
  10789. }
  10790. };
  10791. Enumerator.prototype._settledAt = function (state, i, value) {
  10792. var promise = this.promise;
  10793. if (promise._state === PENDING) {
  10794. this._remaining--;
  10795. if (state === REJECTED) {
  10796. _reject(promise, value);
  10797. } else {
  10798. this._result[i] = value;
  10799. }
  10800. }
  10801. if (this._remaining === 0) {
  10802. fulfill(promise, this._result);
  10803. }
  10804. };
  10805. Enumerator.prototype._willSettleAt = function (promise, i) {
  10806. var enumerator = this;
  10807. subscribe(promise, undefined, function (value) {
  10808. return enumerator._settledAt(FULFILLED, i, value);
  10809. }, function (reason) {
  10810. return enumerator._settledAt(REJECTED, i, reason);
  10811. });
  10812. };
  10813. /**
  10814. `Promise.all` accepts an array of promises, and returns a new promise which
  10815. is fulfilled with an array of fulfillment values for the passed promises, or
  10816. rejected with the reason of the first passed promise to be rejected. It casts all
  10817. elements of the passed iterable to promises as it runs this algorithm.
  10818. Example:
  10819. ```javascript
  10820. let promise1 = resolve(1);
  10821. let promise2 = resolve(2);
  10822. let promise3 = resolve(3);
  10823. let promises = [ promise1, promise2, promise3 ];
  10824. Promise.all(promises).then(function(array){
  10825. // The array here would be [ 1, 2, 3 ];
  10826. });
  10827. ```
  10828. If any of the `promises` given to `all` are rejected, the first promise
  10829. that is rejected will be given as an argument to the returned promises's
  10830. rejection handler. For example:
  10831. Example:
  10832. ```javascript
  10833. let promise1 = resolve(1);
  10834. let promise2 = reject(new Error("2"));
  10835. let promise3 = reject(new Error("3"));
  10836. let promises = [ promise1, promise2, promise3 ];
  10837. Promise.all(promises).then(function(array){
  10838. // Code here never runs because there are rejected promises!
  10839. }, function(error) {
  10840. // error.message === "2"
  10841. });
  10842. ```
  10843. @method all
  10844. @static
  10845. @param {Array} entries array of promises
  10846. @param {String} label optional string for labeling the promise.
  10847. Useful for tooling.
  10848. @return {Promise} promise that is fulfilled when all `promises` have been
  10849. fulfilled, or rejected if any of them become rejected.
  10850. @static
  10851. */
  10852. function all(entries) {
  10853. return new Enumerator(this, entries).promise;
  10854. }
  10855. /**
  10856. `Promise.race` returns a new promise which is settled in the same way as the
  10857. first passed promise to settle.
  10858. Example:
  10859. ```javascript
  10860. let promise1 = new Promise(function(resolve, reject){
  10861. setTimeout(function(){
  10862. resolve('promise 1');
  10863. }, 200);
  10864. });
  10865. let promise2 = new Promise(function(resolve, reject){
  10866. setTimeout(function(){
  10867. resolve('promise 2');
  10868. }, 100);
  10869. });
  10870. Promise.race([promise1, promise2]).then(function(result){
  10871. // result === 'promise 2' because it was resolved before promise1
  10872. // was resolved.
  10873. });
  10874. ```
  10875. `Promise.race` is deterministic in that only the state of the first
  10876. settled promise matters. For example, even if other promises given to the
  10877. `promises` array argument are resolved, but the first settled promise has
  10878. become rejected before the other promises became fulfilled, the returned
  10879. promise will become rejected:
  10880. ```javascript
  10881. let promise1 = new Promise(function(resolve, reject){
  10882. setTimeout(function(){
  10883. resolve('promise 1');
  10884. }, 200);
  10885. });
  10886. let promise2 = new Promise(function(resolve, reject){
  10887. setTimeout(function(){
  10888. reject(new Error('promise 2'));
  10889. }, 100);
  10890. });
  10891. Promise.race([promise1, promise2]).then(function(result){
  10892. // Code here never runs
  10893. }, function(reason){
  10894. // reason.message === 'promise 2' because promise 2 became rejected before
  10895. // promise 1 became fulfilled
  10896. });
  10897. ```
  10898. An example real-world use case is implementing timeouts:
  10899. ```javascript
  10900. Promise.race([ajax('foo.json'), timeout(5000)])
  10901. ```
  10902. @method race
  10903. @static
  10904. @param {Array} promises array of promises to observe
  10905. Useful for tooling.
  10906. @return {Promise} a promise which settles in the same way as the first passed
  10907. promise to settle.
  10908. */
  10909. function race(entries) {
  10910. /*jshint validthis:true */
  10911. var Constructor = this;
  10912. if (!isArray(entries)) {
  10913. return new Constructor(function (_, reject) {
  10914. return reject(new TypeError('You must pass an array to race.'));
  10915. });
  10916. } else {
  10917. return new Constructor(function (resolve, reject) {
  10918. var length = entries.length;
  10919. for (var i = 0; i < length; i++) {
  10920. Constructor.resolve(entries[i]).then(resolve, reject);
  10921. }
  10922. });
  10923. }
  10924. }
  10925. /**
  10926. `Promise.reject` returns a promise rejected with the passed `reason`.
  10927. It is shorthand for the following:
  10928. ```javascript
  10929. let promise = new Promise(function(resolve, reject){
  10930. reject(new Error('WHOOPS'));
  10931. });
  10932. promise.then(function(value){
  10933. // Code here doesn't run because the promise is rejected!
  10934. }, function(reason){
  10935. // reason.message === 'WHOOPS'
  10936. });
  10937. ```
  10938. Instead of writing the above, your code now simply becomes the following:
  10939. ```javascript
  10940. let promise = Promise.reject(new Error('WHOOPS'));
  10941. promise.then(function(value){
  10942. // Code here doesn't run because the promise is rejected!
  10943. }, function(reason){
  10944. // reason.message === 'WHOOPS'
  10945. });
  10946. ```
  10947. @method reject
  10948. @static
  10949. @param {Any} reason value that the returned promise will be rejected with.
  10950. Useful for tooling.
  10951. @return {Promise} a promise rejected with the given `reason`.
  10952. */
  10953. function reject(reason) {
  10954. /*jshint validthis:true */
  10955. var Constructor = this;
  10956. var promise = new Constructor(noop);
  10957. _reject(promise, reason);
  10958. return promise;
  10959. }
  10960. function needsResolver() {
  10961. throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
  10962. }
  10963. function needsNew() {
  10964. throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
  10965. }
  10966. /**
  10967. Promise objects represent the eventual result of an asynchronous operation. The
  10968. primary way of interacting with a promise is through its `then` method, which
  10969. registers callbacks to receive either a promise's eventual value or the reason
  10970. why the promise cannot be fulfilled.
  10971. Terminology
  10972. -----------
  10973. - `promise` is an object or function with a `then` method whose behavior conforms to this specification.
  10974. - `thenable` is an object or function that defines a `then` method.
  10975. - `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
  10976. - `exception` is a value that is thrown using the throw statement.
  10977. - `reason` is a value that indicates why a promise was rejected.
  10978. - `settled` the final resting state of a promise, fulfilled or rejected.
  10979. A promise can be in one of three states: pending, fulfilled, or rejected.
  10980. Promises that are fulfilled have a fulfillment value and are in the fulfilled
  10981. state. Promises that are rejected have a rejection reason and are in the
  10982. rejected state. A fulfillment value is never a thenable.
  10983. Promises can also be said to *resolve* a value. If this value is also a
  10984. promise, then the original promise's settled state will match the value's
  10985. settled state. So a promise that *resolves* a promise that rejects will
  10986. itself reject, and a promise that *resolves* a promise that fulfills will
  10987. itself fulfill.
  10988. Basic Usage:
  10989. ------------
  10990. ```js
  10991. let promise = new Promise(function(resolve, reject) {
  10992. // on success
  10993. resolve(value);
  10994. // on failure
  10995. reject(reason);
  10996. });
  10997. promise.then(function(value) {
  10998. // on fulfillment
  10999. }, function(reason) {
  11000. // on rejection
  11001. });
  11002. ```
  11003. Advanced Usage:
  11004. ---------------
  11005. Promises shine when abstracting away asynchronous interactions such as
  11006. `XMLHttpRequest`s.
  11007. ```js
  11008. function getJSON(url) {
  11009. return new Promise(function(resolve, reject){
  11010. let xhr = new XMLHttpRequest();
  11011. xhr.open('GET', url);
  11012. xhr.onreadystatechange = handler;
  11013. xhr.responseType = 'json';
  11014. xhr.setRequestHeader('Accept', 'application/json');
  11015. xhr.send();
  11016. function handler() {
  11017. if (this.readyState === this.DONE) {
  11018. if (this.status === 200) {
  11019. resolve(this.response);
  11020. } else {
  11021. reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
  11022. }
  11023. }
  11024. };
  11025. });
  11026. }
  11027. getJSON('/posts.json').then(function(json) {
  11028. // on fulfillment
  11029. }, function(reason) {
  11030. // on rejection
  11031. });
  11032. ```
  11033. Unlike callbacks, promises are great composable primitives.
  11034. ```js
  11035. Promise.all([
  11036. getJSON('/posts'),
  11037. getJSON('/comments')
  11038. ]).then(function(values){
  11039. values[0] // => postsJSON
  11040. values[1] // => commentsJSON
  11041. return values;
  11042. });
  11043. ```
  11044. @class Promise
  11045. @param {function} resolver
  11046. Useful for tooling.
  11047. @constructor
  11048. */
  11049. function Promise(resolver) {
  11050. this[PROMISE_ID] = nextId();
  11051. this._result = this._state = undefined;
  11052. this._subscribers = [];
  11053. if (noop !== resolver) {
  11054. typeof resolver !== 'function' && needsResolver();
  11055. this instanceof Promise ? initializePromise(this, resolver) : needsNew();
  11056. }
  11057. }
  11058. Promise.all = all;
  11059. Promise.race = race;
  11060. Promise.resolve = resolve;
  11061. Promise.reject = reject;
  11062. Promise._setScheduler = setScheduler;
  11063. Promise._setAsap = setAsap;
  11064. Promise._asap = asap;
  11065. Promise.prototype = {
  11066. constructor: Promise,
  11067. /**
  11068. The primary way of interacting with a promise is through its `then` method,
  11069. which registers callbacks to receive either a promise's eventual value or the
  11070. reason why the promise cannot be fulfilled.
  11071. ```js
  11072. findUser().then(function(user){
  11073. // user is available
  11074. }, function(reason){
  11075. // user is unavailable, and you are given the reason why
  11076. });
  11077. ```
  11078. Chaining
  11079. --------
  11080. The return value of `then` is itself a promise. This second, 'downstream'
  11081. promise is resolved with the return value of the first promise's fulfillment
  11082. or rejection handler, or rejected if the handler throws an exception.
  11083. ```js
  11084. findUser().then(function (user) {
  11085. return user.name;
  11086. }, function (reason) {
  11087. return 'default name';
  11088. }).then(function (userName) {
  11089. // If `findUser` fulfilled, `userName` will be the user's name, otherwise it
  11090. // will be `'default name'`
  11091. });
  11092. findUser().then(function (user) {
  11093. throw new Error('Found user, but still unhappy');
  11094. }, function (reason) {
  11095. throw new Error('`findUser` rejected and we're unhappy');
  11096. }).then(function (value) {
  11097. // never reached
  11098. }, function (reason) {
  11099. // if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
  11100. // If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
  11101. });
  11102. ```
  11103. If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
  11104. ```js
  11105. findUser().then(function (user) {
  11106. throw new PedagogicalException('Upstream error');
  11107. }).then(function (value) {
  11108. // never reached
  11109. }).then(function (value) {
  11110. // never reached
  11111. }, function (reason) {
  11112. // The `PedgagocialException` is propagated all the way down to here
  11113. });
  11114. ```
  11115. Assimilation
  11116. ------------
  11117. Sometimes the value you want to propagate to a downstream promise can only be
  11118. retrieved asynchronously. This can be achieved by returning a promise in the
  11119. fulfillment or rejection handler. The downstream promise will then be pending
  11120. until the returned promise is settled. This is called *assimilation*.
  11121. ```js
  11122. findUser().then(function (user) {
  11123. return findCommentsByAuthor(user);
  11124. }).then(function (comments) {
  11125. // The user's comments are now available
  11126. });
  11127. ```
  11128. If the assimliated promise rejects, then the downstream promise will also reject.
  11129. ```js
  11130. findUser().then(function (user) {
  11131. return findCommentsByAuthor(user);
  11132. }).then(function (comments) {
  11133. // If `findCommentsByAuthor` fulfills, we'll have the value here
  11134. }, function (reason) {
  11135. // If `findCommentsByAuthor` rejects, we'll have the reason here
  11136. });
  11137. ```
  11138. Simple Example
  11139. --------------
  11140. Synchronous Example
  11141. ```javascript
  11142. let result;
  11143. try {
  11144. result = findResult();
  11145. // success
  11146. } catch(reason) {
  11147. // failure
  11148. }
  11149. ```
  11150. Errback Example
  11151. ```js
  11152. findResult(function(result, err){
  11153. if (err) {
  11154. // failure
  11155. } else {
  11156. // success
  11157. }
  11158. });
  11159. ```
  11160. Promise Example;
  11161. ```javascript
  11162. findResult().then(function(result){
  11163. // success
  11164. }, function(reason){
  11165. // failure
  11166. });
  11167. ```
  11168. Advanced Example
  11169. --------------
  11170. Synchronous Example
  11171. ```javascript
  11172. let author, books;
  11173. try {
  11174. author = findAuthor();
  11175. books = findBooksByAuthor(author);
  11176. // success
  11177. } catch(reason) {
  11178. // failure
  11179. }
  11180. ```
  11181. Errback Example
  11182. ```js
  11183. function foundBooks(books) {
  11184. }
  11185. function failure(reason) {
  11186. }
  11187. findAuthor(function(author, err){
  11188. if (err) {
  11189. failure(err);
  11190. // failure
  11191. } else {
  11192. try {
  11193. findBoooksByAuthor(author, function(books, err) {
  11194. if (err) {
  11195. failure(err);
  11196. } else {
  11197. try {
  11198. foundBooks(books);
  11199. } catch(reason) {
  11200. failure(reason);
  11201. }
  11202. }
  11203. });
  11204. } catch(error) {
  11205. failure(err);
  11206. }
  11207. // success
  11208. }
  11209. });
  11210. ```
  11211. Promise Example;
  11212. ```javascript
  11213. findAuthor().
  11214. then(findBooksByAuthor).
  11215. then(function(books){
  11216. // found books
  11217. }).catch(function(reason){
  11218. // something went wrong
  11219. });
  11220. ```
  11221. @method then
  11222. @param {Function} onFulfilled
  11223. @param {Function} onRejected
  11224. Useful for tooling.
  11225. @return {Promise}
  11226. */
  11227. then: then,
  11228. /**
  11229. `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
  11230. as the catch block of a try/catch statement.
  11231. ```js
  11232. function findAuthor(){
  11233. throw new Error('couldn't find that author');
  11234. }
  11235. // synchronous
  11236. try {
  11237. findAuthor();
  11238. } catch(reason) {
  11239. // something went wrong
  11240. }
  11241. // async with promises
  11242. findAuthor().catch(function(reason){
  11243. // something went wrong
  11244. });
  11245. ```
  11246. @method catch
  11247. @param {Function} onRejection
  11248. Useful for tooling.
  11249. @return {Promise}
  11250. */
  11251. 'catch': function _catch(onRejection) {
  11252. return this.then(null, onRejection);
  11253. }
  11254. };
  11255. function polyfill() {
  11256. var local = undefined;
  11257. if (typeof global !== 'undefined') {
  11258. local = global;
  11259. } else if (typeof self !== 'undefined') {
  11260. local = self;
  11261. } else {
  11262. try {
  11263. local = Function('return this')();
  11264. } catch (e) {
  11265. throw new Error('polyfill failed because global object is unavailable in this environment');
  11266. }
  11267. }
  11268. var P = local.Promise;
  11269. if (P) {
  11270. var promiseToString = null;
  11271. try {
  11272. promiseToString = Object.prototype.toString.call(P.resolve());
  11273. } catch (e) {
  11274. // silently ignored
  11275. }
  11276. if (promiseToString === '[object Promise]' && !P.cast) {
  11277. return;
  11278. }
  11279. }
  11280. local.Promise = Promise;
  11281. }
  11282. polyfill();
  11283. // Strange compat..
  11284. Promise.polyfill = polyfill;
  11285. Promise.Promise = Promise;
  11286. return Promise;
  11287. })));
  11288. }).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11289. },{"_process":33}],18:[function(_dereq_,module,exports){
  11290. /**
  11291. * inspired by is-number <https://github.com/jonschlinkert/is-number>
  11292. * but significantly simplified and sped up by ignoring number and string constructors
  11293. * ie these return false:
  11294. * new Number(1)
  11295. * new String('1')
  11296. */
  11297. 'use strict';
  11298. var allBlankCharCodes = _dereq_('is-string-blank');
  11299. module.exports = function(n) {
  11300. var type = typeof n;
  11301. if(type === 'string') {
  11302. var original = n;
  11303. n = +n;
  11304. // whitespace strings cast to zero - filter them out
  11305. if(n===0 && allBlankCharCodes(original)) return false;
  11306. }
  11307. else if(type !== 'number') return false;
  11308. return n - n < 1;
  11309. };
  11310. },{"is-string-blank":23}],19:[function(_dereq_,module,exports){
  11311. module.exports = fromQuat;
  11312. /**
  11313. * Creates a matrix from a quaternion rotation.
  11314. *
  11315. * @param {mat4} out mat4 receiving operation result
  11316. * @param {quat4} q Rotation quaternion
  11317. * @returns {mat4} out
  11318. */
  11319. function fromQuat(out, q) {
  11320. var x = q[0], y = q[1], z = q[2], w = q[3],
  11321. x2 = x + x,
  11322. y2 = y + y,
  11323. z2 = z + z,
  11324. xx = x * x2,
  11325. yx = y * x2,
  11326. yy = y * y2,
  11327. zx = z * x2,
  11328. zy = z * y2,
  11329. zz = z * z2,
  11330. wx = w * x2,
  11331. wy = w * y2,
  11332. wz = w * z2;
  11333. out[0] = 1 - yy - zz;
  11334. out[1] = yx + wz;
  11335. out[2] = zx - wy;
  11336. out[3] = 0;
  11337. out[4] = yx - wz;
  11338. out[5] = 1 - xx - zz;
  11339. out[6] = zy + wx;
  11340. out[7] = 0;
  11341. out[8] = zx + wy;
  11342. out[9] = zy - wx;
  11343. out[10] = 1 - xx - yy;
  11344. out[11] = 0;
  11345. out[12] = 0;
  11346. out[13] = 0;
  11347. out[14] = 0;
  11348. out[15] = 1;
  11349. return out;
  11350. };
  11351. },{}],20:[function(_dereq_,module,exports){
  11352. (function (global){
  11353. 'use strict'
  11354. var isBrowser = _dereq_('is-browser')
  11355. var hasHover
  11356. if (typeof global.matchMedia === 'function') {
  11357. hasHover = !global.matchMedia('(hover: none)').matches
  11358. }
  11359. else {
  11360. hasHover = isBrowser
  11361. }
  11362. module.exports = hasHover
  11363. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11364. },{"is-browser":22}],21:[function(_dereq_,module,exports){
  11365. 'use strict'
  11366. var isBrowser = _dereq_('is-browser')
  11367. function detect() {
  11368. var supported = false
  11369. try {
  11370. var opts = Object.defineProperty({}, 'passive', {
  11371. get: function() {
  11372. supported = true
  11373. }
  11374. })
  11375. window.addEventListener('test', null, opts)
  11376. window.removeEventListener('test', null, opts)
  11377. } catch(e) {
  11378. supported = false
  11379. }
  11380. return supported
  11381. }
  11382. module.exports = isBrowser && detect()
  11383. },{"is-browser":22}],22:[function(_dereq_,module,exports){
  11384. module.exports = true;
  11385. },{}],23:[function(_dereq_,module,exports){
  11386. 'use strict';
  11387. /**
  11388. * Is this string all whitespace?
  11389. * This solution kind of makes my brain hurt, but it's significantly faster
  11390. * than !str.trim() or any other solution I could find.
  11391. *
  11392. * whitespace codes from: http://en.wikipedia.org/wiki/Whitespace_character
  11393. * and verified with:
  11394. *
  11395. * for(var i = 0; i < 65536; i++) {
  11396. * var s = String.fromCharCode(i);
  11397. * if(+s===0 && !s.trim()) console.log(i, s);
  11398. * }
  11399. *
  11400. * which counts a couple of these as *not* whitespace, but finds nothing else
  11401. * that *is* whitespace. Note that charCodeAt stops at 16 bits, but it appears
  11402. * that there are no whitespace characters above this, and code points above
  11403. * this do not map onto white space characters.
  11404. */
  11405. module.exports = function(str){
  11406. var l = str.length,
  11407. a;
  11408. for(var i = 0; i < l; i++) {
  11409. a = str.charCodeAt(i);
  11410. if((a < 9 || a > 13) && (a !== 32) && (a !== 133) && (a !== 160) &&
  11411. (a !== 5760) && (a !== 6158) && (a < 8192 || a > 8205) &&
  11412. (a !== 8232) && (a !== 8233) && (a !== 8239) && (a !== 8287) &&
  11413. (a !== 8288) && (a !== 12288) && (a !== 65279)) {
  11414. return false;
  11415. }
  11416. }
  11417. return true;
  11418. }
  11419. },{}],24:[function(_dereq_,module,exports){
  11420. var rootPosition = { left: 0, top: 0 }
  11421. module.exports = mouseEventOffset
  11422. function mouseEventOffset (ev, target, out) {
  11423. target = target || ev.currentTarget || ev.srcElement
  11424. if (!Array.isArray(out)) {
  11425. out = [ 0, 0 ]
  11426. }
  11427. var cx = ev.clientX || 0
  11428. var cy = ev.clientY || 0
  11429. var rect = getBoundingClientOffset(target)
  11430. out[0] = cx - rect.left
  11431. out[1] = cy - rect.top
  11432. return out
  11433. }
  11434. function getBoundingClientOffset (element) {
  11435. if (element === window ||
  11436. element === document ||
  11437. element === document.body) {
  11438. return rootPosition
  11439. } else {
  11440. return element.getBoundingClientRect()
  11441. }
  11442. }
  11443. },{}],25:[function(_dereq_,module,exports){
  11444. /*
  11445. * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc
  11446. * @license MIT
  11447. * @preserve Project Home: https://github.com/voidqk/polybooljs
  11448. */
  11449. var BuildLog = _dereq_('./lib/build-log');
  11450. var Epsilon = _dereq_('./lib/epsilon');
  11451. var Intersecter = _dereq_('./lib/intersecter');
  11452. var SegmentChainer = _dereq_('./lib/segment-chainer');
  11453. var SegmentSelector = _dereq_('./lib/segment-selector');
  11454. var GeoJSON = _dereq_('./lib/geojson');
  11455. var buildLog = false;
  11456. var epsilon = Epsilon();
  11457. var PolyBool;
  11458. PolyBool = {
  11459. // getter/setter for buildLog
  11460. buildLog: function(bl){
  11461. if (bl === true)
  11462. buildLog = BuildLog();
  11463. else if (bl === false)
  11464. buildLog = false;
  11465. return buildLog === false ? false : buildLog.list;
  11466. },
  11467. // getter/setter for epsilon
  11468. epsilon: function(v){
  11469. return epsilon.epsilon(v);
  11470. },
  11471. // core API
  11472. segments: function(poly){
  11473. var i = Intersecter(true, epsilon, buildLog);
  11474. poly.regions.forEach(i.addRegion);
  11475. return {
  11476. segments: i.calculate(poly.inverted),
  11477. inverted: poly.inverted
  11478. };
  11479. },
  11480. combine: function(segments1, segments2){
  11481. var i3 = Intersecter(false, epsilon, buildLog);
  11482. return {
  11483. combined: i3.calculate(
  11484. segments1.segments, segments1.inverted,
  11485. segments2.segments, segments2.inverted
  11486. ),
  11487. inverted1: segments1.inverted,
  11488. inverted2: segments2.inverted
  11489. };
  11490. },
  11491. selectUnion: function(combined){
  11492. return {
  11493. segments: SegmentSelector.union(combined.combined, buildLog),
  11494. inverted: combined.inverted1 || combined.inverted2
  11495. }
  11496. },
  11497. selectIntersect: function(combined){
  11498. return {
  11499. segments: SegmentSelector.intersect(combined.combined, buildLog),
  11500. inverted: combined.inverted1 && combined.inverted2
  11501. }
  11502. },
  11503. selectDifference: function(combined){
  11504. return {
  11505. segments: SegmentSelector.difference(combined.combined, buildLog),
  11506. inverted: combined.inverted1 && !combined.inverted2
  11507. }
  11508. },
  11509. selectDifferenceRev: function(combined){
  11510. return {
  11511. segments: SegmentSelector.differenceRev(combined.combined, buildLog),
  11512. inverted: !combined.inverted1 && combined.inverted2
  11513. }
  11514. },
  11515. selectXor: function(combined){
  11516. return {
  11517. segments: SegmentSelector.xor(combined.combined, buildLog),
  11518. inverted: combined.inverted1 !== combined.inverted2
  11519. }
  11520. },
  11521. polygon: function(segments){
  11522. return {
  11523. regions: SegmentChainer(segments.segments, epsilon, buildLog),
  11524. inverted: segments.inverted
  11525. };
  11526. },
  11527. // GeoJSON converters
  11528. polygonFromGeoJSON: function(geojson){
  11529. return GeoJSON.toPolygon(PolyBool, geojson);
  11530. },
  11531. polygonToGeoJSON: function(poly){
  11532. return GeoJSON.fromPolygon(PolyBool, epsilon, poly);
  11533. },
  11534. // helper functions for common operations
  11535. union: function(poly1, poly2){
  11536. return operate(poly1, poly2, PolyBool.selectUnion);
  11537. },
  11538. intersect: function(poly1, poly2){
  11539. return operate(poly1, poly2, PolyBool.selectIntersect);
  11540. },
  11541. difference: function(poly1, poly2){
  11542. return operate(poly1, poly2, PolyBool.selectDifference);
  11543. },
  11544. differenceRev: function(poly1, poly2){
  11545. return operate(poly1, poly2, PolyBool.selectDifferenceRev);
  11546. },
  11547. xor: function(poly1, poly2){
  11548. return operate(poly1, poly2, PolyBool.selectXor);
  11549. }
  11550. };
  11551. function operate(poly1, poly2, selector){
  11552. var seg1 = PolyBool.segments(poly1);
  11553. var seg2 = PolyBool.segments(poly2);
  11554. var comb = PolyBool.combine(seg1, seg2);
  11555. var seg3 = selector(comb);
  11556. return PolyBool.polygon(seg3);
  11557. }
  11558. if (typeof window === 'object')
  11559. window.PolyBool = PolyBool;
  11560. module.exports = PolyBool;
  11561. },{"./lib/build-log":26,"./lib/epsilon":27,"./lib/geojson":28,"./lib/intersecter":29,"./lib/segment-chainer":31,"./lib/segment-selector":32}],26:[function(_dereq_,module,exports){
  11562. // (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
  11563. // MIT License
  11564. // Project Home: https://github.com/voidqk/polybooljs
  11565. //
  11566. // used strictly for logging the processing of the algorithm... only useful if you intend on
  11567. // looking under the covers (for pretty UI's or debugging)
  11568. //
  11569. function BuildLog(){
  11570. var my;
  11571. var nextSegmentId = 0;
  11572. var curVert = false;
  11573. function push(type, data){
  11574. my.list.push({
  11575. type: type,
  11576. data: data ? JSON.parse(JSON.stringify(data)) : void 0
  11577. });
  11578. return my;
  11579. }
  11580. my = {
  11581. list: [],
  11582. segmentId: function(){
  11583. return nextSegmentId++;
  11584. },
  11585. checkIntersection: function(seg1, seg2){
  11586. return push('check', { seg1: seg1, seg2: seg2 });
  11587. },
  11588. segmentChop: function(seg, end){
  11589. push('div_seg', { seg: seg, pt: end });
  11590. return push('chop', { seg: seg, pt: end });
  11591. },
  11592. statusRemove: function(seg){
  11593. return push('pop_seg', { seg: seg });
  11594. },
  11595. segmentUpdate: function(seg){
  11596. return push('seg_update', { seg: seg });
  11597. },
  11598. segmentNew: function(seg, primary){
  11599. return push('new_seg', { seg: seg, primary: primary });
  11600. },
  11601. segmentRemove: function(seg){
  11602. return push('rem_seg', { seg: seg });
  11603. },
  11604. tempStatus: function(seg, above, below){
  11605. return push('temp_status', { seg: seg, above: above, below: below });
  11606. },
  11607. rewind: function(seg){
  11608. return push('rewind', { seg: seg });
  11609. },
  11610. status: function(seg, above, below){
  11611. return push('status', { seg: seg, above: above, below: below });
  11612. },
  11613. vert: function(x){
  11614. if (x === curVert)
  11615. return my;
  11616. curVert = x;
  11617. return push('vert', { x: x });
  11618. },
  11619. log: function(data){
  11620. if (typeof data !== 'string')
  11621. data = JSON.stringify(data, false, ' ');
  11622. return push('log', { txt: data });
  11623. },
  11624. reset: function(){
  11625. return push('reset');
  11626. },
  11627. selected: function(segs){
  11628. return push('selected', { segs: segs });
  11629. },
  11630. chainStart: function(seg){
  11631. return push('chain_start', { seg: seg });
  11632. },
  11633. chainRemoveHead: function(index, pt){
  11634. return push('chain_rem_head', { index: index, pt: pt });
  11635. },
  11636. chainRemoveTail: function(index, pt){
  11637. return push('chain_rem_tail', { index: index, pt: pt });
  11638. },
  11639. chainNew: function(pt1, pt2){
  11640. return push('chain_new', { pt1: pt1, pt2: pt2 });
  11641. },
  11642. chainMatch: function(index){
  11643. return push('chain_match', { index: index });
  11644. },
  11645. chainClose: function(index){
  11646. return push('chain_close', { index: index });
  11647. },
  11648. chainAddHead: function(index, pt){
  11649. return push('chain_add_head', { index: index, pt: pt });
  11650. },
  11651. chainAddTail: function(index, pt){
  11652. return push('chain_add_tail', { index: index, pt: pt, });
  11653. },
  11654. chainConnect: function(index1, index2){
  11655. return push('chain_con', { index1: index1, index2: index2 });
  11656. },
  11657. chainReverse: function(index){
  11658. return push('chain_rev', { index: index });
  11659. },
  11660. chainJoin: function(index1, index2){
  11661. return push('chain_join', { index1: index1, index2: index2 });
  11662. },
  11663. done: function(){
  11664. return push('done');
  11665. }
  11666. };
  11667. return my;
  11668. }
  11669. module.exports = BuildLog;
  11670. },{}],27:[function(_dereq_,module,exports){
  11671. // (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
  11672. // MIT License
  11673. // Project Home: https://github.com/voidqk/polybooljs
  11674. //
  11675. // provides the raw computation functions that takes epsilon into account
  11676. //
  11677. // zero is defined to be between (-epsilon, epsilon) exclusive
  11678. //
  11679. function Epsilon(eps){
  11680. if (typeof eps !== 'number')
  11681. eps = 0.0000000001; // sane default? sure why not
  11682. var my = {
  11683. epsilon: function(v){
  11684. if (typeof v === 'number')
  11685. eps = v;
  11686. return eps;
  11687. },
  11688. pointAboveOrOnLine: function(pt, left, right){
  11689. var Ax = left[0];
  11690. var Ay = left[1];
  11691. var Bx = right[0];
  11692. var By = right[1];
  11693. var Cx = pt[0];
  11694. var Cy = pt[1];
  11695. return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps;
  11696. },
  11697. pointBetween: function(p, left, right){
  11698. // p must be collinear with left->right
  11699. // returns false if p == left, p == right, or left == right
  11700. var d_py_ly = p[1] - left[1];
  11701. var d_rx_lx = right[0] - left[0];
  11702. var d_px_lx = p[0] - left[0];
  11703. var d_ry_ly = right[1] - left[1];
  11704. var dot = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly;
  11705. // if `dot` is 0, then `p` == `left` or `left` == `right` (reject)
  11706. // if `dot` is less than 0, then `p` is to the left of `left` (reject)
  11707. if (dot < eps)
  11708. return false;
  11709. var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly;
  11710. // if `dot` > `sqlen`, then `p` is to the right of `right` (reject)
  11711. // therefore, if `dot - sqlen` is greater than 0, then `p` is to the right of `right` (reject)
  11712. if (dot - sqlen > -eps)
  11713. return false;
  11714. return true;
  11715. },
  11716. pointsSameX: function(p1, p2){
  11717. return Math.abs(p1[0] - p2[0]) < eps;
  11718. },
  11719. pointsSameY: function(p1, p2){
  11720. return Math.abs(p1[1] - p2[1]) < eps;
  11721. },
  11722. pointsSame: function(p1, p2){
  11723. return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2);
  11724. },
  11725. pointsCompare: function(p1, p2){
  11726. // returns -1 if p1 is smaller, 1 if p2 is smaller, 0 if equal
  11727. if (my.pointsSameX(p1, p2))
  11728. return my.pointsSameY(p1, p2) ? 0 : (p1[1] < p2[1] ? -1 : 1);
  11729. return p1[0] < p2[0] ? -1 : 1;
  11730. },
  11731. pointsCollinear: function(pt1, pt2, pt3){
  11732. // does pt1->pt2->pt3 make a straight line?
  11733. // essentially this is just checking to see if the slope(pt1->pt2) === slope(pt2->pt3)
  11734. // if slopes are equal, then they must be collinear, because they share pt2
  11735. var dx1 = pt1[0] - pt2[0];
  11736. var dy1 = pt1[1] - pt2[1];
  11737. var dx2 = pt2[0] - pt3[0];
  11738. var dy2 = pt2[1] - pt3[1];
  11739. return Math.abs(dx1 * dy2 - dx2 * dy1) < eps;
  11740. },
  11741. linesIntersect: function(a0, a1, b0, b1){
  11742. // returns false if the lines are coincident (e.g., parallel or on top of each other)
  11743. //
  11744. // returns an object if the lines intersect:
  11745. // {
  11746. // pt: [x, y], where the intersection point is at
  11747. // alongA: where intersection point is along A,
  11748. // alongB: where intersection point is along B
  11749. // }
  11750. //
  11751. // alongA and alongB will each be one of: -2, -1, 0, 1, 2
  11752. //
  11753. // with the following meaning:
  11754. //
  11755. // -2 intersection point is before segment's first point
  11756. // -1 intersection point is directly on segment's first point
  11757. // 0 intersection point is between segment's first and second points (exclusive)
  11758. // 1 intersection point is directly on segment's second point
  11759. // 2 intersection point is after segment's second point
  11760. var adx = a1[0] - a0[0];
  11761. var ady = a1[1] - a0[1];
  11762. var bdx = b1[0] - b0[0];
  11763. var bdy = b1[1] - b0[1];
  11764. var axb = adx * bdy - ady * bdx;
  11765. if (Math.abs(axb) < eps)
  11766. return false; // lines are coincident
  11767. var dx = a0[0] - b0[0];
  11768. var dy = a0[1] - b0[1];
  11769. var A = (bdx * dy - bdy * dx) / axb;
  11770. var B = (adx * dy - ady * dx) / axb;
  11771. var ret = {
  11772. alongA: 0,
  11773. alongB: 0,
  11774. pt: [
  11775. a0[0] + A * adx,
  11776. a0[1] + A * ady
  11777. ]
  11778. };
  11779. // categorize where intersection point is along A and B
  11780. if (A <= -eps)
  11781. ret.alongA = -2;
  11782. else if (A < eps)
  11783. ret.alongA = -1;
  11784. else if (A - 1 <= -eps)
  11785. ret.alongA = 0;
  11786. else if (A - 1 < eps)
  11787. ret.alongA = 1;
  11788. else
  11789. ret.alongA = 2;
  11790. if (B <= -eps)
  11791. ret.alongB = -2;
  11792. else if (B < eps)
  11793. ret.alongB = -1;
  11794. else if (B - 1 <= -eps)
  11795. ret.alongB = 0;
  11796. else if (B - 1 < eps)
  11797. ret.alongB = 1;
  11798. else
  11799. ret.alongB = 2;
  11800. return ret;
  11801. },
  11802. pointInsideRegion: function(pt, region){
  11803. var x = pt[0];
  11804. var y = pt[1];
  11805. var last_x = region[region.length - 1][0];
  11806. var last_y = region[region.length - 1][1];
  11807. var inside = false;
  11808. for (var i = 0; i < region.length; i++){
  11809. var curr_x = region[i][0];
  11810. var curr_y = region[i][1];
  11811. // if y is between curr_y and last_y, and
  11812. // x is to the right of the boundary created by the line
  11813. if ((curr_y - y > eps) != (last_y - y > eps) &&
  11814. (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps)
  11815. inside = !inside
  11816. last_x = curr_x;
  11817. last_y = curr_y;
  11818. }
  11819. return inside;
  11820. }
  11821. };
  11822. return my;
  11823. }
  11824. module.exports = Epsilon;
  11825. },{}],28:[function(_dereq_,module,exports){
  11826. // (c) Copyright 2017, Sean Connelly (@voidqk), http://syntheti.cc
  11827. // MIT License
  11828. // Project Home: https://github.com/voidqk/polybooljs
  11829. //
  11830. // convert between PolyBool polygon format and GeoJSON formats (Polygon and MultiPolygon)
  11831. //
  11832. var GeoJSON = {
  11833. // convert a GeoJSON object to a PolyBool polygon
  11834. toPolygon: function(PolyBool, geojson){
  11835. // converts list of LineString's to segments
  11836. function GeoPoly(coords){
  11837. // check for empty coords
  11838. if (coords.length <= 0)
  11839. return PolyBool.segments({ inverted: false, regions: [] });
  11840. // convert LineString to segments
  11841. function LineString(ls){
  11842. // remove tail which should be the same as head
  11843. var reg = ls.slice(0, ls.length - 1);
  11844. return PolyBool.segments({ inverted: false, regions: [reg] });
  11845. }
  11846. // the first LineString is considered the outside
  11847. var out = LineString(coords[0]);
  11848. // the rest of the LineStrings are considered interior holes, so subtract them from the
  11849. // current result
  11850. for (var i = 1; i < coords.length; i++)
  11851. out = PolyBool.selectDifference(PolyBool.combine(out, LineString(coords[i])));
  11852. return out;
  11853. }
  11854. if (geojson.type === 'Polygon'){
  11855. // single polygon, so just convert it and we're done
  11856. return PolyBool.polygon(GeoPoly(geojson.coordinates));
  11857. }
  11858. else if (geojson.type === 'MultiPolygon'){
  11859. // multiple polygons, so union all the polygons together
  11860. var out = PolyBool.segments({ inverted: false, regions: [] });
  11861. for (var i = 0; i < geojson.coordinates.length; i++)
  11862. out = PolyBool.selectUnion(PolyBool.combine(out, GeoPoly(geojson.coordinates[i])));
  11863. return PolyBool.polygon(out);
  11864. }
  11865. throw new Error('PolyBool: Cannot convert GeoJSON object to PolyBool polygon');
  11866. },
  11867. // convert a PolyBool polygon to a GeoJSON object
  11868. fromPolygon: function(PolyBool, eps, poly){
  11869. // make sure out polygon is clean
  11870. poly = PolyBool.polygon(PolyBool.segments(poly));
  11871. // test if r1 is inside r2
  11872. function regionInsideRegion(r1, r2){
  11873. // we're guaranteed no lines intersect (because the polygon is clean), but a vertex
  11874. // could be on the edge -- so we just average pt[0] and pt[1] to produce a point on the
  11875. // edge of the first line, which cannot be on an edge
  11876. return eps.pointInsideRegion([
  11877. (r1[0][0] + r1[1][0]) * 0.5,
  11878. (r1[0][1] + r1[1][1]) * 0.5
  11879. ], r2);
  11880. }
  11881. // calculate inside heirarchy
  11882. //
  11883. // _____________________ _______ roots -> A -> F
  11884. // | A | | F | | |
  11885. // | _______ _______ | | ___ | +-- B +-- G
  11886. // | | B | | C | | | | | | | |
  11887. // | | ___ | | ___ | | | | | | | +-- D
  11888. // | | | D | | | | E | | | | | G | | |
  11889. // | | |___| | | |___| | | | | | | +-- C
  11890. // | |_______| |_______| | | |___| | |
  11891. // |_____________________| |_______| +-- E
  11892. function newNode(region){
  11893. return {
  11894. region: region,
  11895. children: []
  11896. };
  11897. }
  11898. var roots = newNode(null);
  11899. function addChild(root, region){
  11900. // first check if we're inside any children
  11901. for (var i = 0; i < root.children.length; i++){
  11902. var child = root.children[i];
  11903. if (regionInsideRegion(region, child.region)){
  11904. // we are, so insert inside them instead
  11905. addChild(child, region);
  11906. return;
  11907. }
  11908. }
  11909. // not inside any children, so check to see if any children are inside us
  11910. var node = newNode(region);
  11911. for (var i = 0; i < root.children.length; i++){
  11912. var child = root.children[i];
  11913. if (regionInsideRegion(child.region, region)){
  11914. // oops... move the child beneath us, and remove them from root
  11915. node.children.push(child);
  11916. root.children.splice(i, 1);
  11917. i--;
  11918. }
  11919. }
  11920. // now we can add ourselves
  11921. root.children.push(node);
  11922. }
  11923. // add all regions to the root
  11924. for (var i = 0; i < poly.regions.length; i++){
  11925. var region = poly.regions[i];
  11926. if (region.length < 3) // regions must have at least 3 points (sanity check)
  11927. continue;
  11928. addChild(roots, region);
  11929. }
  11930. // with our heirarchy, we can distinguish between exterior borders, and interior holes
  11931. // the root nodes are exterior, children are interior, children's children are exterior,
  11932. // children's children's children are interior, etc
  11933. // while we're at it, exteriors are counter-clockwise, and interiors are clockwise
  11934. function forceWinding(region, clockwise){
  11935. // first, see if we're clockwise or counter-clockwise
  11936. // https://en.wikipedia.org/wiki/Shoelace_formula
  11937. var winding = 0;
  11938. var last_x = region[region.length - 1][0];
  11939. var last_y = region[region.length - 1][1];
  11940. var copy = [];
  11941. for (var i = 0; i < region.length; i++){
  11942. var curr_x = region[i][0];
  11943. var curr_y = region[i][1];
  11944. copy.push([curr_x, curr_y]); // create a copy while we're at it
  11945. winding += curr_y * last_x - curr_x * last_y;
  11946. last_x = curr_x;
  11947. last_y = curr_y;
  11948. }
  11949. // this assumes Cartesian coordinates (Y is positive going up)
  11950. var isclockwise = winding < 0;
  11951. if (isclockwise !== clockwise)
  11952. copy.reverse();
  11953. // while we're here, the last point must be the first point...
  11954. copy.push([copy[0][0], copy[0][1]]);
  11955. return copy;
  11956. }
  11957. var geopolys = [];
  11958. function addExterior(node){
  11959. var poly = [forceWinding(node.region, false)];
  11960. geopolys.push(poly);
  11961. // children of exteriors are interior
  11962. for (var i = 0; i < node.children.length; i++)
  11963. poly.push(getInterior(node.children[i]));
  11964. }
  11965. function getInterior(node){
  11966. // children of interiors are exterior
  11967. for (var i = 0; i < node.children.length; i++)
  11968. addExterior(node.children[i]);
  11969. // return the clockwise interior
  11970. return forceWinding(node.region, true);
  11971. }
  11972. // root nodes are exterior
  11973. for (var i = 0; i < roots.children.length; i++)
  11974. addExterior(roots.children[i]);
  11975. // lastly, construct the approrpriate GeoJSON object
  11976. if (geopolys.length <= 0) // empty GeoJSON Polygon
  11977. return { type: 'Polygon', coordinates: [] };
  11978. if (geopolys.length == 1) // use a GeoJSON Polygon
  11979. return { type: 'Polygon', coordinates: geopolys[0] };
  11980. return { // otherwise, use a GeoJSON MultiPolygon
  11981. type: 'MultiPolygon',
  11982. coordinates: geopolys
  11983. };
  11984. }
  11985. };
  11986. module.exports = GeoJSON;
  11987. },{}],29:[function(_dereq_,module,exports){
  11988. // (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
  11989. // MIT License
  11990. // Project Home: https://github.com/voidqk/polybooljs
  11991. //
  11992. // this is the core work-horse
  11993. //
  11994. var LinkedList = _dereq_('./linked-list');
  11995. function Intersecter(selfIntersection, eps, buildLog){
  11996. // selfIntersection is true/false depending on the phase of the overall algorithm
  11997. //
  11998. // segment creation
  11999. //
  12000. function segmentNew(start, end){
  12001. return {
  12002. id: buildLog ? buildLog.segmentId() : -1,
  12003. start: start,
  12004. end: end,
  12005. myFill: {
  12006. above: null, // is there fill above us?
  12007. below: null // is there fill below us?
  12008. },
  12009. otherFill: null
  12010. };
  12011. }
  12012. function segmentCopy(start, end, seg){
  12013. return {
  12014. id: buildLog ? buildLog.segmentId() : -1,
  12015. start: start,
  12016. end: end,
  12017. myFill: {
  12018. above: seg.myFill.above,
  12019. below: seg.myFill.below
  12020. },
  12021. otherFill: null
  12022. };
  12023. }
  12024. //
  12025. // event logic
  12026. //
  12027. var event_root = LinkedList.create();
  12028. function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2){
  12029. // compare the selected points first
  12030. var comp = eps.pointsCompare(p1_1, p2_1);
  12031. if (comp !== 0)
  12032. return comp;
  12033. // the selected points are the same
  12034. if (eps.pointsSame(p1_2, p2_2)) // if the non-selected points are the same too...
  12035. return 0; // then the segments are equal
  12036. if (p1_isStart !== p2_isStart) // if one is a start and the other isn't...
  12037. return p1_isStart ? 1 : -1; // favor the one that isn't the start
  12038. // otherwise, we'll have to calculate which one is below the other manually
  12039. return eps.pointAboveOrOnLine(p1_2,
  12040. p2_isStart ? p2_1 : p2_2, // order matters
  12041. p2_isStart ? p2_2 : p2_1
  12042. ) ? 1 : -1;
  12043. }
  12044. function eventAdd(ev, other_pt){
  12045. event_root.insertBefore(ev, function(here){
  12046. // should ev be inserted before here?
  12047. var comp = eventCompare(
  12048. ev .isStart, ev .pt, other_pt,
  12049. here.isStart, here.pt, here.other.pt
  12050. );
  12051. return comp < 0;
  12052. });
  12053. }
  12054. function eventAddSegmentStart(seg, primary){
  12055. var ev_start = LinkedList.node({
  12056. isStart: true,
  12057. pt: seg.start,
  12058. seg: seg,
  12059. primary: primary,
  12060. other: null,
  12061. status: null
  12062. });
  12063. eventAdd(ev_start, seg.end);
  12064. return ev_start;
  12065. }
  12066. function eventAddSegmentEnd(ev_start, seg, primary){
  12067. var ev_end = LinkedList.node({
  12068. isStart: false,
  12069. pt: seg.end,
  12070. seg: seg,
  12071. primary: primary,
  12072. other: ev_start,
  12073. status: null
  12074. });
  12075. ev_start.other = ev_end;
  12076. eventAdd(ev_end, ev_start.pt);
  12077. }
  12078. function eventAddSegment(seg, primary){
  12079. var ev_start = eventAddSegmentStart(seg, primary);
  12080. eventAddSegmentEnd(ev_start, seg, primary);
  12081. return ev_start;
  12082. }
  12083. function eventUpdateEnd(ev, end){
  12084. // slides an end backwards
  12085. // (start)------------(end) to:
  12086. // (start)---(end)
  12087. if (buildLog)
  12088. buildLog.segmentChop(ev.seg, end);
  12089. ev.other.remove();
  12090. ev.seg.end = end;
  12091. ev.other.pt = end;
  12092. eventAdd(ev.other, ev.pt);
  12093. }
  12094. function eventDivide(ev, pt){
  12095. var ns = segmentCopy(pt, ev.seg.end, ev.seg);
  12096. eventUpdateEnd(ev, pt);
  12097. return eventAddSegment(ns, ev.primary);
  12098. }
  12099. function calculate(primaryPolyInverted, secondaryPolyInverted){
  12100. // if selfIntersection is true then there is no secondary polygon, so that isn't used
  12101. //
  12102. // status logic
  12103. //
  12104. var status_root = LinkedList.create();
  12105. function statusCompare(ev1, ev2){
  12106. var a1 = ev1.seg.start;
  12107. var a2 = ev1.seg.end;
  12108. var b1 = ev2.seg.start;
  12109. var b2 = ev2.seg.end;
  12110. if (eps.pointsCollinear(a1, b1, b2)){
  12111. if (eps.pointsCollinear(a2, b1, b2))
  12112. return 1;//eventCompare(true, a1, a2, true, b1, b2);
  12113. return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1;
  12114. }
  12115. return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1;
  12116. }
  12117. function statusFindSurrounding(ev){
  12118. return status_root.findTransition(function(here){
  12119. var comp = statusCompare(ev, here.ev);
  12120. return comp > 0;
  12121. });
  12122. }
  12123. function checkIntersection(ev1, ev2){
  12124. // returns the segment equal to ev1, or false if nothing equal
  12125. var seg1 = ev1.seg;
  12126. var seg2 = ev2.seg;
  12127. var a1 = seg1.start;
  12128. var a2 = seg1.end;
  12129. var b1 = seg2.start;
  12130. var b2 = seg2.end;
  12131. if (buildLog)
  12132. buildLog.checkIntersection(seg1, seg2);
  12133. var i = eps.linesIntersect(a1, a2, b1, b2);
  12134. if (i === false){
  12135. // segments are parallel or coincident
  12136. // if points aren't collinear, then the segments are parallel, so no intersections
  12137. if (!eps.pointsCollinear(a1, a2, b1))
  12138. return false;
  12139. // otherwise, segments are on top of each other somehow (aka coincident)
  12140. if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1))
  12141. return false; // segments touch at endpoints... no intersection
  12142. var a1_equ_b1 = eps.pointsSame(a1, b1);
  12143. var a2_equ_b2 = eps.pointsSame(a2, b2);
  12144. if (a1_equ_b1 && a2_equ_b2)
  12145. return ev2; // segments are exactly equal
  12146. var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2);
  12147. var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2);
  12148. // handy for debugging:
  12149. // buildLog.log({
  12150. // a1_equ_b1: a1_equ_b1,
  12151. // a2_equ_b2: a2_equ_b2,
  12152. // a1_between: a1_between,
  12153. // a2_between: a2_between
  12154. // });
  12155. if (a1_equ_b1){
  12156. if (a2_between){
  12157. // (a1)---(a2)
  12158. // (b1)----------(b2)
  12159. eventDivide(ev2, a2);
  12160. }
  12161. else{
  12162. // (a1)----------(a2)
  12163. // (b1)---(b2)
  12164. eventDivide(ev1, b2);
  12165. }
  12166. return ev2;
  12167. }
  12168. else if (a1_between){
  12169. if (!a2_equ_b2){
  12170. // make a2 equal to b2
  12171. if (a2_between){
  12172. // (a1)---(a2)
  12173. // (b1)-----------------(b2)
  12174. eventDivide(ev2, a2);
  12175. }
  12176. else{
  12177. // (a1)----------(a2)
  12178. // (b1)----------(b2)
  12179. eventDivide(ev1, b2);
  12180. }
  12181. }
  12182. // (a1)---(a2)
  12183. // (b1)----------(b2)
  12184. eventDivide(ev2, a1);
  12185. }
  12186. }
  12187. else{
  12188. // otherwise, lines intersect at i.pt, which may or may not be between the endpoints
  12189. // is A divided between its endpoints? (exclusive)
  12190. if (i.alongA === 0){
  12191. if (i.alongB === -1) // yes, at exactly b1
  12192. eventDivide(ev1, b1);
  12193. else if (i.alongB === 0) // yes, somewhere between B's endpoints
  12194. eventDivide(ev1, i.pt);
  12195. else if (i.alongB === 1) // yes, at exactly b2
  12196. eventDivide(ev1, b2);
  12197. }
  12198. // is B divided between its endpoints? (exclusive)
  12199. if (i.alongB === 0){
  12200. if (i.alongA === -1) // yes, at exactly a1
  12201. eventDivide(ev2, a1);
  12202. else if (i.alongA === 0) // yes, somewhere between A's endpoints (exclusive)
  12203. eventDivide(ev2, i.pt);
  12204. else if (i.alongA === 1) // yes, at exactly a2
  12205. eventDivide(ev2, a2);
  12206. }
  12207. }
  12208. return false;
  12209. }
  12210. //
  12211. // main event loop
  12212. //
  12213. var segments = [];
  12214. while (!event_root.isEmpty()){
  12215. var ev = event_root.getHead();
  12216. if (buildLog)
  12217. buildLog.vert(ev.pt[0]);
  12218. if (ev.isStart){
  12219. if (buildLog)
  12220. buildLog.segmentNew(ev.seg, ev.primary);
  12221. var surrounding = statusFindSurrounding(ev);
  12222. var above = surrounding.before ? surrounding.before.ev : null;
  12223. var below = surrounding.after ? surrounding.after.ev : null;
  12224. if (buildLog){
  12225. buildLog.tempStatus(
  12226. ev.seg,
  12227. above ? above.seg : false,
  12228. below ? below.seg : false
  12229. );
  12230. }
  12231. function checkBothIntersections(){
  12232. if (above){
  12233. var eve = checkIntersection(ev, above);
  12234. if (eve)
  12235. return eve;
  12236. }
  12237. if (below)
  12238. return checkIntersection(ev, below);
  12239. return false;
  12240. }
  12241. var eve = checkBothIntersections();
  12242. if (eve){
  12243. // ev and eve are equal
  12244. // we'll keep eve and throw away ev
  12245. // merge ev.seg's fill information into eve.seg
  12246. if (selfIntersection){
  12247. var toggle; // are we a toggling edge?
  12248. if (ev.seg.myFill.below === null)
  12249. toggle = true;
  12250. else
  12251. toggle = ev.seg.myFill.above !== ev.seg.myFill.below;
  12252. // merge two segments that belong to the same polygon
  12253. // think of this as sandwiching two segments together, where `eve.seg` is
  12254. // the bottom -- this will cause the above fill flag to toggle
  12255. if (toggle)
  12256. eve.seg.myFill.above = !eve.seg.myFill.above;
  12257. }
  12258. else{
  12259. // merge two segments that belong to different polygons
  12260. // each segment has distinct knowledge, so no special logic is needed
  12261. // note that this can only happen once per segment in this phase, because we
  12262. // are guaranteed that all self-intersections are gone
  12263. eve.seg.otherFill = ev.seg.myFill;
  12264. }
  12265. if (buildLog)
  12266. buildLog.segmentUpdate(eve.seg);
  12267. ev.other.remove();
  12268. ev.remove();
  12269. }
  12270. if (event_root.getHead() !== ev){
  12271. // something was inserted before us in the event queue, so loop back around and
  12272. // process it before continuing
  12273. if (buildLog)
  12274. buildLog.rewind(ev.seg);
  12275. continue;
  12276. }
  12277. //
  12278. // calculate fill flags
  12279. //
  12280. if (selfIntersection){
  12281. var toggle; // are we a toggling edge?
  12282. if (ev.seg.myFill.below === null) // if we are a new segment...
  12283. toggle = true; // then we toggle
  12284. else // we are a segment that has previous knowledge from a division
  12285. toggle = ev.seg.myFill.above !== ev.seg.myFill.below; // calculate toggle
  12286. // next, calculate whether we are filled below us
  12287. if (!below){ // if nothing is below us...
  12288. // we are filled below us if the polygon is inverted
  12289. ev.seg.myFill.below = primaryPolyInverted;
  12290. }
  12291. else{
  12292. // otherwise, we know the answer -- it's the same if whatever is below
  12293. // us is filled above it
  12294. ev.seg.myFill.below = below.seg.myFill.above;
  12295. }
  12296. // since now we know if we're filled below us, we can calculate whether
  12297. // we're filled above us by applying toggle to whatever is below us
  12298. if (toggle)
  12299. ev.seg.myFill.above = !ev.seg.myFill.below;
  12300. else
  12301. ev.seg.myFill.above = ev.seg.myFill.below;
  12302. }
  12303. else{
  12304. // now we fill in any missing transition information, since we are all-knowing
  12305. // at this point
  12306. if (ev.seg.otherFill === null){
  12307. // if we don't have other information, then we need to figure out if we're
  12308. // inside the other polygon
  12309. var inside;
  12310. if (!below){
  12311. // if nothing is below us, then we're inside if the other polygon is
  12312. // inverted
  12313. inside =
  12314. ev.primary ? secondaryPolyInverted : primaryPolyInverted;
  12315. }
  12316. else{ // otherwise, something is below us
  12317. // so copy the below segment's other polygon's above
  12318. if (ev.primary === below.primary)
  12319. inside = below.seg.otherFill.above;
  12320. else
  12321. inside = below.seg.myFill.above;
  12322. }
  12323. ev.seg.otherFill = {
  12324. above: inside,
  12325. below: inside
  12326. };
  12327. }
  12328. }
  12329. if (buildLog){
  12330. buildLog.status(
  12331. ev.seg,
  12332. above ? above.seg : false,
  12333. below ? below.seg : false
  12334. );
  12335. }
  12336. // insert the status and remember it for later removal
  12337. ev.other.status = surrounding.insert(LinkedList.node({ ev: ev }));
  12338. }
  12339. else{
  12340. var st = ev.status;
  12341. if (st === null){
  12342. throw new Error('PolyBool: Zero-length segment detected; your epsilon is ' +
  12343. 'probably too small or too large');
  12344. }
  12345. // removing the status will create two new adjacent edges, so we'll need to check
  12346. // for those
  12347. if (status_root.exists(st.prev) && status_root.exists(st.next))
  12348. checkIntersection(st.prev.ev, st.next.ev);
  12349. if (buildLog)
  12350. buildLog.statusRemove(st.ev.seg);
  12351. // remove the status
  12352. st.remove();
  12353. // if we've reached this point, we've calculated everything there is to know, so
  12354. // save the segment for reporting
  12355. if (!ev.primary){
  12356. // make sure `seg.myFill` actually points to the primary polygon though
  12357. var s = ev.seg.myFill;
  12358. ev.seg.myFill = ev.seg.otherFill;
  12359. ev.seg.otherFill = s;
  12360. }
  12361. segments.push(ev.seg);
  12362. }
  12363. // remove the event and continue
  12364. event_root.getHead().remove();
  12365. }
  12366. if (buildLog)
  12367. buildLog.done();
  12368. return segments;
  12369. }
  12370. // return the appropriate API depending on what we're doing
  12371. if (!selfIntersection){
  12372. // performing combination of polygons, so only deal with already-processed segments
  12373. return {
  12374. calculate: function(segments1, inverted1, segments2, inverted2){
  12375. // segmentsX come from the self-intersection API, or this API
  12376. // invertedX is whether we treat that list of segments as an inverted polygon or not
  12377. // returns segments that can be used for further operations
  12378. segments1.forEach(function(seg){
  12379. eventAddSegment(segmentCopy(seg.start, seg.end, seg), true);
  12380. });
  12381. segments2.forEach(function(seg){
  12382. eventAddSegment(segmentCopy(seg.start, seg.end, seg), false);
  12383. });
  12384. return calculate(inverted1, inverted2);
  12385. }
  12386. };
  12387. }
  12388. // otherwise, performing self-intersection, so deal with regions
  12389. return {
  12390. addRegion: function(region){
  12391. // regions are a list of points:
  12392. // [ [0, 0], [100, 0], [50, 100] ]
  12393. // you can add multiple regions before running calculate
  12394. var pt1;
  12395. var pt2 = region[region.length - 1];
  12396. for (var i = 0; i < region.length; i++){
  12397. pt1 = pt2;
  12398. pt2 = region[i];
  12399. var forward = eps.pointsCompare(pt1, pt2);
  12400. if (forward === 0) // points are equal, so we have a zero-length segment
  12401. continue; // just skip it
  12402. eventAddSegment(
  12403. segmentNew(
  12404. forward < 0 ? pt1 : pt2,
  12405. forward < 0 ? pt2 : pt1
  12406. ),
  12407. true
  12408. );
  12409. }
  12410. },
  12411. calculate: function(inverted){
  12412. // is the polygon inverted?
  12413. // returns segments
  12414. return calculate(inverted, false);
  12415. }
  12416. };
  12417. }
  12418. module.exports = Intersecter;
  12419. },{"./linked-list":30}],30:[function(_dereq_,module,exports){
  12420. // (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
  12421. // MIT License
  12422. // Project Home: https://github.com/voidqk/polybooljs
  12423. //
  12424. // simple linked list implementation that allows you to traverse down nodes and save positions
  12425. //
  12426. var LinkedList = {
  12427. create: function(){
  12428. var my = {
  12429. root: { root: true, next: null },
  12430. exists: function(node){
  12431. if (node === null || node === my.root)
  12432. return false;
  12433. return true;
  12434. },
  12435. isEmpty: function(){
  12436. return my.root.next === null;
  12437. },
  12438. getHead: function(){
  12439. return my.root.next;
  12440. },
  12441. insertBefore: function(node, check){
  12442. var last = my.root;
  12443. var here = my.root.next;
  12444. while (here !== null){
  12445. if (check(here)){
  12446. node.prev = here.prev;
  12447. node.next = here;
  12448. here.prev.next = node;
  12449. here.prev = node;
  12450. return;
  12451. }
  12452. last = here;
  12453. here = here.next;
  12454. }
  12455. last.next = node;
  12456. node.prev = last;
  12457. node.next = null;
  12458. },
  12459. findTransition: function(check){
  12460. var prev = my.root;
  12461. var here = my.root.next;
  12462. while (here !== null){
  12463. if (check(here))
  12464. break;
  12465. prev = here;
  12466. here = here.next;
  12467. }
  12468. return {
  12469. before: prev === my.root ? null : prev,
  12470. after: here,
  12471. insert: function(node){
  12472. node.prev = prev;
  12473. node.next = here;
  12474. prev.next = node;
  12475. if (here !== null)
  12476. here.prev = node;
  12477. return node;
  12478. }
  12479. };
  12480. }
  12481. };
  12482. return my;
  12483. },
  12484. node: function(data){
  12485. data.prev = null;
  12486. data.next = null;
  12487. data.remove = function(){
  12488. data.prev.next = data.next;
  12489. if (data.next)
  12490. data.next.prev = data.prev;
  12491. data.prev = null;
  12492. data.next = null;
  12493. };
  12494. return data;
  12495. }
  12496. };
  12497. module.exports = LinkedList;
  12498. },{}],31:[function(_dereq_,module,exports){
  12499. // (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
  12500. // MIT License
  12501. // Project Home: https://github.com/voidqk/polybooljs
  12502. //
  12503. // converts a list of segments into a list of regions, while also removing unnecessary verticies
  12504. //
  12505. function SegmentChainer(segments, eps, buildLog){
  12506. var chains = [];
  12507. var regions = [];
  12508. segments.forEach(function(seg){
  12509. var pt1 = seg.start;
  12510. var pt2 = seg.end;
  12511. if (eps.pointsSame(pt1, pt2)){
  12512. console.warn('PolyBool: Warning: Zero-length segment detected; your epsilon is ' +
  12513. 'probably too small or too large');
  12514. return;
  12515. }
  12516. if (buildLog)
  12517. buildLog.chainStart(seg);
  12518. // search for two chains that this segment matches
  12519. var first_match = {
  12520. index: 0,
  12521. matches_head: false,
  12522. matches_pt1: false
  12523. };
  12524. var second_match = {
  12525. index: 0,
  12526. matches_head: false,
  12527. matches_pt1: false
  12528. };
  12529. var next_match = first_match;
  12530. function setMatch(index, matches_head, matches_pt1){
  12531. // return true if we've matched twice
  12532. next_match.index = index;
  12533. next_match.matches_head = matches_head;
  12534. next_match.matches_pt1 = matches_pt1;
  12535. if (next_match === first_match){
  12536. next_match = second_match;
  12537. return false;
  12538. }
  12539. next_match = null;
  12540. return true; // we've matched twice, we're done here
  12541. }
  12542. for (var i = 0; i < chains.length; i++){
  12543. var chain = chains[i];
  12544. var head = chain[0];
  12545. var head2 = chain[1];
  12546. var tail = chain[chain.length - 1];
  12547. var tail2 = chain[chain.length - 2];
  12548. if (eps.pointsSame(head, pt1)){
  12549. if (setMatch(i, true, true))
  12550. break;
  12551. }
  12552. else if (eps.pointsSame(head, pt2)){
  12553. if (setMatch(i, true, false))
  12554. break;
  12555. }
  12556. else if (eps.pointsSame(tail, pt1)){
  12557. if (setMatch(i, false, true))
  12558. break;
  12559. }
  12560. else if (eps.pointsSame(tail, pt2)){
  12561. if (setMatch(i, false, false))
  12562. break;
  12563. }
  12564. }
  12565. if (next_match === first_match){
  12566. // we didn't match anything, so create a new chain
  12567. chains.push([ pt1, pt2 ]);
  12568. if (buildLog)
  12569. buildLog.chainNew(pt1, pt2);
  12570. return;
  12571. }
  12572. if (next_match === second_match){
  12573. // we matched a single chain
  12574. if (buildLog)
  12575. buildLog.chainMatch(first_match.index);
  12576. // add the other point to the apporpriate end, and check to see if we've closed the
  12577. // chain into a loop
  12578. var index = first_match.index;
  12579. var pt = first_match.matches_pt1 ? pt2 : pt1; // if we matched pt1, then we add pt2, etc
  12580. var addToHead = first_match.matches_head; // if we matched at head, then add to the head
  12581. var chain = chains[index];
  12582. var grow = addToHead ? chain[0] : chain[chain.length - 1];
  12583. var grow2 = addToHead ? chain[1] : chain[chain.length - 2];
  12584. var oppo = addToHead ? chain[chain.length - 1] : chain[0];
  12585. var oppo2 = addToHead ? chain[chain.length - 2] : chain[1];
  12586. if (eps.pointsCollinear(grow2, grow, pt)){
  12587. // grow isn't needed because it's directly between grow2 and pt:
  12588. // grow2 ---grow---> pt
  12589. if (addToHead){
  12590. if (buildLog)
  12591. buildLog.chainRemoveHead(first_match.index, pt);
  12592. chain.shift();
  12593. }
  12594. else{
  12595. if (buildLog)
  12596. buildLog.chainRemoveTail(first_match.index, pt);
  12597. chain.pop();
  12598. }
  12599. grow = grow2; // old grow is gone... new grow is what grow2 was
  12600. }
  12601. if (eps.pointsSame(oppo, pt)){
  12602. // we're closing the loop, so remove chain from chains
  12603. chains.splice(index, 1);
  12604. if (eps.pointsCollinear(oppo2, oppo, grow)){
  12605. // oppo isn't needed because it's directly between oppo2 and grow:
  12606. // oppo2 ---oppo--->grow
  12607. if (addToHead){
  12608. if (buildLog)
  12609. buildLog.chainRemoveTail(first_match.index, grow);
  12610. chain.pop();
  12611. }
  12612. else{
  12613. if (buildLog)
  12614. buildLog.chainRemoveHead(first_match.index, grow);
  12615. chain.shift();
  12616. }
  12617. }
  12618. if (buildLog)
  12619. buildLog.chainClose(first_match.index);
  12620. // we have a closed chain!
  12621. regions.push(chain);
  12622. return;
  12623. }
  12624. // not closing a loop, so just add it to the apporpriate side
  12625. if (addToHead){
  12626. if (buildLog)
  12627. buildLog.chainAddHead(first_match.index, pt);
  12628. chain.unshift(pt);
  12629. }
  12630. else{
  12631. if (buildLog)
  12632. buildLog.chainAddTail(first_match.index, pt);
  12633. chain.push(pt);
  12634. }
  12635. return;
  12636. }
  12637. // otherwise, we matched two chains, so we need to combine those chains together
  12638. function reverseChain(index){
  12639. if (buildLog)
  12640. buildLog.chainReverse(index);
  12641. chains[index].reverse(); // gee, that's easy
  12642. }
  12643. function appendChain(index1, index2){
  12644. // index1 gets index2 appended to it, and index2 is removed
  12645. var chain1 = chains[index1];
  12646. var chain2 = chains[index2];
  12647. var tail = chain1[chain1.length - 1];
  12648. var tail2 = chain1[chain1.length - 2];
  12649. var head = chain2[0];
  12650. var head2 = chain2[1];
  12651. if (eps.pointsCollinear(tail2, tail, head)){
  12652. // tail isn't needed because it's directly between tail2 and head
  12653. // tail2 ---tail---> head
  12654. if (buildLog)
  12655. buildLog.chainRemoveTail(index1, tail);
  12656. chain1.pop();
  12657. tail = tail2; // old tail is gone... new tail is what tail2 was
  12658. }
  12659. if (eps.pointsCollinear(tail, head, head2)){
  12660. // head isn't needed because it's directly between tail and head2
  12661. // tail ---head---> head2
  12662. if (buildLog)
  12663. buildLog.chainRemoveHead(index2, head);
  12664. chain2.shift();
  12665. }
  12666. if (buildLog)
  12667. buildLog.chainJoin(index1, index2);
  12668. chains[index1] = chain1.concat(chain2);
  12669. chains.splice(index2, 1);
  12670. }
  12671. var F = first_match.index;
  12672. var S = second_match.index;
  12673. if (buildLog)
  12674. buildLog.chainConnect(F, S);
  12675. var reverseF = chains[F].length < chains[S].length; // reverse the shorter chain, if needed
  12676. if (first_match.matches_head){
  12677. if (second_match.matches_head){
  12678. if (reverseF){
  12679. // <<<< F <<<< --- >>>> S >>>>
  12680. reverseChain(F);
  12681. // >>>> F >>>> --- >>>> S >>>>
  12682. appendChain(F, S);
  12683. }
  12684. else{
  12685. // <<<< F <<<< --- >>>> S >>>>
  12686. reverseChain(S);
  12687. // <<<< F <<<< --- <<<< S <<<< logically same as:
  12688. // >>>> S >>>> --- >>>> F >>>>
  12689. appendChain(S, F);
  12690. }
  12691. }
  12692. else{
  12693. // <<<< F <<<< --- <<<< S <<<< logically same as:
  12694. // >>>> S >>>> --- >>>> F >>>>
  12695. appendChain(S, F);
  12696. }
  12697. }
  12698. else{
  12699. if (second_match.matches_head){
  12700. // >>>> F >>>> --- >>>> S >>>>
  12701. appendChain(F, S);
  12702. }
  12703. else{
  12704. if (reverseF){
  12705. // >>>> F >>>> --- <<<< S <<<<
  12706. reverseChain(F);
  12707. // <<<< F <<<< --- <<<< S <<<< logically same as:
  12708. // >>>> S >>>> --- >>>> F >>>>
  12709. appendChain(S, F);
  12710. }
  12711. else{
  12712. // >>>> F >>>> --- <<<< S <<<<
  12713. reverseChain(S);
  12714. // >>>> F >>>> --- >>>> S >>>>
  12715. appendChain(F, S);
  12716. }
  12717. }
  12718. }
  12719. });
  12720. return regions;
  12721. }
  12722. module.exports = SegmentChainer;
  12723. },{}],32:[function(_dereq_,module,exports){
  12724. // (c) Copyright 2016, Sean Connelly (@voidqk), http://syntheti.cc
  12725. // MIT License
  12726. // Project Home: https://github.com/voidqk/polybooljs
  12727. //
  12728. // filter a list of segments based on boolean operations
  12729. //
  12730. function select(segments, selection, buildLog){
  12731. var result = [];
  12732. segments.forEach(function(seg){
  12733. var index =
  12734. (seg.myFill.above ? 8 : 0) +
  12735. (seg.myFill.below ? 4 : 0) +
  12736. ((seg.otherFill && seg.otherFill.above) ? 2 : 0) +
  12737. ((seg.otherFill && seg.otherFill.below) ? 1 : 0);
  12738. if (selection[index] !== 0){
  12739. // copy the segment to the results, while also calculating the fill status
  12740. result.push({
  12741. id: buildLog ? buildLog.segmentId() : -1,
  12742. start: seg.start,
  12743. end: seg.end,
  12744. myFill: {
  12745. above: selection[index] === 1, // 1 if filled above
  12746. below: selection[index] === 2 // 2 if filled below
  12747. },
  12748. otherFill: null
  12749. });
  12750. }
  12751. });
  12752. if (buildLog)
  12753. buildLog.selected(result);
  12754. return result;
  12755. }
  12756. var SegmentSelector = {
  12757. union: function(segments, buildLog){ // primary | secondary
  12758. // above1 below1 above2 below2 Keep? Value
  12759. // 0 0 0 0 => no 0
  12760. // 0 0 0 1 => yes filled below 2
  12761. // 0 0 1 0 => yes filled above 1
  12762. // 0 0 1 1 => no 0
  12763. // 0 1 0 0 => yes filled below 2
  12764. // 0 1 0 1 => yes filled below 2
  12765. // 0 1 1 0 => no 0
  12766. // 0 1 1 1 => no 0
  12767. // 1 0 0 0 => yes filled above 1
  12768. // 1 0 0 1 => no 0
  12769. // 1 0 1 0 => yes filled above 1
  12770. // 1 0 1 1 => no 0
  12771. // 1 1 0 0 => no 0
  12772. // 1 1 0 1 => no 0
  12773. // 1 1 1 0 => no 0
  12774. // 1 1 1 1 => no 0
  12775. return select(segments, [
  12776. 0, 2, 1, 0,
  12777. 2, 2, 0, 0,
  12778. 1, 0, 1, 0,
  12779. 0, 0, 0, 0
  12780. ], buildLog);
  12781. },
  12782. intersect: function(segments, buildLog){ // primary & secondary
  12783. // above1 below1 above2 below2 Keep? Value
  12784. // 0 0 0 0 => no 0
  12785. // 0 0 0 1 => no 0
  12786. // 0 0 1 0 => no 0
  12787. // 0 0 1 1 => no 0
  12788. // 0 1 0 0 => no 0
  12789. // 0 1 0 1 => yes filled below 2
  12790. // 0 1 1 0 => no 0
  12791. // 0 1 1 1 => yes filled below 2
  12792. // 1 0 0 0 => no 0
  12793. // 1 0 0 1 => no 0
  12794. // 1 0 1 0 => yes filled above 1
  12795. // 1 0 1 1 => yes filled above 1
  12796. // 1 1 0 0 => no 0
  12797. // 1 1 0 1 => yes filled below 2
  12798. // 1 1 1 0 => yes filled above 1
  12799. // 1 1 1 1 => no 0
  12800. return select(segments, [
  12801. 0, 0, 0, 0,
  12802. 0, 2, 0, 2,
  12803. 0, 0, 1, 1,
  12804. 0, 2, 1, 0
  12805. ], buildLog);
  12806. },
  12807. difference: function(segments, buildLog){ // primary - secondary
  12808. // above1 below1 above2 below2 Keep? Value
  12809. // 0 0 0 0 => no 0
  12810. // 0 0 0 1 => no 0
  12811. // 0 0 1 0 => no 0
  12812. // 0 0 1 1 => no 0
  12813. // 0 1 0 0 => yes filled below 2
  12814. // 0 1 0 1 => no 0
  12815. // 0 1 1 0 => yes filled below 2
  12816. // 0 1 1 1 => no 0
  12817. // 1 0 0 0 => yes filled above 1
  12818. // 1 0 0 1 => yes filled above 1
  12819. // 1 0 1 0 => no 0
  12820. // 1 0 1 1 => no 0
  12821. // 1 1 0 0 => no 0
  12822. // 1 1 0 1 => yes filled above 1
  12823. // 1 1 1 0 => yes filled below 2
  12824. // 1 1 1 1 => no 0
  12825. return select(segments, [
  12826. 0, 0, 0, 0,
  12827. 2, 0, 2, 0,
  12828. 1, 1, 0, 0,
  12829. 0, 1, 2, 0
  12830. ], buildLog);
  12831. },
  12832. differenceRev: function(segments, buildLog){ // secondary - primary
  12833. // above1 below1 above2 below2 Keep? Value
  12834. // 0 0 0 0 => no 0
  12835. // 0 0 0 1 => yes filled below 2
  12836. // 0 0 1 0 => yes filled above 1
  12837. // 0 0 1 1 => no 0
  12838. // 0 1 0 0 => no 0
  12839. // 0 1 0 1 => no 0
  12840. // 0 1 1 0 => yes filled above 1
  12841. // 0 1 1 1 => yes filled above 1
  12842. // 1 0 0 0 => no 0
  12843. // 1 0 0 1 => yes filled below 2
  12844. // 1 0 1 0 => no 0
  12845. // 1 0 1 1 => yes filled below 2
  12846. // 1 1 0 0 => no 0
  12847. // 1 1 0 1 => no 0
  12848. // 1 1 1 0 => no 0
  12849. // 1 1 1 1 => no 0
  12850. return select(segments, [
  12851. 0, 2, 1, 0,
  12852. 0, 0, 1, 1,
  12853. 0, 2, 0, 2,
  12854. 0, 0, 0, 0
  12855. ], buildLog);
  12856. },
  12857. xor: function(segments, buildLog){ // primary ^ secondary
  12858. // above1 below1 above2 below2 Keep? Value
  12859. // 0 0 0 0 => no 0
  12860. // 0 0 0 1 => yes filled below 2
  12861. // 0 0 1 0 => yes filled above 1
  12862. // 0 0 1 1 => no 0
  12863. // 0 1 0 0 => yes filled below 2
  12864. // 0 1 0 1 => no 0
  12865. // 0 1 1 0 => no 0
  12866. // 0 1 1 1 => yes filled above 1
  12867. // 1 0 0 0 => yes filled above 1
  12868. // 1 0 0 1 => no 0
  12869. // 1 0 1 0 => no 0
  12870. // 1 0 1 1 => yes filled below 2
  12871. // 1 1 0 0 => no 0
  12872. // 1 1 0 1 => yes filled above 1
  12873. // 1 1 1 0 => yes filled below 2
  12874. // 1 1 1 1 => no 0
  12875. return select(segments, [
  12876. 0, 2, 1, 0,
  12877. 2, 0, 0, 1,
  12878. 1, 0, 0, 2,
  12879. 0, 1, 2, 0
  12880. ], buildLog);
  12881. }
  12882. };
  12883. module.exports = SegmentSelector;
  12884. },{}],33:[function(_dereq_,module,exports){
  12885. // shim for using process in browser
  12886. var process = module.exports = {};
  12887. // cached from whatever global is present so that test runners that stub it
  12888. // don't break things. But we need to wrap it in a try catch in case it is
  12889. // wrapped in strict mode code which doesn't define any globals. It's inside a
  12890. // function because try/catches deoptimize in certain engines.
  12891. var cachedSetTimeout;
  12892. var cachedClearTimeout;
  12893. function defaultSetTimout() {
  12894. throw new Error('setTimeout has not been defined');
  12895. }
  12896. function defaultClearTimeout () {
  12897. throw new Error('clearTimeout has not been defined');
  12898. }
  12899. (function () {
  12900. try {
  12901. if (typeof setTimeout === 'function') {
  12902. cachedSetTimeout = setTimeout;
  12903. } else {
  12904. cachedSetTimeout = defaultSetTimout;
  12905. }
  12906. } catch (e) {
  12907. cachedSetTimeout = defaultSetTimout;
  12908. }
  12909. try {
  12910. if (typeof clearTimeout === 'function') {
  12911. cachedClearTimeout = clearTimeout;
  12912. } else {
  12913. cachedClearTimeout = defaultClearTimeout;
  12914. }
  12915. } catch (e) {
  12916. cachedClearTimeout = defaultClearTimeout;
  12917. }
  12918. } ())
  12919. function runTimeout(fun) {
  12920. if (cachedSetTimeout === setTimeout) {
  12921. //normal enviroments in sane situations
  12922. return setTimeout(fun, 0);
  12923. }
  12924. // if setTimeout wasn't available but was latter defined
  12925. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  12926. cachedSetTimeout = setTimeout;
  12927. return setTimeout(fun, 0);
  12928. }
  12929. try {
  12930. // when when somebody has screwed with setTimeout but no I.E. maddness
  12931. return cachedSetTimeout(fun, 0);
  12932. } catch(e){
  12933. try {
  12934. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  12935. return cachedSetTimeout.call(null, fun, 0);
  12936. } catch(e){
  12937. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  12938. return cachedSetTimeout.call(this, fun, 0);
  12939. }
  12940. }
  12941. }
  12942. function runClearTimeout(marker) {
  12943. if (cachedClearTimeout === clearTimeout) {
  12944. //normal enviroments in sane situations
  12945. return clearTimeout(marker);
  12946. }
  12947. // if clearTimeout wasn't available but was latter defined
  12948. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  12949. cachedClearTimeout = clearTimeout;
  12950. return clearTimeout(marker);
  12951. }
  12952. try {
  12953. // when when somebody has screwed with setTimeout but no I.E. maddness
  12954. return cachedClearTimeout(marker);
  12955. } catch (e){
  12956. try {
  12957. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  12958. return cachedClearTimeout.call(null, marker);
  12959. } catch (e){
  12960. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  12961. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  12962. return cachedClearTimeout.call(this, marker);
  12963. }
  12964. }
  12965. }
  12966. var queue = [];
  12967. var draining = false;
  12968. var currentQueue;
  12969. var queueIndex = -1;
  12970. function cleanUpNextTick() {
  12971. if (!draining || !currentQueue) {
  12972. return;
  12973. }
  12974. draining = false;
  12975. if (currentQueue.length) {
  12976. queue = currentQueue.concat(queue);
  12977. } else {
  12978. queueIndex = -1;
  12979. }
  12980. if (queue.length) {
  12981. drainQueue();
  12982. }
  12983. }
  12984. function drainQueue() {
  12985. if (draining) {
  12986. return;
  12987. }
  12988. var timeout = runTimeout(cleanUpNextTick);
  12989. draining = true;
  12990. var len = queue.length;
  12991. while(len) {
  12992. currentQueue = queue;
  12993. queue = [];
  12994. while (++queueIndex < len) {
  12995. if (currentQueue) {
  12996. currentQueue[queueIndex].run();
  12997. }
  12998. }
  12999. queueIndex = -1;
  13000. len = queue.length;
  13001. }
  13002. currentQueue = null;
  13003. draining = false;
  13004. runClearTimeout(timeout);
  13005. }
  13006. process.nextTick = function (fun) {
  13007. var args = new Array(arguments.length - 1);
  13008. if (arguments.length > 1) {
  13009. for (var i = 1; i < arguments.length; i++) {
  13010. args[i - 1] = arguments[i];
  13011. }
  13012. }
  13013. queue.push(new Item(fun, args));
  13014. if (queue.length === 1 && !draining) {
  13015. runTimeout(drainQueue);
  13016. }
  13017. };
  13018. // v8 likes predictible objects
  13019. function Item(fun, array) {
  13020. this.fun = fun;
  13021. this.array = array;
  13022. }
  13023. Item.prototype.run = function () {
  13024. this.fun.apply(null, this.array);
  13025. };
  13026. process.title = 'browser';
  13027. process.browser = true;
  13028. process.env = {};
  13029. process.argv = [];
  13030. process.version = ''; // empty string to avoid regexp issues
  13031. process.versions = {};
  13032. function noop() {}
  13033. process.on = noop;
  13034. process.addListener = noop;
  13035. process.once = noop;
  13036. process.off = noop;
  13037. process.removeListener = noop;
  13038. process.removeAllListeners = noop;
  13039. process.emit = noop;
  13040. process.prependListener = noop;
  13041. process.prependOnceListener = noop;
  13042. process.listeners = function (name) { return [] }
  13043. process.binding = function (name) {
  13044. throw new Error('process.binding is not supported');
  13045. };
  13046. process.cwd = function () { return '/' };
  13047. process.chdir = function (dir) {
  13048. throw new Error('process.chdir is not supported');
  13049. };
  13050. process.umask = function() { return 0; };
  13051. },{}],34:[function(_dereq_,module,exports){
  13052. // TinyColor v1.4.1
  13053. // https://github.com/bgrins/TinyColor
  13054. // Brian Grinstead, MIT License
  13055. (function(Math) {
  13056. var trimLeft = /^\s+/,
  13057. trimRight = /\s+$/,
  13058. tinyCounter = 0,
  13059. mathRound = Math.round,
  13060. mathMin = Math.min,
  13061. mathMax = Math.max,
  13062. mathRandom = Math.random;
  13063. function tinycolor (color, opts) {
  13064. color = (color) ? color : '';
  13065. opts = opts || { };
  13066. // If input is already a tinycolor, return itself
  13067. if (color instanceof tinycolor) {
  13068. return color;
  13069. }
  13070. // If we are called as a function, call using new instead
  13071. if (!(this instanceof tinycolor)) {
  13072. return new tinycolor(color, opts);
  13073. }
  13074. var rgb = inputToRGB(color);
  13075. this._originalInput = color,
  13076. this._r = rgb.r,
  13077. this._g = rgb.g,
  13078. this._b = rgb.b,
  13079. this._a = rgb.a,
  13080. this._roundA = mathRound(100*this._a) / 100,
  13081. this._format = opts.format || rgb.format;
  13082. this._gradientType = opts.gradientType;
  13083. // Don't let the range of [0,255] come back in [0,1].
  13084. // Potentially lose a little bit of precision here, but will fix issues where
  13085. // .5 gets interpreted as half of the total, instead of half of 1
  13086. // If it was supposed to be 128, this was already taken care of by `inputToRgb`
  13087. if (this._r < 1) { this._r = mathRound(this._r); }
  13088. if (this._g < 1) { this._g = mathRound(this._g); }
  13089. if (this._b < 1) { this._b = mathRound(this._b); }
  13090. this._ok = rgb.ok;
  13091. this._tc_id = tinyCounter++;
  13092. }
  13093. tinycolor.prototype = {
  13094. isDark: function() {
  13095. return this.getBrightness() < 128;
  13096. },
  13097. isLight: function() {
  13098. return !this.isDark();
  13099. },
  13100. isValid: function() {
  13101. return this._ok;
  13102. },
  13103. getOriginalInput: function() {
  13104. return this._originalInput;
  13105. },
  13106. getFormat: function() {
  13107. return this._format;
  13108. },
  13109. getAlpha: function() {
  13110. return this._a;
  13111. },
  13112. getBrightness: function() {
  13113. //http://www.w3.org/TR/AERT#color-contrast
  13114. var rgb = this.toRgb();
  13115. return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000;
  13116. },
  13117. getLuminance: function() {
  13118. //http://www.w3.org/TR/2008/REC-WCAG20-20081211/#relativeluminancedef
  13119. var rgb = this.toRgb();
  13120. var RsRGB, GsRGB, BsRGB, R, G, B;
  13121. RsRGB = rgb.r/255;
  13122. GsRGB = rgb.g/255;
  13123. BsRGB = rgb.b/255;
  13124. if (RsRGB <= 0.03928) {R = RsRGB / 12.92;} else {R = Math.pow(((RsRGB + 0.055) / 1.055), 2.4);}
  13125. if (GsRGB <= 0.03928) {G = GsRGB / 12.92;} else {G = Math.pow(((GsRGB + 0.055) / 1.055), 2.4);}
  13126. if (BsRGB <= 0.03928) {B = BsRGB / 12.92;} else {B = Math.pow(((BsRGB + 0.055) / 1.055), 2.4);}
  13127. return (0.2126 * R) + (0.7152 * G) + (0.0722 * B);
  13128. },
  13129. setAlpha: function(value) {
  13130. this._a = boundAlpha(value);
  13131. this._roundA = mathRound(100*this._a) / 100;
  13132. return this;
  13133. },
  13134. toHsv: function() {
  13135. var hsv = rgbToHsv(this._r, this._g, this._b);
  13136. return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a };
  13137. },
  13138. toHsvString: function() {
  13139. var hsv = rgbToHsv(this._r, this._g, this._b);
  13140. var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100);
  13141. return (this._a == 1) ?
  13142. "hsv(" + h + ", " + s + "%, " + v + "%)" :
  13143. "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")";
  13144. },
  13145. toHsl: function() {
  13146. var hsl = rgbToHsl(this._r, this._g, this._b);
  13147. return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a };
  13148. },
  13149. toHslString: function() {
  13150. var hsl = rgbToHsl(this._r, this._g, this._b);
  13151. var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100);
  13152. return (this._a == 1) ?
  13153. "hsl(" + h + ", " + s + "%, " + l + "%)" :
  13154. "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")";
  13155. },
  13156. toHex: function(allow3Char) {
  13157. return rgbToHex(this._r, this._g, this._b, allow3Char);
  13158. },
  13159. toHexString: function(allow3Char) {
  13160. return '#' + this.toHex(allow3Char);
  13161. },
  13162. toHex8: function(allow4Char) {
  13163. return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char);
  13164. },
  13165. toHex8String: function(allow4Char) {
  13166. return '#' + this.toHex8(allow4Char);
  13167. },
  13168. toRgb: function() {
  13169. return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a };
  13170. },
  13171. toRgbString: function() {
  13172. return (this._a == 1) ?
  13173. "rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" :
  13174. "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")";
  13175. },
  13176. toPercentageRgb: function() {
  13177. return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a };
  13178. },
  13179. toPercentageRgbString: function() {
  13180. return (this._a == 1) ?
  13181. "rgb(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" :
  13182. "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")";
  13183. },
  13184. toName: function() {
  13185. if (this._a === 0) {
  13186. return "transparent";
  13187. }
  13188. if (this._a < 1) {
  13189. return false;
  13190. }
  13191. return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false;
  13192. },
  13193. toFilter: function(secondColor) {
  13194. var hex8String = '#' + rgbaToArgbHex(this._r, this._g, this._b, this._a);
  13195. var secondHex8String = hex8String;
  13196. var gradientType = this._gradientType ? "GradientType = 1, " : "";
  13197. if (secondColor) {
  13198. var s = tinycolor(secondColor);
  13199. secondHex8String = '#' + rgbaToArgbHex(s._r, s._g, s._b, s._a);
  13200. }
  13201. return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")";
  13202. },
  13203. toString: function(format) {
  13204. var formatSet = !!format;
  13205. format = format || this._format;
  13206. var formattedString = false;
  13207. var hasAlpha = this._a < 1 && this._a >= 0;
  13208. var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "hex4" || format === "hex8" || format === "name");
  13209. if (needsAlphaFormat) {
  13210. // Special case for "transparent", all other non-alpha formats
  13211. // will return rgba when there is transparency.
  13212. if (format === "name" && this._a === 0) {
  13213. return this.toName();
  13214. }
  13215. return this.toRgbString();
  13216. }
  13217. if (format === "rgb") {
  13218. formattedString = this.toRgbString();
  13219. }
  13220. if (format === "prgb") {
  13221. formattedString = this.toPercentageRgbString();
  13222. }
  13223. if (format === "hex" || format === "hex6") {
  13224. formattedString = this.toHexString();
  13225. }
  13226. if (format === "hex3") {
  13227. formattedString = this.toHexString(true);
  13228. }
  13229. if (format === "hex4") {
  13230. formattedString = this.toHex8String(true);
  13231. }
  13232. if (format === "hex8") {
  13233. formattedString = this.toHex8String();
  13234. }
  13235. if (format === "name") {
  13236. formattedString = this.toName();
  13237. }
  13238. if (format === "hsl") {
  13239. formattedString = this.toHslString();
  13240. }
  13241. if (format === "hsv") {
  13242. formattedString = this.toHsvString();
  13243. }
  13244. return formattedString || this.toHexString();
  13245. },
  13246. clone: function() {
  13247. return tinycolor(this.toString());
  13248. },
  13249. _applyModification: function(fn, args) {
  13250. var color = fn.apply(null, [this].concat([].slice.call(args)));
  13251. this._r = color._r;
  13252. this._g = color._g;
  13253. this._b = color._b;
  13254. this.setAlpha(color._a);
  13255. return this;
  13256. },
  13257. lighten: function() {
  13258. return this._applyModification(lighten, arguments);
  13259. },
  13260. brighten: function() {
  13261. return this._applyModification(brighten, arguments);
  13262. },
  13263. darken: function() {
  13264. return this._applyModification(darken, arguments);
  13265. },
  13266. desaturate: function() {
  13267. return this._applyModification(desaturate, arguments);
  13268. },
  13269. saturate: function() {
  13270. return this._applyModification(saturate, arguments);
  13271. },
  13272. greyscale: function() {
  13273. return this._applyModification(greyscale, arguments);
  13274. },
  13275. spin: function() {
  13276. return this._applyModification(spin, arguments);
  13277. },
  13278. _applyCombination: function(fn, args) {
  13279. return fn.apply(null, [this].concat([].slice.call(args)));
  13280. },
  13281. analogous: function() {
  13282. return this._applyCombination(analogous, arguments);
  13283. },
  13284. complement: function() {
  13285. return this._applyCombination(complement, arguments);
  13286. },
  13287. monochromatic: function() {
  13288. return this._applyCombination(monochromatic, arguments);
  13289. },
  13290. splitcomplement: function() {
  13291. return this._applyCombination(splitcomplement, arguments);
  13292. },
  13293. triad: function() {
  13294. return this._applyCombination(triad, arguments);
  13295. },
  13296. tetrad: function() {
  13297. return this._applyCombination(tetrad, arguments);
  13298. }
  13299. };
  13300. // If input is an object, force 1 into "1.0" to handle ratios properly
  13301. // String input requires "1.0" as input, so 1 will be treated as 1
  13302. tinycolor.fromRatio = function(color, opts) {
  13303. if (typeof color == "object") {
  13304. var newColor = {};
  13305. for (var i in color) {
  13306. if (color.hasOwnProperty(i)) {
  13307. if (i === "a") {
  13308. newColor[i] = color[i];
  13309. }
  13310. else {
  13311. newColor[i] = convertToPercentage(color[i]);
  13312. }
  13313. }
  13314. }
  13315. color = newColor;
  13316. }
  13317. return tinycolor(color, opts);
  13318. };
  13319. // Given a string or object, convert that input to RGB
  13320. // Possible string inputs:
  13321. //
  13322. // "red"
  13323. // "#f00" or "f00"
  13324. // "#ff0000" or "ff0000"
  13325. // "#ff000000" or "ff000000"
  13326. // "rgb 255 0 0" or "rgb (255, 0, 0)"
  13327. // "rgb 1.0 0 0" or "rgb (1, 0, 0)"
  13328. // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1"
  13329. // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1"
  13330. // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%"
  13331. // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1"
  13332. // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%"
  13333. //
  13334. function inputToRGB(color) {
  13335. var rgb = { r: 0, g: 0, b: 0 };
  13336. var a = 1;
  13337. var s = null;
  13338. var v = null;
  13339. var l = null;
  13340. var ok = false;
  13341. var format = false;
  13342. if (typeof color == "string") {
  13343. color = stringInputToObject(color);
  13344. }
  13345. if (typeof color == "object") {
  13346. if (isValidCSSUnit(color.r) && isValidCSSUnit(color.g) && isValidCSSUnit(color.b)) {
  13347. rgb = rgbToRgb(color.r, color.g, color.b);
  13348. ok = true;
  13349. format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb";
  13350. }
  13351. else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.v)) {
  13352. s = convertToPercentage(color.s);
  13353. v = convertToPercentage(color.v);
  13354. rgb = hsvToRgb(color.h, s, v);
  13355. ok = true;
  13356. format = "hsv";
  13357. }
  13358. else if (isValidCSSUnit(color.h) && isValidCSSUnit(color.s) && isValidCSSUnit(color.l)) {
  13359. s = convertToPercentage(color.s);
  13360. l = convertToPercentage(color.l);
  13361. rgb = hslToRgb(color.h, s, l);
  13362. ok = true;
  13363. format = "hsl";
  13364. }
  13365. if (color.hasOwnProperty("a")) {
  13366. a = color.a;
  13367. }
  13368. }
  13369. a = boundAlpha(a);
  13370. return {
  13371. ok: ok,
  13372. format: color.format || format,
  13373. r: mathMin(255, mathMax(rgb.r, 0)),
  13374. g: mathMin(255, mathMax(rgb.g, 0)),
  13375. b: mathMin(255, mathMax(rgb.b, 0)),
  13376. a: a
  13377. };
  13378. }
  13379. // Conversion Functions
  13380. // --------------------
  13381. // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from:
  13382. // <http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript>
  13383. // `rgbToRgb`
  13384. // Handle bounds / percentage checking to conform to CSS color spec
  13385. // <http://www.w3.org/TR/css3-color/>
  13386. // *Assumes:* r, g, b in [0, 255] or [0, 1]
  13387. // *Returns:* { r, g, b } in [0, 255]
  13388. function rgbToRgb(r, g, b){
  13389. return {
  13390. r: bound01(r, 255) * 255,
  13391. g: bound01(g, 255) * 255,
  13392. b: bound01(b, 255) * 255
  13393. };
  13394. }
  13395. // `rgbToHsl`
  13396. // Converts an RGB color value to HSL.
  13397. // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1]
  13398. // *Returns:* { h, s, l } in [0,1]
  13399. function rgbToHsl(r, g, b) {
  13400. r = bound01(r, 255);
  13401. g = bound01(g, 255);
  13402. b = bound01(b, 255);
  13403. var max = mathMax(r, g, b), min = mathMin(r, g, b);
  13404. var h, s, l = (max + min) / 2;
  13405. if(max == min) {
  13406. h = s = 0; // achromatic
  13407. }
  13408. else {
  13409. var d = max - min;
  13410. s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
  13411. switch(max) {
  13412. case r: h = (g - b) / d + (g < b ? 6 : 0); break;
  13413. case g: h = (b - r) / d + 2; break;
  13414. case b: h = (r - g) / d + 4; break;
  13415. }
  13416. h /= 6;
  13417. }
  13418. return { h: h, s: s, l: l };
  13419. }
  13420. // `hslToRgb`
  13421. // Converts an HSL color value to RGB.
  13422. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100]
  13423. // *Returns:* { r, g, b } in the set [0, 255]
  13424. function hslToRgb(h, s, l) {
  13425. var r, g, b;
  13426. h = bound01(h, 360);
  13427. s = bound01(s, 100);
  13428. l = bound01(l, 100);
  13429. function hue2rgb(p, q, t) {
  13430. if(t < 0) t += 1;
  13431. if(t > 1) t -= 1;
  13432. if(t < 1/6) return p + (q - p) * 6 * t;
  13433. if(t < 1/2) return q;
  13434. if(t < 2/3) return p + (q - p) * (2/3 - t) * 6;
  13435. return p;
  13436. }
  13437. if(s === 0) {
  13438. r = g = b = l; // achromatic
  13439. }
  13440. else {
  13441. var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
  13442. var p = 2 * l - q;
  13443. r = hue2rgb(p, q, h + 1/3);
  13444. g = hue2rgb(p, q, h);
  13445. b = hue2rgb(p, q, h - 1/3);
  13446. }
  13447. return { r: r * 255, g: g * 255, b: b * 255 };
  13448. }
  13449. // `rgbToHsv`
  13450. // Converts an RGB color value to HSV
  13451. // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1]
  13452. // *Returns:* { h, s, v } in [0,1]
  13453. function rgbToHsv(r, g, b) {
  13454. r = bound01(r, 255);
  13455. g = bound01(g, 255);
  13456. b = bound01(b, 255);
  13457. var max = mathMax(r, g, b), min = mathMin(r, g, b);
  13458. var h, s, v = max;
  13459. var d = max - min;
  13460. s = max === 0 ? 0 : d / max;
  13461. if(max == min) {
  13462. h = 0; // achromatic
  13463. }
  13464. else {
  13465. switch(max) {
  13466. case r: h = (g - b) / d + (g < b ? 6 : 0); break;
  13467. case g: h = (b - r) / d + 2; break;
  13468. case b: h = (r - g) / d + 4; break;
  13469. }
  13470. h /= 6;
  13471. }
  13472. return { h: h, s: s, v: v };
  13473. }
  13474. // `hsvToRgb`
  13475. // Converts an HSV color value to RGB.
  13476. // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100]
  13477. // *Returns:* { r, g, b } in the set [0, 255]
  13478. function hsvToRgb(h, s, v) {
  13479. h = bound01(h, 360) * 6;
  13480. s = bound01(s, 100);
  13481. v = bound01(v, 100);
  13482. var i = Math.floor(h),
  13483. f = h - i,
  13484. p = v * (1 - s),
  13485. q = v * (1 - f * s),
  13486. t = v * (1 - (1 - f) * s),
  13487. mod = i % 6,
  13488. r = [v, q, p, p, t, v][mod],
  13489. g = [t, v, v, q, p, p][mod],
  13490. b = [p, p, t, v, v, q][mod];
  13491. return { r: r * 255, g: g * 255, b: b * 255 };
  13492. }
  13493. // `rgbToHex`
  13494. // Converts an RGB color to hex
  13495. // Assumes r, g, and b are contained in the set [0, 255]
  13496. // Returns a 3 or 6 character hex
  13497. function rgbToHex(r, g, b, allow3Char) {
  13498. var hex = [
  13499. pad2(mathRound(r).toString(16)),
  13500. pad2(mathRound(g).toString(16)),
  13501. pad2(mathRound(b).toString(16))
  13502. ];
  13503. // Return a 3 character hex if possible
  13504. if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) {
  13505. return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0);
  13506. }
  13507. return hex.join("");
  13508. }
  13509. // `rgbaToHex`
  13510. // Converts an RGBA color plus alpha transparency to hex
  13511. // Assumes r, g, b are contained in the set [0, 255] and
  13512. // a in [0, 1]. Returns a 4 or 8 character rgba hex
  13513. function rgbaToHex(r, g, b, a, allow4Char) {
  13514. var hex = [
  13515. pad2(mathRound(r).toString(16)),
  13516. pad2(mathRound(g).toString(16)),
  13517. pad2(mathRound(b).toString(16)),
  13518. pad2(convertDecimalToHex(a))
  13519. ];
  13520. // Return a 4 character hex if possible
  13521. if (allow4Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1) && hex[3].charAt(0) == hex[3].charAt(1)) {
  13522. return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0) + hex[3].charAt(0);
  13523. }
  13524. return hex.join("");
  13525. }
  13526. // `rgbaToArgbHex`
  13527. // Converts an RGBA color to an ARGB Hex8 string
  13528. // Rarely used, but required for "toFilter()"
  13529. function rgbaToArgbHex(r, g, b, a) {
  13530. var hex = [
  13531. pad2(convertDecimalToHex(a)),
  13532. pad2(mathRound(r).toString(16)),
  13533. pad2(mathRound(g).toString(16)),
  13534. pad2(mathRound(b).toString(16))
  13535. ];
  13536. return hex.join("");
  13537. }
  13538. // `equals`
  13539. // Can be called with any tinycolor input
  13540. tinycolor.equals = function (color1, color2) {
  13541. if (!color1 || !color2) { return false; }
  13542. return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString();
  13543. };
  13544. tinycolor.random = function() {
  13545. return tinycolor.fromRatio({
  13546. r: mathRandom(),
  13547. g: mathRandom(),
  13548. b: mathRandom()
  13549. });
  13550. };
  13551. // Modification Functions
  13552. // ----------------------
  13553. // Thanks to less.js for some of the basics here
  13554. // <https://github.com/cloudhead/less.js/blob/master/lib/less/functions.js>
  13555. function desaturate(color, amount) {
  13556. amount = (amount === 0) ? 0 : (amount || 10);
  13557. var hsl = tinycolor(color).toHsl();
  13558. hsl.s -= amount / 100;
  13559. hsl.s = clamp01(hsl.s);
  13560. return tinycolor(hsl);
  13561. }
  13562. function saturate(color, amount) {
  13563. amount = (amount === 0) ? 0 : (amount || 10);
  13564. var hsl = tinycolor(color).toHsl();
  13565. hsl.s += amount / 100;
  13566. hsl.s = clamp01(hsl.s);
  13567. return tinycolor(hsl);
  13568. }
  13569. function greyscale(color) {
  13570. return tinycolor(color).desaturate(100);
  13571. }
  13572. function lighten (color, amount) {
  13573. amount = (amount === 0) ? 0 : (amount || 10);
  13574. var hsl = tinycolor(color).toHsl();
  13575. hsl.l += amount / 100;
  13576. hsl.l = clamp01(hsl.l);
  13577. return tinycolor(hsl);
  13578. }
  13579. function brighten(color, amount) {
  13580. amount = (amount === 0) ? 0 : (amount || 10);
  13581. var rgb = tinycolor(color).toRgb();
  13582. rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100))));
  13583. rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100))));
  13584. rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100))));
  13585. return tinycolor(rgb);
  13586. }
  13587. function darken (color, amount) {
  13588. amount = (amount === 0) ? 0 : (amount || 10);
  13589. var hsl = tinycolor(color).toHsl();
  13590. hsl.l -= amount / 100;
  13591. hsl.l = clamp01(hsl.l);
  13592. return tinycolor(hsl);
  13593. }
  13594. // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue.
  13595. // Values outside of this range will be wrapped into this range.
  13596. function spin(color, amount) {
  13597. var hsl = tinycolor(color).toHsl();
  13598. var hue = (hsl.h + amount) % 360;
  13599. hsl.h = hue < 0 ? 360 + hue : hue;
  13600. return tinycolor(hsl);
  13601. }
  13602. // Combination Functions
  13603. // ---------------------
  13604. // Thanks to jQuery xColor for some of the ideas behind these
  13605. // <https://github.com/infusion/jQuery-xcolor/blob/master/jquery.xcolor.js>
  13606. function complement(color) {
  13607. var hsl = tinycolor(color).toHsl();
  13608. hsl.h = (hsl.h + 180) % 360;
  13609. return tinycolor(hsl);
  13610. }
  13611. function triad(color) {
  13612. var hsl = tinycolor(color).toHsl();
  13613. var h = hsl.h;
  13614. return [
  13615. tinycolor(color),
  13616. tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }),
  13617. tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l })
  13618. ];
  13619. }
  13620. function tetrad(color) {
  13621. var hsl = tinycolor(color).toHsl();
  13622. var h = hsl.h;
  13623. return [
  13624. tinycolor(color),
  13625. tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }),
  13626. tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }),
  13627. tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l })
  13628. ];
  13629. }
  13630. function splitcomplement(color) {
  13631. var hsl = tinycolor(color).toHsl();
  13632. var h = hsl.h;
  13633. return [
  13634. tinycolor(color),
  13635. tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}),
  13636. tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l})
  13637. ];
  13638. }
  13639. function analogous(color, results, slices) {
  13640. results = results || 6;
  13641. slices = slices || 30;
  13642. var hsl = tinycolor(color).toHsl();
  13643. var part = 360 / slices;
  13644. var ret = [tinycolor(color)];
  13645. for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) {
  13646. hsl.h = (hsl.h + part) % 360;
  13647. ret.push(tinycolor(hsl));
  13648. }
  13649. return ret;
  13650. }
  13651. function monochromatic(color, results) {
  13652. results = results || 6;
  13653. var hsv = tinycolor(color).toHsv();
  13654. var h = hsv.h, s = hsv.s, v = hsv.v;
  13655. var ret = [];
  13656. var modification = 1 / results;
  13657. while (results--) {
  13658. ret.push(tinycolor({ h: h, s: s, v: v}));
  13659. v = (v + modification) % 1;
  13660. }
  13661. return ret;
  13662. }
  13663. // Utility Functions
  13664. // ---------------------
  13665. tinycolor.mix = function(color1, color2, amount) {
  13666. amount = (amount === 0) ? 0 : (amount || 50);
  13667. var rgb1 = tinycolor(color1).toRgb();
  13668. var rgb2 = tinycolor(color2).toRgb();
  13669. var p = amount / 100;
  13670. var rgba = {
  13671. r: ((rgb2.r - rgb1.r) * p) + rgb1.r,
  13672. g: ((rgb2.g - rgb1.g) * p) + rgb1.g,
  13673. b: ((rgb2.b - rgb1.b) * p) + rgb1.b,
  13674. a: ((rgb2.a - rgb1.a) * p) + rgb1.a
  13675. };
  13676. return tinycolor(rgba);
  13677. };
  13678. // Readability Functions
  13679. // ---------------------
  13680. // <http://www.w3.org/TR/2008/REC-WCAG20-20081211/#contrast-ratiodef (WCAG Version 2)
  13681. // `contrast`
  13682. // Analyze the 2 colors and returns the color contrast defined by (WCAG Version 2)
  13683. tinycolor.readability = function(color1, color2) {
  13684. var c1 = tinycolor(color1);
  13685. var c2 = tinycolor(color2);
  13686. return (Math.max(c1.getLuminance(),c2.getLuminance())+0.05) / (Math.min(c1.getLuminance(),c2.getLuminance())+0.05);
  13687. };
  13688. // `isReadable`
  13689. // Ensure that foreground and background color combinations meet WCAG2 guidelines.
  13690. // The third argument is an optional Object.
  13691. // the 'level' property states 'AA' or 'AAA' - if missing or invalid, it defaults to 'AA';
  13692. // the 'size' property states 'large' or 'small' - if missing or invalid, it defaults to 'small'.
  13693. // If the entire object is absent, isReadable defaults to {level:"AA",size:"small"}.
  13694. // *Example*
  13695. // tinycolor.isReadable("#000", "#111") => false
  13696. // tinycolor.isReadable("#000", "#111",{level:"AA",size:"large"}) => false
  13697. tinycolor.isReadable = function(color1, color2, wcag2) {
  13698. var readability = tinycolor.readability(color1, color2);
  13699. var wcag2Parms, out;
  13700. out = false;
  13701. wcag2Parms = validateWCAG2Parms(wcag2);
  13702. switch (wcag2Parms.level + wcag2Parms.size) {
  13703. case "AAsmall":
  13704. case "AAAlarge":
  13705. out = readability >= 4.5;
  13706. break;
  13707. case "AAlarge":
  13708. out = readability >= 3;
  13709. break;
  13710. case "AAAsmall":
  13711. out = readability >= 7;
  13712. break;
  13713. }
  13714. return out;
  13715. };
  13716. // `mostReadable`
  13717. // Given a base color and a list of possible foreground or background
  13718. // colors for that base, returns the most readable color.
  13719. // Optionally returns Black or White if the most readable color is unreadable.
  13720. // *Example*
  13721. // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:false}).toHexString(); // "#112255"
  13722. // tinycolor.mostReadable(tinycolor.mostReadable("#123", ["#124", "#125"],{includeFallbackColors:true}).toHexString(); // "#ffffff"
  13723. // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"large"}).toHexString(); // "#faf3f3"
  13724. // tinycolor.mostReadable("#a8015a", ["#faf3f3"],{includeFallbackColors:true,level:"AAA",size:"small"}).toHexString(); // "#ffffff"
  13725. tinycolor.mostReadable = function(baseColor, colorList, args) {
  13726. var bestColor = null;
  13727. var bestScore = 0;
  13728. var readability;
  13729. var includeFallbackColors, level, size ;
  13730. args = args || {};
  13731. includeFallbackColors = args.includeFallbackColors ;
  13732. level = args.level;
  13733. size = args.size;
  13734. for (var i= 0; i < colorList.length ; i++) {
  13735. readability = tinycolor.readability(baseColor, colorList[i]);
  13736. if (readability > bestScore) {
  13737. bestScore = readability;
  13738. bestColor = tinycolor(colorList[i]);
  13739. }
  13740. }
  13741. if (tinycolor.isReadable(baseColor, bestColor, {"level":level,"size":size}) || !includeFallbackColors) {
  13742. return bestColor;
  13743. }
  13744. else {
  13745. args.includeFallbackColors=false;
  13746. return tinycolor.mostReadable(baseColor,["#fff", "#000"],args);
  13747. }
  13748. };
  13749. // Big List of Colors
  13750. // ------------------
  13751. // <http://www.w3.org/TR/css3-color/#svg-color>
  13752. var names = tinycolor.names = {
  13753. aliceblue: "f0f8ff",
  13754. antiquewhite: "faebd7",
  13755. aqua: "0ff",
  13756. aquamarine: "7fffd4",
  13757. azure: "f0ffff",
  13758. beige: "f5f5dc",
  13759. bisque: "ffe4c4",
  13760. black: "000",
  13761. blanchedalmond: "ffebcd",
  13762. blue: "00f",
  13763. blueviolet: "8a2be2",
  13764. brown: "a52a2a",
  13765. burlywood: "deb887",
  13766. burntsienna: "ea7e5d",
  13767. cadetblue: "5f9ea0",
  13768. chartreuse: "7fff00",
  13769. chocolate: "d2691e",
  13770. coral: "ff7f50",
  13771. cornflowerblue: "6495ed",
  13772. cornsilk: "fff8dc",
  13773. crimson: "dc143c",
  13774. cyan: "0ff",
  13775. darkblue: "00008b",
  13776. darkcyan: "008b8b",
  13777. darkgoldenrod: "b8860b",
  13778. darkgray: "a9a9a9",
  13779. darkgreen: "006400",
  13780. darkgrey: "a9a9a9",
  13781. darkkhaki: "bdb76b",
  13782. darkmagenta: "8b008b",
  13783. darkolivegreen: "556b2f",
  13784. darkorange: "ff8c00",
  13785. darkorchid: "9932cc",
  13786. darkred: "8b0000",
  13787. darksalmon: "e9967a",
  13788. darkseagreen: "8fbc8f",
  13789. darkslateblue: "483d8b",
  13790. darkslategray: "2f4f4f",
  13791. darkslategrey: "2f4f4f",
  13792. darkturquoise: "00ced1",
  13793. darkviolet: "9400d3",
  13794. deeppink: "ff1493",
  13795. deepskyblue: "00bfff",
  13796. dimgray: "696969",
  13797. dimgrey: "696969",
  13798. dodgerblue: "1e90ff",
  13799. firebrick: "b22222",
  13800. floralwhite: "fffaf0",
  13801. forestgreen: "228b22",
  13802. fuchsia: "f0f",
  13803. gainsboro: "dcdcdc",
  13804. ghostwhite: "f8f8ff",
  13805. gold: "ffd700",
  13806. goldenrod: "daa520",
  13807. gray: "808080",
  13808. green: "008000",
  13809. greenyellow: "adff2f",
  13810. grey: "808080",
  13811. honeydew: "f0fff0",
  13812. hotpink: "ff69b4",
  13813. indianred: "cd5c5c",
  13814. indigo: "4b0082",
  13815. ivory: "fffff0",
  13816. khaki: "f0e68c",
  13817. lavender: "e6e6fa",
  13818. lavenderblush: "fff0f5",
  13819. lawngreen: "7cfc00",
  13820. lemonchiffon: "fffacd",
  13821. lightblue: "add8e6",
  13822. lightcoral: "f08080",
  13823. lightcyan: "e0ffff",
  13824. lightgoldenrodyellow: "fafad2",
  13825. lightgray: "d3d3d3",
  13826. lightgreen: "90ee90",
  13827. lightgrey: "d3d3d3",
  13828. lightpink: "ffb6c1",
  13829. lightsalmon: "ffa07a",
  13830. lightseagreen: "20b2aa",
  13831. lightskyblue: "87cefa",
  13832. lightslategray: "789",
  13833. lightslategrey: "789",
  13834. lightsteelblue: "b0c4de",
  13835. lightyellow: "ffffe0",
  13836. lime: "0f0",
  13837. limegreen: "32cd32",
  13838. linen: "faf0e6",
  13839. magenta: "f0f",
  13840. maroon: "800000",
  13841. mediumaquamarine: "66cdaa",
  13842. mediumblue: "0000cd",
  13843. mediumorchid: "ba55d3",
  13844. mediumpurple: "9370db",
  13845. mediumseagreen: "3cb371",
  13846. mediumslateblue: "7b68ee",
  13847. mediumspringgreen: "00fa9a",
  13848. mediumturquoise: "48d1cc",
  13849. mediumvioletred: "c71585",
  13850. midnightblue: "191970",
  13851. mintcream: "f5fffa",
  13852. mistyrose: "ffe4e1",
  13853. moccasin: "ffe4b5",
  13854. navajowhite: "ffdead",
  13855. navy: "000080",
  13856. oldlace: "fdf5e6",
  13857. olive: "808000",
  13858. olivedrab: "6b8e23",
  13859. orange: "ffa500",
  13860. orangered: "ff4500",
  13861. orchid: "da70d6",
  13862. palegoldenrod: "eee8aa",
  13863. palegreen: "98fb98",
  13864. paleturquoise: "afeeee",
  13865. palevioletred: "db7093",
  13866. papayawhip: "ffefd5",
  13867. peachpuff: "ffdab9",
  13868. peru: "cd853f",
  13869. pink: "ffc0cb",
  13870. plum: "dda0dd",
  13871. powderblue: "b0e0e6",
  13872. purple: "800080",
  13873. rebeccapurple: "663399",
  13874. red: "f00",
  13875. rosybrown: "bc8f8f",
  13876. royalblue: "4169e1",
  13877. saddlebrown: "8b4513",
  13878. salmon: "fa8072",
  13879. sandybrown: "f4a460",
  13880. seagreen: "2e8b57",
  13881. seashell: "fff5ee",
  13882. sienna: "a0522d",
  13883. silver: "c0c0c0",
  13884. skyblue: "87ceeb",
  13885. slateblue: "6a5acd",
  13886. slategray: "708090",
  13887. slategrey: "708090",
  13888. snow: "fffafa",
  13889. springgreen: "00ff7f",
  13890. steelblue: "4682b4",
  13891. tan: "d2b48c",
  13892. teal: "008080",
  13893. thistle: "d8bfd8",
  13894. tomato: "ff6347",
  13895. turquoise: "40e0d0",
  13896. violet: "ee82ee",
  13897. wheat: "f5deb3",
  13898. white: "fff",
  13899. whitesmoke: "f5f5f5",
  13900. yellow: "ff0",
  13901. yellowgreen: "9acd32"
  13902. };
  13903. // Make it easy to access colors via `hexNames[hex]`
  13904. var hexNames = tinycolor.hexNames = flip(names);
  13905. // Utilities
  13906. // ---------
  13907. // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }`
  13908. function flip(o) {
  13909. var flipped = { };
  13910. for (var i in o) {
  13911. if (o.hasOwnProperty(i)) {
  13912. flipped[o[i]] = i;
  13913. }
  13914. }
  13915. return flipped;
  13916. }
  13917. // Return a valid alpha value [0,1] with all invalid values being set to 1
  13918. function boundAlpha(a) {
  13919. a = parseFloat(a);
  13920. if (isNaN(a) || a < 0 || a > 1) {
  13921. a = 1;
  13922. }
  13923. return a;
  13924. }
  13925. // Take input from [0, n] and return it as [0, 1]
  13926. function bound01(n, max) {
  13927. if (isOnePointZero(n)) { n = "100%"; }
  13928. var processPercent = isPercentage(n);
  13929. n = mathMin(max, mathMax(0, parseFloat(n)));
  13930. // Automatically convert percentage into number
  13931. if (processPercent) {
  13932. n = parseInt(n * max, 10) / 100;
  13933. }
  13934. // Handle floating point rounding errors
  13935. if ((Math.abs(n - max) < 0.000001)) {
  13936. return 1;
  13937. }
  13938. // Convert into [0, 1] range if it isn't already
  13939. return (n % max) / parseFloat(max);
  13940. }
  13941. // Force a number between 0 and 1
  13942. function clamp01(val) {
  13943. return mathMin(1, mathMax(0, val));
  13944. }
  13945. // Parse a base-16 hex value into a base-10 integer
  13946. function parseIntFromHex(val) {
  13947. return parseInt(val, 16);
  13948. }
  13949. // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1
  13950. // <http://stackoverflow.com/questions/7422072/javascript-how-to-detect-number-as-a-decimal-including-1-0>
  13951. function isOnePointZero(n) {
  13952. return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1;
  13953. }
  13954. // Check to see if string passed in is a percentage
  13955. function isPercentage(n) {
  13956. return typeof n === "string" && n.indexOf('%') != -1;
  13957. }
  13958. // Force a hex value to have 2 characters
  13959. function pad2(c) {
  13960. return c.length == 1 ? '0' + c : '' + c;
  13961. }
  13962. // Replace a decimal with it's percentage value
  13963. function convertToPercentage(n) {
  13964. if (n <= 1) {
  13965. n = (n * 100) + "%";
  13966. }
  13967. return n;
  13968. }
  13969. // Converts a decimal to a hex value
  13970. function convertDecimalToHex(d) {
  13971. return Math.round(parseFloat(d) * 255).toString(16);
  13972. }
  13973. // Converts a hex value to a decimal
  13974. function convertHexToDecimal(h) {
  13975. return (parseIntFromHex(h) / 255);
  13976. }
  13977. var matchers = (function() {
  13978. // <http://www.w3.org/TR/css3-values/#integers>
  13979. var CSS_INTEGER = "[-\\+]?\\d+%?";
  13980. // <http://www.w3.org/TR/css3-values/#number-value>
  13981. var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?";
  13982. // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome.
  13983. var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")";
  13984. // Actual matching.
  13985. // Parentheses and commas are optional, but not required.
  13986. // Whitespace can take the place of commas or opening paren
  13987. var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
  13988. var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?";
  13989. return {
  13990. CSS_UNIT: new RegExp(CSS_UNIT),
  13991. rgb: new RegExp("rgb" + PERMISSIVE_MATCH3),
  13992. rgba: new RegExp("rgba" + PERMISSIVE_MATCH4),
  13993. hsl: new RegExp("hsl" + PERMISSIVE_MATCH3),
  13994. hsla: new RegExp("hsla" + PERMISSIVE_MATCH4),
  13995. hsv: new RegExp("hsv" + PERMISSIVE_MATCH3),
  13996. hsva: new RegExp("hsva" + PERMISSIVE_MATCH4),
  13997. hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
  13998. hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/,
  13999. hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/,
  14000. hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/
  14001. };
  14002. })();
  14003. // `isValidCSSUnit`
  14004. // Take in a single string / number and check to see if it looks like a CSS unit
  14005. // (see `matchers` above for definition).
  14006. function isValidCSSUnit(color) {
  14007. return !!matchers.CSS_UNIT.exec(color);
  14008. }
  14009. // `stringInputToObject`
  14010. // Permissive string parsing. Take in a number of formats, and output an object
  14011. // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}`
  14012. function stringInputToObject(color) {
  14013. color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase();
  14014. var named = false;
  14015. if (names[color]) {
  14016. color = names[color];
  14017. named = true;
  14018. }
  14019. else if (color == 'transparent') {
  14020. return { r: 0, g: 0, b: 0, a: 0, format: "name" };
  14021. }
  14022. // Try to match string input using regular expressions.
  14023. // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360]
  14024. // Just return an object and let the conversion functions handle that.
  14025. // This way the result will be the same whether the tinycolor is initialized with string or object.
  14026. var match;
  14027. if ((match = matchers.rgb.exec(color))) {
  14028. return { r: match[1], g: match[2], b: match[3] };
  14029. }
  14030. if ((match = matchers.rgba.exec(color))) {
  14031. return { r: match[1], g: match[2], b: match[3], a: match[4] };
  14032. }
  14033. if ((match = matchers.hsl.exec(color))) {
  14034. return { h: match[1], s: match[2], l: match[3] };
  14035. }
  14036. if ((match = matchers.hsla.exec(color))) {
  14037. return { h: match[1], s: match[2], l: match[3], a: match[4] };
  14038. }
  14039. if ((match = matchers.hsv.exec(color))) {
  14040. return { h: match[1], s: match[2], v: match[3] };
  14041. }
  14042. if ((match = matchers.hsva.exec(color))) {
  14043. return { h: match[1], s: match[2], v: match[3], a: match[4] };
  14044. }
  14045. if ((match = matchers.hex8.exec(color))) {
  14046. return {
  14047. r: parseIntFromHex(match[1]),
  14048. g: parseIntFromHex(match[2]),
  14049. b: parseIntFromHex(match[3]),
  14050. a: convertHexToDecimal(match[4]),
  14051. format: named ? "name" : "hex8"
  14052. };
  14053. }
  14054. if ((match = matchers.hex6.exec(color))) {
  14055. return {
  14056. r: parseIntFromHex(match[1]),
  14057. g: parseIntFromHex(match[2]),
  14058. b: parseIntFromHex(match[3]),
  14059. format: named ? "name" : "hex"
  14060. };
  14061. }
  14062. if ((match = matchers.hex4.exec(color))) {
  14063. return {
  14064. r: parseIntFromHex(match[1] + '' + match[1]),
  14065. g: parseIntFromHex(match[2] + '' + match[2]),
  14066. b: parseIntFromHex(match[3] + '' + match[3]),
  14067. a: convertHexToDecimal(match[4] + '' + match[4]),
  14068. format: named ? "name" : "hex8"
  14069. };
  14070. }
  14071. if ((match = matchers.hex3.exec(color))) {
  14072. return {
  14073. r: parseIntFromHex(match[1] + '' + match[1]),
  14074. g: parseIntFromHex(match[2] + '' + match[2]),
  14075. b: parseIntFromHex(match[3] + '' + match[3]),
  14076. format: named ? "name" : "hex"
  14077. };
  14078. }
  14079. return false;
  14080. }
  14081. function validateWCAG2Parms(parms) {
  14082. // return valid WCAG2 parms for isReadable.
  14083. // If input parms are invalid, return {"level":"AA", "size":"small"}
  14084. var level, size;
  14085. parms = parms || {"level":"AA", "size":"small"};
  14086. level = (parms.level || "AA").toUpperCase();
  14087. size = (parms.size || "small").toLowerCase();
  14088. if (level !== "AA" && level !== "AAA") {
  14089. level = "AA";
  14090. }
  14091. if (size !== "small" && size !== "large") {
  14092. size = "small";
  14093. }
  14094. return {"level":level, "size":size};
  14095. }
  14096. // Node: Export function
  14097. if (typeof module !== "undefined" && module.exports) {
  14098. module.exports = tinycolor;
  14099. }
  14100. // AMD/requirejs: Define the module
  14101. else if (typeof define === 'function' && define.amd) {
  14102. define(function () {return tinycolor;});
  14103. }
  14104. // Browser: Expose to window
  14105. else {
  14106. window.tinycolor = tinycolor;
  14107. }
  14108. })(Math);
  14109. },{}],35:[function(_dereq_,module,exports){
  14110. /**
  14111. * Copyright 2012-2019, Plotly, Inc.
  14112. * All rights reserved.
  14113. *
  14114. * This source code is licensed under the MIT license found in the
  14115. * LICENSE file in the root directory of this source tree.
  14116. */
  14117. 'use strict';
  14118. /**
  14119. * All paths are tuned for maximum scalability of the arrowhead,
  14120. * ie throughout arrowwidth=0.3..3 the head is joined smoothly
  14121. * to the line, with the line coming from the left and ending at (0, 0).
  14122. *
  14123. * `backoff` is the distance to move the arrowhead and the end of the line,
  14124. * in order that the arrowhead points to the desired place, either at
  14125. * the tip of the arrow or (in the case of circle or square)
  14126. * the center of the symbol.
  14127. *
  14128. * `noRotate`, if truthy, says that this arrowhead should not rotate with the
  14129. * arrow. That's the case for squares, which should always be straight, and
  14130. * circles, for which it's irrelevant.
  14131. */
  14132. module.exports = [
  14133. // no arrow
  14134. {
  14135. path: '',
  14136. backoff: 0
  14137. },
  14138. // wide with flat back
  14139. {
  14140. path: 'M-2.4,-3V3L0.6,0Z',
  14141. backoff: 0.6
  14142. },
  14143. // narrower with flat back
  14144. {
  14145. path: 'M-3.7,-2.5V2.5L1.3,0Z',
  14146. backoff: 1.3
  14147. },
  14148. // barbed
  14149. {
  14150. path: 'M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z',
  14151. backoff: 1.55
  14152. },
  14153. // wide line-drawn
  14154. {
  14155. path: 'M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z',
  14156. backoff: 1.6
  14157. },
  14158. // narrower line-drawn
  14159. {
  14160. path: 'M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z',
  14161. backoff: 2
  14162. },
  14163. // circle
  14164. {
  14165. path: 'M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z',
  14166. backoff: 0,
  14167. noRotate: true
  14168. },
  14169. // square
  14170. {
  14171. path: 'M2,2V-2H-2V2Z',
  14172. backoff: 0,
  14173. noRotate: true
  14174. }
  14175. ];
  14176. },{}],36:[function(_dereq_,module,exports){
  14177. /**
  14178. * Copyright 2012-2019, Plotly, Inc.
  14179. * All rights reserved.
  14180. *
  14181. * This source code is licensed under the MIT license found in the
  14182. * LICENSE file in the root directory of this source tree.
  14183. */
  14184. 'use strict';
  14185. var ARROWPATHS = _dereq_('./arrow_paths');
  14186. var fontAttrs = _dereq_('../../plots/font_attributes');
  14187. var cartesianConstants = _dereq_('../../plots/cartesian/constants');
  14188. var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;
  14189. module.exports = templatedArray('annotation', {
  14190. visible: {
  14191. valType: 'boolean',
  14192. dflt: true,
  14193. editType: 'calc+arraydraw',
  14194. },
  14195. text: {
  14196. valType: 'string',
  14197. editType: 'calc+arraydraw',
  14198. },
  14199. textangle: {
  14200. valType: 'angle',
  14201. dflt: 0,
  14202. editType: 'calc+arraydraw',
  14203. },
  14204. font: fontAttrs({
  14205. editType: 'calc+arraydraw',
  14206. colorEditType: 'arraydraw',
  14207. }),
  14208. width: {
  14209. valType: 'number',
  14210. min: 1,
  14211. dflt: null,
  14212. editType: 'calc+arraydraw',
  14213. },
  14214. height: {
  14215. valType: 'number',
  14216. min: 1,
  14217. dflt: null,
  14218. editType: 'calc+arraydraw',
  14219. },
  14220. opacity: {
  14221. valType: 'number',
  14222. min: 0,
  14223. max: 1,
  14224. dflt: 1,
  14225. editType: 'arraydraw',
  14226. },
  14227. align: {
  14228. valType: 'enumerated',
  14229. values: ['left', 'center', 'right'],
  14230. dflt: 'center',
  14231. editType: 'arraydraw',
  14232. },
  14233. valign: {
  14234. valType: 'enumerated',
  14235. values: ['top', 'middle', 'bottom'],
  14236. dflt: 'middle',
  14237. editType: 'arraydraw',
  14238. },
  14239. bgcolor: {
  14240. valType: 'color',
  14241. dflt: 'rgba(0,0,0,0)',
  14242. editType: 'arraydraw',
  14243. },
  14244. bordercolor: {
  14245. valType: 'color',
  14246. dflt: 'rgba(0,0,0,0)',
  14247. editType: 'arraydraw',
  14248. },
  14249. borderpad: {
  14250. valType: 'number',
  14251. min: 0,
  14252. dflt: 1,
  14253. editType: 'calc+arraydraw',
  14254. },
  14255. borderwidth: {
  14256. valType: 'number',
  14257. min: 0,
  14258. dflt: 1,
  14259. editType: 'calc+arraydraw',
  14260. },
  14261. // arrow
  14262. showarrow: {
  14263. valType: 'boolean',
  14264. dflt: true,
  14265. editType: 'calc+arraydraw',
  14266. },
  14267. arrowcolor: {
  14268. valType: 'color',
  14269. editType: 'arraydraw',
  14270. },
  14271. arrowhead: {
  14272. valType: 'integer',
  14273. min: 0,
  14274. max: ARROWPATHS.length,
  14275. dflt: 1,
  14276. editType: 'arraydraw',
  14277. },
  14278. startarrowhead: {
  14279. valType: 'integer',
  14280. min: 0,
  14281. max: ARROWPATHS.length,
  14282. dflt: 1,
  14283. editType: 'arraydraw',
  14284. },
  14285. arrowside: {
  14286. valType: 'flaglist',
  14287. flags: ['end', 'start'],
  14288. extras: ['none'],
  14289. dflt: 'end',
  14290. editType: 'arraydraw',
  14291. },
  14292. arrowsize: {
  14293. valType: 'number',
  14294. min: 0.3,
  14295. dflt: 1,
  14296. editType: 'calc+arraydraw',
  14297. },
  14298. startarrowsize: {
  14299. valType: 'number',
  14300. min: 0.3,
  14301. dflt: 1,
  14302. editType: 'calc+arraydraw',
  14303. },
  14304. arrowwidth: {
  14305. valType: 'number',
  14306. min: 0.1,
  14307. editType: 'calc+arraydraw',
  14308. },
  14309. standoff: {
  14310. valType: 'number',
  14311. min: 0,
  14312. dflt: 0,
  14313. editType: 'calc+arraydraw',
  14314. },
  14315. startstandoff: {
  14316. valType: 'number',
  14317. min: 0,
  14318. dflt: 0,
  14319. editType: 'calc+arraydraw',
  14320. },
  14321. ax: {
  14322. valType: 'any',
  14323. editType: 'calc+arraydraw',
  14324. },
  14325. ay: {
  14326. valType: 'any',
  14327. editType: 'calc+arraydraw',
  14328. },
  14329. axref: {
  14330. valType: 'enumerated',
  14331. dflt: 'pixel',
  14332. values: [
  14333. 'pixel',
  14334. cartesianConstants.idRegex.x.toString()
  14335. ],
  14336. editType: 'calc',
  14337. },
  14338. ayref: {
  14339. valType: 'enumerated',
  14340. dflt: 'pixel',
  14341. values: [
  14342. 'pixel',
  14343. cartesianConstants.idRegex.y.toString()
  14344. ],
  14345. editType: 'calc',
  14346. },
  14347. // positioning
  14348. xref: {
  14349. valType: 'enumerated',
  14350. values: [
  14351. 'paper',
  14352. cartesianConstants.idRegex.x.toString()
  14353. ],
  14354. editType: 'calc',
  14355. },
  14356. x: {
  14357. valType: 'any',
  14358. editType: 'calc+arraydraw',
  14359. },
  14360. xanchor: {
  14361. valType: 'enumerated',
  14362. values: ['auto', 'left', 'center', 'right'],
  14363. dflt: 'auto',
  14364. editType: 'calc+arraydraw',
  14365. },
  14366. xshift: {
  14367. valType: 'number',
  14368. dflt: 0,
  14369. editType: 'calc+arraydraw',
  14370. },
  14371. yref: {
  14372. valType: 'enumerated',
  14373. values: [
  14374. 'paper',
  14375. cartesianConstants.idRegex.y.toString()
  14376. ],
  14377. editType: 'calc',
  14378. },
  14379. y: {
  14380. valType: 'any',
  14381. editType: 'calc+arraydraw',
  14382. },
  14383. yanchor: {
  14384. valType: 'enumerated',
  14385. values: ['auto', 'top', 'middle', 'bottom'],
  14386. dflt: 'auto',
  14387. editType: 'calc+arraydraw',
  14388. },
  14389. yshift: {
  14390. valType: 'number',
  14391. dflt: 0,
  14392. editType: 'calc+arraydraw',
  14393. },
  14394. clicktoshow: {
  14395. valType: 'enumerated',
  14396. values: [false, 'onoff', 'onout'],
  14397. dflt: false,
  14398. editType: 'arraydraw',
  14399. },
  14400. xclick: {
  14401. valType: 'any',
  14402. editType: 'arraydraw',
  14403. },
  14404. yclick: {
  14405. valType: 'any',
  14406. editType: 'arraydraw',
  14407. },
  14408. hovertext: {
  14409. valType: 'string',
  14410. editType: 'arraydraw',
  14411. },
  14412. hoverlabel: {
  14413. bgcolor: {
  14414. valType: 'color',
  14415. editType: 'arraydraw',
  14416. },
  14417. bordercolor: {
  14418. valType: 'color',
  14419. editType: 'arraydraw',
  14420. },
  14421. font: fontAttrs({
  14422. editType: 'arraydraw',
  14423. }),
  14424. editType: 'arraydraw'
  14425. },
  14426. captureevents: {
  14427. valType: 'boolean',
  14428. editType: 'arraydraw',
  14429. },
  14430. editType: 'calc',
  14431. _deprecated: {
  14432. ref: {
  14433. valType: 'string',
  14434. editType: 'calc',
  14435. }
  14436. }
  14437. });
  14438. },{"../../plot_api/plot_template":202,"../../plots/cartesian/constants":218,"../../plots/font_attributes":239,"./arrow_paths":35}],37:[function(_dereq_,module,exports){
  14439. /**
  14440. * Copyright 2012-2019, Plotly, Inc.
  14441. * All rights reserved.
  14442. *
  14443. * This source code is licensed under the MIT license found in the
  14444. * LICENSE file in the root directory of this source tree.
  14445. */
  14446. 'use strict';
  14447. var Lib = _dereq_('../../lib');
  14448. var Axes = _dereq_('../../plots/cartesian/axes');
  14449. var draw = _dereq_('./draw').draw;
  14450. module.exports = function calcAutorange(gd) {
  14451. var fullLayout = gd._fullLayout;
  14452. var annotationList = Lib.filterVisible(fullLayout.annotations);
  14453. if(annotationList.length && gd._fullData.length) {
  14454. return Lib.syncOrAsync([draw, annAutorange], gd);
  14455. }
  14456. };
  14457. function annAutorange(gd) {
  14458. var fullLayout = gd._fullLayout;
  14459. // find the bounding boxes for each of these annotations'
  14460. // relative to their anchor points
  14461. // use the arrow and the text bg rectangle,
  14462. // as the whole anno may include hidden text in its bbox
  14463. Lib.filterVisible(fullLayout.annotations).forEach(function(ann) {
  14464. var xa = Axes.getFromId(gd, ann.xref);
  14465. var ya = Axes.getFromId(gd, ann.yref);
  14466. ann._extremes = {};
  14467. if(xa) calcAxisExpansion(ann, xa);
  14468. if(ya) calcAxisExpansion(ann, ya);
  14469. });
  14470. }
  14471. function calcAxisExpansion(ann, ax) {
  14472. var axId = ax._id;
  14473. var letter = axId.charAt(0);
  14474. var pos = ann[letter];
  14475. var apos = ann['a' + letter];
  14476. var ref = ann[letter + 'ref'];
  14477. var aref = ann['a' + letter + 'ref'];
  14478. var padplus = ann['_' + letter + 'padplus'];
  14479. var padminus = ann['_' + letter + 'padminus'];
  14480. var shift = {x: 1, y: -1}[letter] * ann[letter + 'shift'];
  14481. var headSize = 3 * ann.arrowsize * ann.arrowwidth || 0;
  14482. var headPlus = headSize + shift;
  14483. var headMinus = headSize - shift;
  14484. var startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0;
  14485. var startHeadPlus = startHeadSize + shift;
  14486. var startHeadMinus = startHeadSize - shift;
  14487. var extremes;
  14488. if(aref === ref) {
  14489. // expand for the arrowhead (padded by arrowhead)
  14490. var extremeArrowHead = Axes.findExtremes(ax, [ax.r2c(pos)], {
  14491. ppadplus: headPlus,
  14492. ppadminus: headMinus
  14493. });
  14494. // again for the textbox (padded by textbox)
  14495. var extremeText = Axes.findExtremes(ax, [ax.r2c(apos)], {
  14496. ppadplus: Math.max(padplus, startHeadPlus),
  14497. ppadminus: Math.max(padminus, startHeadMinus)
  14498. });
  14499. extremes = {
  14500. min: [extremeArrowHead.min[0], extremeText.min[0]],
  14501. max: [extremeArrowHead.max[0], extremeText.max[0]]
  14502. };
  14503. } else {
  14504. startHeadPlus = apos ? startHeadPlus + apos : startHeadPlus;
  14505. startHeadMinus = apos ? startHeadMinus - apos : startHeadMinus;
  14506. extremes = Axes.findExtremes(ax, [ax.r2c(pos)], {
  14507. ppadplus: Math.max(padplus, headPlus, startHeadPlus),
  14508. ppadminus: Math.max(padminus, headMinus, startHeadMinus)
  14509. });
  14510. }
  14511. ann._extremes[axId] = extremes;
  14512. }
  14513. },{"../../lib":168,"../../plots/cartesian/axes":212,"./draw":42}],38:[function(_dereq_,module,exports){
  14514. /**
  14515. * Copyright 2012-2019, Plotly, Inc.
  14516. * All rights reserved.
  14517. *
  14518. * This source code is licensed under the MIT license found in the
  14519. * LICENSE file in the root directory of this source tree.
  14520. */
  14521. 'use strict';
  14522. var Lib = _dereq_('../../lib');
  14523. var Registry = _dereq_('../../registry');
  14524. var arrayEditor = _dereq_('../../plot_api/plot_template').arrayEditor;
  14525. module.exports = {
  14526. hasClickToShow: hasClickToShow,
  14527. onClick: onClick
  14528. };
  14529. /*
  14530. * hasClickToShow: does the given hoverData have ANY annotations which will
  14531. * turn ON if we click here? (used by hover events to set cursor)
  14532. *
  14533. * gd: graphDiv
  14534. * hoverData: a hoverData array, as included with the *plotly_hover* or
  14535. * *plotly_click* events in the `points` attribute
  14536. *
  14537. * returns: boolean
  14538. */
  14539. function hasClickToShow(gd, hoverData) {
  14540. var sets = getToggleSets(gd, hoverData);
  14541. return sets.on.length > 0 || sets.explicitOff.length > 0;
  14542. }
  14543. /*
  14544. * onClick: perform the toggling (via Plotly.update) implied by clicking
  14545. * at this hoverData
  14546. *
  14547. * gd: graphDiv
  14548. * hoverData: a hoverData array, as included with the *plotly_hover* or
  14549. * *plotly_click* events in the `points` attribute
  14550. *
  14551. * returns: Promise that the update is complete
  14552. */
  14553. function onClick(gd, hoverData) {
  14554. var toggleSets = getToggleSets(gd, hoverData);
  14555. var onSet = toggleSets.on;
  14556. var offSet = toggleSets.off.concat(toggleSets.explicitOff);
  14557. var update = {};
  14558. var annotationsOut = gd._fullLayout.annotations;
  14559. var i, editHelpers;
  14560. if(!(onSet.length || offSet.length)) return;
  14561. for(i = 0; i < onSet.length; i++) {
  14562. editHelpers = arrayEditor(gd.layout, 'annotations', annotationsOut[onSet[i]]);
  14563. editHelpers.modifyItem('visible', true);
  14564. Lib.extendFlat(update, editHelpers.getUpdateObj());
  14565. }
  14566. for(i = 0; i < offSet.length; i++) {
  14567. editHelpers = arrayEditor(gd.layout, 'annotations', annotationsOut[offSet[i]]);
  14568. editHelpers.modifyItem('visible', false);
  14569. Lib.extendFlat(update, editHelpers.getUpdateObj());
  14570. }
  14571. return Registry.call('update', gd, {}, update);
  14572. }
  14573. /*
  14574. * getToggleSets: find the annotations which will turn on or off at this
  14575. * hoverData
  14576. *
  14577. * gd: graphDiv
  14578. * hoverData: a hoverData array, as included with the *plotly_hover* or
  14579. * *plotly_click* events in the `points` attribute
  14580. *
  14581. * returns: {
  14582. * on: Array (indices of annotations to turn on),
  14583. * off: Array (indices to turn off because you're not hovering on them),
  14584. * explicitOff: Array (indices to turn off because you *are* hovering on them)
  14585. * }
  14586. */
  14587. function getToggleSets(gd, hoverData) {
  14588. var annotations = gd._fullLayout.annotations;
  14589. var onSet = [];
  14590. var offSet = [];
  14591. var explicitOffSet = [];
  14592. var hoverLen = (hoverData || []).length;
  14593. var i, j, anni, showMode, pointj, xa, ya, toggleType;
  14594. for(i = 0; i < annotations.length; i++) {
  14595. anni = annotations[i];
  14596. showMode = anni.clicktoshow;
  14597. if(showMode) {
  14598. for(j = 0; j < hoverLen; j++) {
  14599. pointj = hoverData[j];
  14600. xa = pointj.xaxis;
  14601. ya = pointj.yaxis;
  14602. if(xa._id === anni.xref &&
  14603. ya._id === anni.yref &&
  14604. xa.d2r(pointj.x) === clickData2r(anni._xclick, xa) &&
  14605. ya.d2r(pointj.y) === clickData2r(anni._yclick, ya)
  14606. ) {
  14607. // match! toggle this annotation
  14608. // regardless of its clicktoshow mode
  14609. // but if it's onout mode, off is implicit
  14610. if(anni.visible) {
  14611. if(showMode === 'onout') toggleType = offSet;
  14612. else toggleType = explicitOffSet;
  14613. }
  14614. else {
  14615. toggleType = onSet;
  14616. }
  14617. toggleType.push(i);
  14618. break;
  14619. }
  14620. }
  14621. if(j === hoverLen) {
  14622. // no match - only turn this annotation OFF, and only if
  14623. // showmode is 'onout'
  14624. if(anni.visible && showMode === 'onout') offSet.push(i);
  14625. }
  14626. }
  14627. }
  14628. return {on: onSet, off: offSet, explicitOff: explicitOffSet};
  14629. }
  14630. // to handle log axes until v2
  14631. function clickData2r(d, ax) {
  14632. return ax.type === 'log' ? ax.l2r(d) : ax.d2r(d);
  14633. }
  14634. },{"../../lib":168,"../../plot_api/plot_template":202,"../../registry":257}],39:[function(_dereq_,module,exports){
  14635. /**
  14636. * Copyright 2012-2019, Plotly, Inc.
  14637. * All rights reserved.
  14638. *
  14639. * This source code is licensed under the MIT license found in the
  14640. * LICENSE file in the root directory of this source tree.
  14641. */
  14642. 'use strict';
  14643. var Lib = _dereq_('../../lib');
  14644. var Color = _dereq_('../color');
  14645. // defaults common to 'annotations' and 'annotations3d'
  14646. module.exports = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce) {
  14647. coerce('opacity');
  14648. var bgColor = coerce('bgcolor');
  14649. var borderColor = coerce('bordercolor');
  14650. var borderOpacity = Color.opacity(borderColor);
  14651. coerce('borderpad');
  14652. var borderWidth = coerce('borderwidth');
  14653. var showArrow = coerce('showarrow');
  14654. coerce('text', showArrow ? ' ' : fullLayout._dfltTitle.annotation);
  14655. coerce('textangle');
  14656. Lib.coerceFont(coerce, 'font', fullLayout.font);
  14657. coerce('width');
  14658. coerce('align');
  14659. var h = coerce('height');
  14660. if(h) coerce('valign');
  14661. if(showArrow) {
  14662. var arrowside = coerce('arrowside');
  14663. var arrowhead;
  14664. var arrowsize;
  14665. if(arrowside.indexOf('end') !== -1) {
  14666. arrowhead = coerce('arrowhead');
  14667. arrowsize = coerce('arrowsize');
  14668. }
  14669. if(arrowside.indexOf('start') !== -1) {
  14670. coerce('startarrowhead', arrowhead);
  14671. coerce('startarrowsize', arrowsize);
  14672. }
  14673. coerce('arrowcolor', borderOpacity ? annOut.bordercolor : Color.defaultLine);
  14674. coerce('arrowwidth', ((borderOpacity && borderWidth) || 1) * 2);
  14675. coerce('standoff');
  14676. coerce('startstandoff');
  14677. }
  14678. var hoverText = coerce('hovertext');
  14679. var globalHoverLabel = fullLayout.hoverlabel || {};
  14680. if(hoverText) {
  14681. var hoverBG = coerce('hoverlabel.bgcolor', globalHoverLabel.bgcolor ||
  14682. (Color.opacity(bgColor) ? Color.rgb(bgColor) : Color.defaultLine)
  14683. );
  14684. var hoverBorder = coerce('hoverlabel.bordercolor', globalHoverLabel.bordercolor ||
  14685. Color.contrast(hoverBG)
  14686. );
  14687. Lib.coerceFont(coerce, 'hoverlabel.font', {
  14688. family: globalHoverLabel.font.family,
  14689. size: globalHoverLabel.font.size,
  14690. color: globalHoverLabel.font.color || hoverBorder
  14691. });
  14692. }
  14693. coerce('captureevents', !!hoverText);
  14694. };
  14695. },{"../../lib":168,"../color":51}],40:[function(_dereq_,module,exports){
  14696. /**
  14697. * Copyright 2012-2019, Plotly, Inc.
  14698. * All rights reserved.
  14699. *
  14700. * This source code is licensed under the MIT license found in the
  14701. * LICENSE file in the root directory of this source tree.
  14702. */
  14703. 'use strict';
  14704. var isNumeric = _dereq_('fast-isnumeric');
  14705. var toLogRange = _dereq_('../../lib/to_log_range');
  14706. /*
  14707. * convertCoords: when converting an axis between log and linear
  14708. * you need to alter any annotations on that axis to keep them
  14709. * pointing at the same data point.
  14710. * In v2.0 this will become obsolete
  14711. *
  14712. * gd: the plot div
  14713. * ax: the axis being changed
  14714. * newType: the type it's getting
  14715. * doExtra: function(attr, val) from inside relayout that sets the attribute.
  14716. * Use this to make the changes as it's aware if any other changes in the
  14717. * same relayout call should override this conversion.
  14718. */
  14719. module.exports = function convertCoords(gd, ax, newType, doExtra) {
  14720. ax = ax || {};
  14721. var toLog = (newType === 'log') && (ax.type === 'linear');
  14722. var fromLog = (newType === 'linear') && (ax.type === 'log');
  14723. if(!(toLog || fromLog)) return;
  14724. var annotations = gd._fullLayout.annotations;
  14725. var axLetter = ax._id.charAt(0);
  14726. var ann;
  14727. var attrPrefix;
  14728. function convert(attr) {
  14729. var currentVal = ann[attr];
  14730. var newVal = null;
  14731. if(toLog) newVal = toLogRange(currentVal, ax.range);
  14732. else newVal = Math.pow(10, currentVal);
  14733. // if conversion failed, delete the value so it gets a default value
  14734. if(!isNumeric(newVal)) newVal = null;
  14735. doExtra(attrPrefix + attr, newVal);
  14736. }
  14737. for(var i = 0; i < annotations.length; i++) {
  14738. ann = annotations[i];
  14739. attrPrefix = 'annotations[' + i + '].';
  14740. if(ann[axLetter + 'ref'] === ax._id) convert(axLetter);
  14741. if(ann['a' + axLetter + 'ref'] === ax._id) convert('a' + axLetter);
  14742. }
  14743. };
  14744. },{"../../lib/to_log_range":191,"fast-isnumeric":18}],41:[function(_dereq_,module,exports){
  14745. /**
  14746. * Copyright 2012-2019, Plotly, Inc.
  14747. * All rights reserved.
  14748. *
  14749. * This source code is licensed under the MIT license found in the
  14750. * LICENSE file in the root directory of this source tree.
  14751. */
  14752. 'use strict';
  14753. var Lib = _dereq_('../../lib');
  14754. var Axes = _dereq_('../../plots/cartesian/axes');
  14755. var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');
  14756. var handleAnnotationCommonDefaults = _dereq_('./common_defaults');
  14757. var attributes = _dereq_('./attributes');
  14758. module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
  14759. handleArrayContainerDefaults(layoutIn, layoutOut, {
  14760. name: 'annotations',
  14761. handleItemDefaults: handleAnnotationDefaults
  14762. });
  14763. };
  14764. function handleAnnotationDefaults(annIn, annOut, fullLayout) {
  14765. function coerce(attr, dflt) {
  14766. return Lib.coerce(annIn, annOut, attributes, attr, dflt);
  14767. }
  14768. var visible = coerce('visible');
  14769. var clickToShow = coerce('clicktoshow');
  14770. if(!(visible || clickToShow)) return;
  14771. handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce);
  14772. var showArrow = annOut.showarrow;
  14773. // positioning
  14774. var axLetters = ['x', 'y'];
  14775. var arrowPosDflt = [-10, -30];
  14776. var gdMock = {_fullLayout: fullLayout};
  14777. for(var i = 0; i < 2; i++) {
  14778. var axLetter = axLetters[i];
  14779. // xref, yref
  14780. var axRef = Axes.coerceRef(annIn, annOut, gdMock, axLetter, '', 'paper');
  14781. if(axRef !== 'paper') {
  14782. var ax = Axes.getFromId(gdMock, axRef);
  14783. ax._annIndices.push(annOut._index);
  14784. }
  14785. // x, y
  14786. Axes.coercePosition(annOut, gdMock, coerce, axRef, axLetter, 0.5);
  14787. if(showArrow) {
  14788. var arrowPosAttr = 'a' + axLetter;
  14789. // axref, ayref
  14790. var aaxRef = Axes.coerceRef(annIn, annOut, gdMock, arrowPosAttr, 'pixel');
  14791. // for now the arrow can only be on the same axis or specified as pixels
  14792. // TODO: sometime it might be interesting to allow it to be on *any* axis
  14793. // but that would require updates to drawing & autorange code and maybe more
  14794. if(aaxRef !== 'pixel' && aaxRef !== axRef) {
  14795. aaxRef = annOut[arrowPosAttr] = 'pixel';
  14796. }
  14797. // ax, ay
  14798. var aDflt = (aaxRef === 'pixel') ? arrowPosDflt[i] : 0.4;
  14799. Axes.coercePosition(annOut, gdMock, coerce, aaxRef, arrowPosAttr, aDflt);
  14800. }
  14801. // xanchor, yanchor
  14802. coerce(axLetter + 'anchor');
  14803. // xshift, yshift
  14804. coerce(axLetter + 'shift');
  14805. }
  14806. // if you have one coordinate you should have both
  14807. Lib.noneOrAll(annIn, annOut, ['x', 'y']);
  14808. // if you have one part of arrow length you should have both
  14809. if(showArrow) {
  14810. Lib.noneOrAll(annIn, annOut, ['ax', 'ay']);
  14811. }
  14812. if(clickToShow) {
  14813. var xClick = coerce('xclick');
  14814. var yClick = coerce('yclick');
  14815. // put the actual click data to bind to into private attributes
  14816. // so we don't have to do this little bit of logic on every hover event
  14817. annOut._xclick = (xClick === undefined) ?
  14818. annOut.x :
  14819. Axes.cleanPosition(xClick, gdMock, annOut.xref);
  14820. annOut._yclick = (yClick === undefined) ?
  14821. annOut.y :
  14822. Axes.cleanPosition(yClick, gdMock, annOut.yref);
  14823. }
  14824. }
  14825. },{"../../lib":168,"../../plots/array_container_defaults":208,"../../plots/cartesian/axes":212,"./attributes":36,"./common_defaults":39}],42:[function(_dereq_,module,exports){
  14826. /**
  14827. * Copyright 2012-2019, Plotly, Inc.
  14828. * All rights reserved.
  14829. *
  14830. * This source code is licensed under the MIT license found in the
  14831. * LICENSE file in the root directory of this source tree.
  14832. */
  14833. 'use strict';
  14834. var d3 = _dereq_('d3');
  14835. var Registry = _dereq_('../../registry');
  14836. var Plots = _dereq_('../../plots/plots');
  14837. var Lib = _dereq_('../../lib');
  14838. var Axes = _dereq_('../../plots/cartesian/axes');
  14839. var Color = _dereq_('../color');
  14840. var Drawing = _dereq_('../drawing');
  14841. var Fx = _dereq_('../fx');
  14842. var svgTextUtils = _dereq_('../../lib/svg_text_utils');
  14843. var setCursor = _dereq_('../../lib/setcursor');
  14844. var dragElement = _dereq_('../dragelement');
  14845. var arrayEditor = _dereq_('../../plot_api/plot_template').arrayEditor;
  14846. var drawArrowHead = _dereq_('./draw_arrow_head');
  14847. // Annotations are stored in gd.layout.annotations, an array of objects
  14848. // index can point to one item in this array,
  14849. // or non-numeric to simply add a new one
  14850. // or -1 to modify all existing
  14851. // opt can be the full options object, or one key (to be set to value)
  14852. // or undefined to simply redraw
  14853. // if opt is blank, val can be 'add' or a full options object to add a new
  14854. // annotation at that point in the array, or 'remove' to delete this one
  14855. module.exports = {
  14856. draw: draw,
  14857. drawOne: drawOne,
  14858. drawRaw: drawRaw
  14859. };
  14860. /*
  14861. * draw: draw all annotations without any new modifications
  14862. */
  14863. function draw(gd) {
  14864. var fullLayout = gd._fullLayout;
  14865. fullLayout._infolayer.selectAll('.annotation').remove();
  14866. for(var i = 0; i < fullLayout.annotations.length; i++) {
  14867. if(fullLayout.annotations[i].visible) {
  14868. drawOne(gd, i);
  14869. }
  14870. }
  14871. return Plots.previousPromises(gd);
  14872. }
  14873. /*
  14874. * drawOne: draw a single cartesian or paper-ref annotation, potentially with modifications
  14875. *
  14876. * index (int): the annotation to draw
  14877. */
  14878. function drawOne(gd, index) {
  14879. var fullLayout = gd._fullLayout;
  14880. var options = fullLayout.annotations[index] || {};
  14881. var xa = Axes.getFromId(gd, options.xref);
  14882. var ya = Axes.getFromId(gd, options.yref);
  14883. if(xa) xa.setScale();
  14884. if(ya) ya.setScale();
  14885. drawRaw(gd, options, index, false, xa, ya);
  14886. }
  14887. /**
  14888. * drawRaw: draw a single annotation, potentially with modifications
  14889. *
  14890. * @param {DOM element} gd
  14891. * @param {object} options : this annotation's fullLayout options
  14892. * @param {integer} index : index in 'annotations' container of the annotation to draw
  14893. * @param {string} subplotId : id of the annotation's subplot
  14894. * - use false for 2d (i.e. cartesian or paper-ref) annotations
  14895. * @param {object | undefined} xa : full x-axis object to compute subplot pos-to-px
  14896. * @param {object | undefined} ya : ... y-axis
  14897. */
  14898. function drawRaw(gd, options, index, subplotId, xa, ya) {
  14899. var fullLayout = gd._fullLayout;
  14900. var gs = gd._fullLayout._size;
  14901. var edits = gd._context.edits;
  14902. var className, containerStr;
  14903. if(subplotId) {
  14904. className = 'annotation-' + subplotId;
  14905. containerStr = subplotId + '.annotations';
  14906. } else {
  14907. className = 'annotation';
  14908. containerStr = 'annotations';
  14909. }
  14910. var editHelpers = arrayEditor(gd.layout, containerStr, options);
  14911. var modifyBase = editHelpers.modifyBase;
  14912. var modifyItem = editHelpers.modifyItem;
  14913. var getUpdateObj = editHelpers.getUpdateObj;
  14914. // remove the existing annotation if there is one
  14915. fullLayout._infolayer
  14916. .selectAll('.' + className + '[data-index="' + index + '"]')
  14917. .remove();
  14918. var annClipID = 'clip' + fullLayout._uid + '_ann' + index;
  14919. // this annotation is gone - quit now after deleting it
  14920. // TODO: use d3 idioms instead of deleting and redrawing every time
  14921. if(!options._input || options.visible === false) {
  14922. d3.selectAll('#' + annClipID).remove();
  14923. return;
  14924. }
  14925. // calculated pixel positions
  14926. // x & y each will get text, head, and tail as appropriate
  14927. var annPosPx = {x: {}, y: {}};
  14928. var textangle = +options.textangle || 0;
  14929. // create the components
  14930. // made a single group to contain all, so opacity can work right
  14931. // with border/arrow together this could handle a whole bunch of
  14932. // cleanup at this point, but works for now
  14933. var annGroup = fullLayout._infolayer.append('g')
  14934. .classed(className, true)
  14935. .attr('data-index', String(index))
  14936. .style('opacity', options.opacity);
  14937. // another group for text+background so that they can rotate together
  14938. var annTextGroup = annGroup.append('g')
  14939. .classed('annotation-text-g', true);
  14940. var editTextPosition = edits[options.showarrow ? 'annotationTail' : 'annotationPosition'];
  14941. var textEvents = options.captureevents || edits.annotationText || editTextPosition;
  14942. var annTextGroupInner = annTextGroup.append('g')
  14943. .style('pointer-events', textEvents ? 'all' : null)
  14944. .call(setCursor, 'pointer')
  14945. .on('click', function() {
  14946. gd._dragging = false;
  14947. var eventData = {
  14948. index: index,
  14949. annotation: options._input,
  14950. fullAnnotation: options,
  14951. event: d3.event
  14952. };
  14953. if(subplotId) {
  14954. eventData.subplotId = subplotId;
  14955. }
  14956. gd.emit('plotly_clickannotation', eventData);
  14957. });
  14958. if(options.hovertext) {
  14959. annTextGroupInner
  14960. .on('mouseover', function() {
  14961. var hoverOptions = options.hoverlabel;
  14962. var hoverFont = hoverOptions.font;
  14963. var bBox = this.getBoundingClientRect();
  14964. var bBoxRef = gd.getBoundingClientRect();
  14965. Fx.loneHover({
  14966. x0: bBox.left - bBoxRef.left,
  14967. x1: bBox.right - bBoxRef.left,
  14968. y: (bBox.top + bBox.bottom) / 2 - bBoxRef.top,
  14969. text: options.hovertext,
  14970. color: hoverOptions.bgcolor,
  14971. borderColor: hoverOptions.bordercolor,
  14972. fontFamily: hoverFont.family,
  14973. fontSize: hoverFont.size,
  14974. fontColor: hoverFont.color
  14975. }, {
  14976. container: fullLayout._hoverlayer.node(),
  14977. outerContainer: fullLayout._paper.node(),
  14978. gd: gd
  14979. });
  14980. })
  14981. .on('mouseout', function() {
  14982. Fx.loneUnhover(fullLayout._hoverlayer.node());
  14983. });
  14984. }
  14985. var borderwidth = options.borderwidth;
  14986. var borderpad = options.borderpad;
  14987. var borderfull = borderwidth + borderpad;
  14988. var annTextBG = annTextGroupInner.append('rect')
  14989. .attr('class', 'bg')
  14990. .style('stroke-width', borderwidth + 'px')
  14991. .call(Color.stroke, options.bordercolor)
  14992. .call(Color.fill, options.bgcolor);
  14993. var isSizeConstrained = options.width || options.height;
  14994. var annTextClip = fullLayout._topclips
  14995. .selectAll('#' + annClipID)
  14996. .data(isSizeConstrained ? [0] : []);
  14997. annTextClip.enter().append('clipPath')
  14998. .classed('annclip', true)
  14999. .attr('id', annClipID)
  15000. .append('rect');
  15001. annTextClip.exit().remove();
  15002. var font = options.font;
  15003. var text = fullLayout.meta ?
  15004. Lib.templateString(options.text, {meta: fullLayout.meta}) :
  15005. options.text;
  15006. var annText = annTextGroupInner.append('text')
  15007. .classed('annotation-text', true)
  15008. .text(text);
  15009. function textLayout(s) {
  15010. s.call(Drawing.font, font)
  15011. .attr({
  15012. 'text-anchor': {
  15013. left: 'start',
  15014. right: 'end'
  15015. }[options.align] || 'middle'
  15016. });
  15017. svgTextUtils.convertToTspans(s, gd, drawGraphicalElements);
  15018. return s;
  15019. }
  15020. function drawGraphicalElements() {
  15021. // if the text has *only* a link, make the whole box into a link
  15022. var anchor3 = annText.selectAll('a');
  15023. if(anchor3.size() === 1 && anchor3.text() === annText.text()) {
  15024. var wholeLink = annTextGroupInner.insert('a', ':first-child').attr({
  15025. 'xlink:xlink:href': anchor3.attr('xlink:href'),
  15026. 'xlink:xlink:show': anchor3.attr('xlink:show')
  15027. })
  15028. .style({cursor: 'pointer'});
  15029. wholeLink.node().appendChild(annTextBG.node());
  15030. }
  15031. var mathjaxGroup = annTextGroupInner.select('.annotation-text-math-group');
  15032. var hasMathjax = !mathjaxGroup.empty();
  15033. var anntextBB = Drawing.bBox(
  15034. (hasMathjax ? mathjaxGroup : annText).node());
  15035. var textWidth = anntextBB.width;
  15036. var textHeight = anntextBB.height;
  15037. var annWidth = options.width || textWidth;
  15038. var annHeight = options.height || textHeight;
  15039. var outerWidth = Math.round(annWidth + 2 * borderfull);
  15040. var outerHeight = Math.round(annHeight + 2 * borderfull);
  15041. function shiftFraction(v, anchor) {
  15042. if(anchor === 'auto') {
  15043. if(v < 1 / 3) anchor = 'left';
  15044. else if(v > 2 / 3) anchor = 'right';
  15045. else anchor = 'center';
  15046. }
  15047. return {
  15048. center: 0,
  15049. middle: 0,
  15050. left: 0.5,
  15051. bottom: -0.5,
  15052. right: -0.5,
  15053. top: 0.5
  15054. }[anchor];
  15055. }
  15056. var annotationIsOffscreen = false;
  15057. var letters = ['x', 'y'];
  15058. for(var i = 0; i < letters.length; i++) {
  15059. var axLetter = letters[i];
  15060. var axRef = options[axLetter + 'ref'] || axLetter;
  15061. var tailRef = options['a' + axLetter + 'ref'];
  15062. var ax = {x: xa, y: ya}[axLetter];
  15063. var dimAngle = (textangle + (axLetter === 'x' ? 0 : -90)) * Math.PI / 180;
  15064. // note that these two can be either positive or negative
  15065. var annSizeFromWidth = outerWidth * Math.cos(dimAngle);
  15066. var annSizeFromHeight = outerHeight * Math.sin(dimAngle);
  15067. // but this one is the positive total size
  15068. var annSize = Math.abs(annSizeFromWidth) + Math.abs(annSizeFromHeight);
  15069. var anchor = options[axLetter + 'anchor'];
  15070. var overallShift = options[axLetter + 'shift'] * (axLetter === 'x' ? 1 : -1);
  15071. var posPx = annPosPx[axLetter];
  15072. var basePx;
  15073. var textPadShift;
  15074. var alignPosition;
  15075. var autoAlignFraction;
  15076. var textShift;
  15077. /*
  15078. * calculate the *primary* pixel position
  15079. * which is the arrowhead if there is one,
  15080. * otherwise the text anchor point
  15081. */
  15082. if(ax) {
  15083. // check if annotation is off screen, to bypass DOM manipulations
  15084. var posFraction = ax.r2fraction(options[axLetter]);
  15085. if(posFraction < 0 || posFraction > 1) {
  15086. if(tailRef === axRef) {
  15087. posFraction = ax.r2fraction(options['a' + axLetter]);
  15088. if(posFraction < 0 || posFraction > 1) {
  15089. annotationIsOffscreen = true;
  15090. }
  15091. } else {
  15092. annotationIsOffscreen = true;
  15093. }
  15094. }
  15095. basePx = ax._offset + ax.r2p(options[axLetter]);
  15096. autoAlignFraction = 0.5;
  15097. }
  15098. else {
  15099. if(axLetter === 'x') {
  15100. alignPosition = options[axLetter];
  15101. basePx = gs.l + gs.w * alignPosition;
  15102. }
  15103. else {
  15104. alignPosition = 1 - options[axLetter];
  15105. basePx = gs.t + gs.h * alignPosition;
  15106. }
  15107. autoAlignFraction = options.showarrow ? 0.5 : alignPosition;
  15108. }
  15109. // now translate this into pixel positions of head, tail, and text
  15110. // as well as paddings for autorange
  15111. if(options.showarrow) {
  15112. posPx.head = basePx;
  15113. var arrowLength = options['a' + axLetter];
  15114. // with an arrow, the text rotates around the anchor point
  15115. textShift = annSizeFromWidth * shiftFraction(0.5, options.xanchor) -
  15116. annSizeFromHeight * shiftFraction(0.5, options.yanchor);
  15117. if(tailRef === axRef) {
  15118. posPx.tail = ax._offset + ax.r2p(arrowLength);
  15119. // tail is data-referenced: autorange pads the text in px from the tail
  15120. textPadShift = textShift;
  15121. }
  15122. else {
  15123. posPx.tail = basePx + arrowLength;
  15124. // tail is specified in px from head, so autorange also pads vs head
  15125. textPadShift = textShift + arrowLength;
  15126. }
  15127. posPx.text = posPx.tail + textShift;
  15128. // constrain pixel/paper referenced so the draggers are at least
  15129. // partially visible
  15130. var maxPx = fullLayout[(axLetter === 'x') ? 'width' : 'height'];
  15131. if(axRef === 'paper') {
  15132. posPx.head = Lib.constrain(posPx.head, 1, maxPx - 1);
  15133. }
  15134. if(tailRef === 'pixel') {
  15135. var shiftPlus = -Math.max(posPx.tail - 3, posPx.text);
  15136. var shiftMinus = Math.min(posPx.tail + 3, posPx.text) - maxPx;
  15137. if(shiftPlus > 0) {
  15138. posPx.tail += shiftPlus;
  15139. posPx.text += shiftPlus;
  15140. }
  15141. else if(shiftMinus > 0) {
  15142. posPx.tail -= shiftMinus;
  15143. posPx.text -= shiftMinus;
  15144. }
  15145. }
  15146. posPx.tail += overallShift;
  15147. posPx.head += overallShift;
  15148. }
  15149. else {
  15150. // with no arrow, the text rotates and *then* we put the anchor
  15151. // relative to the new bounding box
  15152. textShift = annSize * shiftFraction(autoAlignFraction, anchor);
  15153. textPadShift = textShift;
  15154. posPx.text = basePx + textShift;
  15155. }
  15156. posPx.text += overallShift;
  15157. textShift += overallShift;
  15158. textPadShift += overallShift;
  15159. // padplus/minus are used by autorange
  15160. options['_' + axLetter + 'padplus'] = (annSize / 2) + textPadShift;
  15161. options['_' + axLetter + 'padminus'] = (annSize / 2) - textPadShift;
  15162. // size/shift are used during dragging
  15163. options['_' + axLetter + 'size'] = annSize;
  15164. options['_' + axLetter + 'shift'] = textShift;
  15165. }
  15166. // We have everything we need for calcAutorange at this point,
  15167. // we can safely exit - unless we're currently dragging the plot
  15168. if(!gd._dragging && annotationIsOffscreen) {
  15169. annTextGroupInner.remove();
  15170. return;
  15171. }
  15172. var xShift = 0;
  15173. var yShift = 0;
  15174. if(options.align !== 'left') {
  15175. xShift = (annWidth - textWidth) * (options.align === 'center' ? 0.5 : 1);
  15176. }
  15177. if(options.valign !== 'top') {
  15178. yShift = (annHeight - textHeight) * (options.valign === 'middle' ? 0.5 : 1);
  15179. }
  15180. if(hasMathjax) {
  15181. mathjaxGroup.select('svg').attr({
  15182. x: borderfull + xShift - 1,
  15183. y: borderfull + yShift
  15184. })
  15185. .call(Drawing.setClipUrl, isSizeConstrained ? annClipID : null, gd);
  15186. }
  15187. else {
  15188. var texty = borderfull + yShift - anntextBB.top;
  15189. var textx = borderfull + xShift - anntextBB.left;
  15190. annText.call(svgTextUtils.positionText, textx, texty)
  15191. .call(Drawing.setClipUrl, isSizeConstrained ? annClipID : null, gd);
  15192. }
  15193. annTextClip.select('rect').call(Drawing.setRect, borderfull, borderfull,
  15194. annWidth, annHeight);
  15195. annTextBG.call(Drawing.setRect, borderwidth / 2, borderwidth / 2,
  15196. outerWidth - borderwidth, outerHeight - borderwidth);
  15197. annTextGroupInner.call(Drawing.setTranslate,
  15198. Math.round(annPosPx.x.text - outerWidth / 2),
  15199. Math.round(annPosPx.y.text - outerHeight / 2));
  15200. /*
  15201. * rotate text and background
  15202. * we already calculated the text center position *as rotated*
  15203. * because we needed that for autoranging anyway, so now whether
  15204. * we have an arrow or not, we rotate about the text center.
  15205. */
  15206. annTextGroup.attr({transform: 'rotate(' + textangle + ',' +
  15207. annPosPx.x.text + ',' + annPosPx.y.text + ')'});
  15208. /*
  15209. * add the arrow
  15210. * uses options[arrowwidth,arrowcolor,arrowhead] for styling
  15211. * dx and dy are normally zero, but when you are dragging the textbox
  15212. * while the head stays put, dx and dy are the pixel offsets
  15213. */
  15214. var drawArrow = function(dx, dy) {
  15215. annGroup
  15216. .selectAll('.annotation-arrow-g')
  15217. .remove();
  15218. var headX = annPosPx.x.head;
  15219. var headY = annPosPx.y.head;
  15220. var tailX = annPosPx.x.tail + dx;
  15221. var tailY = annPosPx.y.tail + dy;
  15222. var textX = annPosPx.x.text + dx;
  15223. var textY = annPosPx.y.text + dy;
  15224. // find the edge of the text box, where we'll start the arrow:
  15225. // create transform matrix to rotate the text box corners
  15226. var transform = Lib.rotationXYMatrix(textangle, textX, textY);
  15227. var applyTransform = Lib.apply2DTransform(transform);
  15228. var applyTransform2 = Lib.apply2DTransform2(transform);
  15229. // calculate and transform bounding box
  15230. var width = +annTextBG.attr('width');
  15231. var height = +annTextBG.attr('height');
  15232. var xLeft = textX - 0.5 * width;
  15233. var xRight = xLeft + width;
  15234. var yTop = textY - 0.5 * height;
  15235. var yBottom = yTop + height;
  15236. var edges = [
  15237. [xLeft, yTop, xLeft, yBottom],
  15238. [xLeft, yBottom, xRight, yBottom],
  15239. [xRight, yBottom, xRight, yTop],
  15240. [xRight, yTop, xLeft, yTop]
  15241. ].map(applyTransform2);
  15242. // Remove the line if it ends inside the box. Use ray
  15243. // casting for rotated boxes: see which edges intersect a
  15244. // line from the arrowhead to far away and reduce with xor
  15245. // to get the parity of the number of intersections.
  15246. if(edges.reduce(function(a, x) {
  15247. return a ^
  15248. !!Lib.segmentsIntersect(headX, headY, headX + 1e6, headY + 1e6,
  15249. x[0], x[1], x[2], x[3]);
  15250. }, false)) {
  15251. // no line or arrow - so quit drawArrow now
  15252. return;
  15253. }
  15254. edges.forEach(function(x) {
  15255. var p = Lib.segmentsIntersect(tailX, tailY, headX, headY,
  15256. x[0], x[1], x[2], x[3]);
  15257. if(p) {
  15258. tailX = p.x;
  15259. tailY = p.y;
  15260. }
  15261. });
  15262. var strokewidth = options.arrowwidth;
  15263. var arrowColor = options.arrowcolor;
  15264. var arrowSide = options.arrowside;
  15265. var arrowGroup = annGroup.append('g')
  15266. .style({opacity: Color.opacity(arrowColor)})
  15267. .classed('annotation-arrow-g', true);
  15268. var arrow = arrowGroup.append('path')
  15269. .attr('d', 'M' + tailX + ',' + tailY + 'L' + headX + ',' + headY)
  15270. .style('stroke-width', strokewidth + 'px')
  15271. .call(Color.stroke, Color.rgb(arrowColor));
  15272. drawArrowHead(arrow, arrowSide, options);
  15273. // the arrow dragger is a small square right at the head, then a line to the tail,
  15274. // all expanded by a stroke width of 6px plus the arrow line width
  15275. if(edits.annotationPosition && arrow.node().parentNode && !subplotId) {
  15276. var arrowDragHeadX = headX;
  15277. var arrowDragHeadY = headY;
  15278. if(options.standoff) {
  15279. var arrowLength = Math.sqrt(Math.pow(headX - tailX, 2) + Math.pow(headY - tailY, 2));
  15280. arrowDragHeadX += options.standoff * (tailX - headX) / arrowLength;
  15281. arrowDragHeadY += options.standoff * (tailY - headY) / arrowLength;
  15282. }
  15283. var arrowDrag = arrowGroup.append('path')
  15284. .classed('annotation-arrow', true)
  15285. .classed('anndrag', true)
  15286. .classed('cursor-move', true)
  15287. .attr({
  15288. d: 'M3,3H-3V-3H3ZM0,0L' + (tailX - arrowDragHeadX) + ',' + (tailY - arrowDragHeadY),
  15289. transform: 'translate(' + arrowDragHeadX + ',' + arrowDragHeadY + ')'
  15290. })
  15291. .style('stroke-width', (strokewidth + 6) + 'px')
  15292. .call(Color.stroke, 'rgba(0,0,0,0)')
  15293. .call(Color.fill, 'rgba(0,0,0,0)');
  15294. var annx0, anny0;
  15295. // dragger for the arrow & head: translates the whole thing
  15296. // (head/tail/text) all together
  15297. dragElement.init({
  15298. element: arrowDrag.node(),
  15299. gd: gd,
  15300. prepFn: function() {
  15301. var pos = Drawing.getTranslate(annTextGroupInner);
  15302. annx0 = pos.x;
  15303. anny0 = pos.y;
  15304. if(xa && xa.autorange) {
  15305. modifyBase(xa._name + '.autorange', true);
  15306. }
  15307. if(ya && ya.autorange) {
  15308. modifyBase(ya._name + '.autorange', true);
  15309. }
  15310. },
  15311. moveFn: function(dx, dy) {
  15312. var annxy0 = applyTransform(annx0, anny0);
  15313. var xcenter = annxy0[0] + dx;
  15314. var ycenter = annxy0[1] + dy;
  15315. annTextGroupInner.call(Drawing.setTranslate, xcenter, ycenter);
  15316. modifyItem('x', xa ?
  15317. xa.p2r(xa.r2p(options.x) + dx) :
  15318. (options.x + (dx / gs.w)));
  15319. modifyItem('y', ya ?
  15320. ya.p2r(ya.r2p(options.y) + dy) :
  15321. (options.y - (dy / gs.h)));
  15322. if(options.axref === options.xref) {
  15323. modifyItem('ax', xa.p2r(xa.r2p(options.ax) + dx));
  15324. }
  15325. if(options.ayref === options.yref) {
  15326. modifyItem('ay', ya.p2r(ya.r2p(options.ay) + dy));
  15327. }
  15328. arrowGroup.attr('transform', 'translate(' + dx + ',' + dy + ')');
  15329. annTextGroup.attr({
  15330. transform: 'rotate(' + textangle + ',' +
  15331. xcenter + ',' + ycenter + ')'
  15332. });
  15333. },
  15334. doneFn: function() {
  15335. Registry.call('_guiRelayout', gd, getUpdateObj());
  15336. var notesBox = document.querySelector('.js-notes-box-panel');
  15337. if(notesBox) notesBox.redraw(notesBox.selectedObj);
  15338. }
  15339. });
  15340. }
  15341. };
  15342. if(options.showarrow) drawArrow(0, 0);
  15343. // user dragging the annotation (text, not arrow)
  15344. if(editTextPosition) {
  15345. var baseTextTransform;
  15346. // dragger for the textbox: if there's an arrow, just drag the
  15347. // textbox and tail, leave the head untouched
  15348. dragElement.init({
  15349. element: annTextGroupInner.node(),
  15350. gd: gd,
  15351. prepFn: function() {
  15352. baseTextTransform = annTextGroup.attr('transform');
  15353. },
  15354. moveFn: function(dx, dy) {
  15355. var csr = 'pointer';
  15356. if(options.showarrow) {
  15357. if(options.axref === options.xref) {
  15358. modifyItem('ax', xa.p2r(xa.r2p(options.ax) + dx));
  15359. } else {
  15360. modifyItem('ax', options.ax + dx);
  15361. }
  15362. if(options.ayref === options.yref) {
  15363. modifyItem('ay', ya.p2r(ya.r2p(options.ay) + dy));
  15364. } else {
  15365. modifyItem('ay', options.ay + dy);
  15366. }
  15367. drawArrow(dx, dy);
  15368. }
  15369. else if(!subplotId) {
  15370. var xUpdate, yUpdate;
  15371. if(xa) {
  15372. xUpdate = xa.p2r(xa.r2p(options.x) + dx);
  15373. } else {
  15374. var widthFraction = options._xsize / gs.w;
  15375. var xLeft = options.x + (options._xshift - options.xshift) / gs.w - widthFraction / 2;
  15376. xUpdate = dragElement.align(xLeft + dx / gs.w,
  15377. widthFraction, 0, 1, options.xanchor);
  15378. }
  15379. if(ya) {
  15380. yUpdate = ya.p2r(ya.r2p(options.y) + dy);
  15381. } else {
  15382. var heightFraction = options._ysize / gs.h;
  15383. var yBottom = options.y - (options._yshift + options.yshift) / gs.h - heightFraction / 2;
  15384. yUpdate = dragElement.align(yBottom - dy / gs.h,
  15385. heightFraction, 0, 1, options.yanchor);
  15386. }
  15387. modifyItem('x', xUpdate);
  15388. modifyItem('y', yUpdate);
  15389. if(!xa || !ya) {
  15390. csr = dragElement.getCursor(
  15391. xa ? 0.5 : xUpdate,
  15392. ya ? 0.5 : yUpdate,
  15393. options.xanchor, options.yanchor
  15394. );
  15395. }
  15396. }
  15397. else return;
  15398. annTextGroup.attr({
  15399. transform: 'translate(' + dx + ',' + dy + ')' + baseTextTransform
  15400. });
  15401. setCursor(annTextGroupInner, csr);
  15402. },
  15403. doneFn: function() {
  15404. setCursor(annTextGroupInner);
  15405. Registry.call('_guiRelayout', gd, getUpdateObj());
  15406. var notesBox = document.querySelector('.js-notes-box-panel');
  15407. if(notesBox) notesBox.redraw(notesBox.selectedObj);
  15408. }
  15409. });
  15410. }
  15411. }
  15412. if(edits.annotationText) {
  15413. annText.call(svgTextUtils.makeEditable, {delegate: annTextGroupInner, gd: gd})
  15414. .call(textLayout)
  15415. .on('edit', function(_text) {
  15416. options.text = _text;
  15417. this.call(textLayout);
  15418. modifyItem('text', _text);
  15419. if(xa && xa.autorange) {
  15420. modifyBase(xa._name + '.autorange', true);
  15421. }
  15422. if(ya && ya.autorange) {
  15423. modifyBase(ya._name + '.autorange', true);
  15424. }
  15425. Registry.call('_guiRelayout', gd, getUpdateObj());
  15426. });
  15427. }
  15428. else annText.call(textLayout);
  15429. }
  15430. },{"../../lib":168,"../../lib/setcursor":187,"../../lib/svg_text_utils":189,"../../plot_api/plot_template":202,"../../plots/cartesian/axes":212,"../../plots/plots":245,"../../registry":257,"../color":51,"../dragelement":69,"../drawing":72,"../fx":90,"./draw_arrow_head":43,"d3":16}],43:[function(_dereq_,module,exports){
  15431. /**
  15432. * Copyright 2012-2019, Plotly, Inc.
  15433. * All rights reserved.
  15434. *
  15435. * This source code is licensed under the MIT license found in the
  15436. * LICENSE file in the root directory of this source tree.
  15437. */
  15438. 'use strict';
  15439. var d3 = _dereq_('d3');
  15440. var Color = _dereq_('../color');
  15441. var ARROWPATHS = _dereq_('./arrow_paths');
  15442. /**
  15443. * Add arrowhead(s) to a path or line element
  15444. *
  15445. * @param {d3.selection} el3: a d3-selected line or path element
  15446. *
  15447. * @param {string} ends: 'none', 'start', 'end', or 'start+end' for which ends get arrowheads
  15448. *
  15449. * @param {object} options: style information. Must have all the following:
  15450. * @param {number} options.arrowhead: end head style - see ./arrow_paths
  15451. * @param {number} options.startarrowhead: start head style - see ./arrow_paths
  15452. * @param {number} options.arrowsize: relative size of the end head vs line width
  15453. * @param {number} options.startarrowsize: relative size of the start head vs line width
  15454. * @param {number} options.standoff: distance in px to move the end arrow point from its target
  15455. * @param {number} options.startstandoff: distance in px to move the start arrow point from its target
  15456. * @param {number} options.arrowwidth: width of the arrow line
  15457. * @param {string} options.arrowcolor: color of the arrow line, for the head to match
  15458. * Note that the opacity of this color is ignored, as it's assumed the container
  15459. * of both the line and head has opacity applied to it so there isn't greater opacity
  15460. * where they overlap.
  15461. */
  15462. module.exports = function drawArrowHead(el3, ends, options) {
  15463. var el = el3.node();
  15464. var headStyle = ARROWPATHS[options.arrowhead || 0];
  15465. var startHeadStyle = ARROWPATHS[options.startarrowhead || 0];
  15466. var scale = (options.arrowwidth || 1) * (options.arrowsize || 1);
  15467. var startScale = (options.arrowwidth || 1) * (options.startarrowsize || 1);
  15468. var doStart = ends.indexOf('start') >= 0;
  15469. var doEnd = ends.indexOf('end') >= 0;
  15470. var backOff = headStyle.backoff * scale + options.standoff;
  15471. var startBackOff = startHeadStyle.backoff * startScale + options.startstandoff;
  15472. var start, end, startRot, endRot;
  15473. if(el.nodeName === 'line') {
  15474. start = {x: +el3.attr('x1'), y: +el3.attr('y1')};
  15475. end = {x: +el3.attr('x2'), y: +el3.attr('y2')};
  15476. var dx = start.x - end.x;
  15477. var dy = start.y - end.y;
  15478. startRot = Math.atan2(dy, dx);
  15479. endRot = startRot + Math.PI;
  15480. if(backOff && startBackOff) {
  15481. if(backOff + startBackOff > Math.sqrt(dx * dx + dy * dy)) {
  15482. hideLine();
  15483. return;
  15484. }
  15485. }
  15486. if(backOff) {
  15487. if(backOff * backOff > dx * dx + dy * dy) {
  15488. hideLine();
  15489. return;
  15490. }
  15491. var backOffX = backOff * Math.cos(startRot);
  15492. var backOffY = backOff * Math.sin(startRot);
  15493. end.x += backOffX;
  15494. end.y += backOffY;
  15495. el3.attr({x2: end.x, y2: end.y});
  15496. }
  15497. if(startBackOff) {
  15498. if(startBackOff * startBackOff > dx * dx + dy * dy) {
  15499. hideLine();
  15500. return;
  15501. }
  15502. var startBackOffX = startBackOff * Math.cos(startRot);
  15503. var startbackOffY = startBackOff * Math.sin(startRot);
  15504. start.x -= startBackOffX;
  15505. start.y -= startbackOffY;
  15506. el3.attr({x1: start.x, y1: start.y});
  15507. }
  15508. }
  15509. else if(el.nodeName === 'path') {
  15510. var pathlen = el.getTotalLength();
  15511. // using dash to hide the backOff region of the path.
  15512. // if we ever allow dash for the arrow we'll have to
  15513. // do better than this hack... maybe just manually
  15514. // combine the two
  15515. var dashArray = '';
  15516. if(pathlen < backOff + startBackOff) {
  15517. hideLine();
  15518. return;
  15519. }
  15520. var start0 = el.getPointAtLength(0);
  15521. var dstart = el.getPointAtLength(0.1);
  15522. startRot = Math.atan2(start0.y - dstart.y, start0.x - dstart.x);
  15523. start = el.getPointAtLength(Math.min(startBackOff, pathlen));
  15524. dashArray = '0px,' + startBackOff + 'px,';
  15525. var end0 = el.getPointAtLength(pathlen);
  15526. var dend = el.getPointAtLength(pathlen - 0.1);
  15527. endRot = Math.atan2(end0.y - dend.y, end0.x - dend.x);
  15528. end = el.getPointAtLength(Math.max(0, pathlen - backOff));
  15529. var shortening = dashArray ? startBackOff + backOff : backOff;
  15530. dashArray += (pathlen - shortening) + 'px,' + pathlen + 'px';
  15531. el3.style('stroke-dasharray', dashArray);
  15532. }
  15533. function hideLine() { el3.style('stroke-dasharray', '0px,100px'); }
  15534. function drawhead(arrowHeadStyle, p, rot, arrowScale) {
  15535. if(!arrowHeadStyle.path) return;
  15536. if(arrowHeadStyle.noRotate) rot = 0;
  15537. d3.select(el.parentNode).append('path')
  15538. .attr({
  15539. 'class': el3.attr('class'),
  15540. d: arrowHeadStyle.path,
  15541. transform:
  15542. 'translate(' + p.x + ',' + p.y + ')' +
  15543. (rot ? 'rotate(' + (rot * 180 / Math.PI) + ')' : '') +
  15544. 'scale(' + arrowScale + ')'
  15545. })
  15546. .style({
  15547. fill: Color.rgb(options.arrowcolor),
  15548. 'stroke-width': 0
  15549. });
  15550. }
  15551. if(doStart) drawhead(startHeadStyle, start, startRot, startScale);
  15552. if(doEnd) drawhead(headStyle, end, endRot, scale);
  15553. };
  15554. },{"../color":51,"./arrow_paths":35,"d3":16}],44:[function(_dereq_,module,exports){
  15555. /**
  15556. * Copyright 2012-2019, Plotly, Inc.
  15557. * All rights reserved.
  15558. *
  15559. * This source code is licensed under the MIT license found in the
  15560. * LICENSE file in the root directory of this source tree.
  15561. */
  15562. 'use strict';
  15563. var drawModule = _dereq_('./draw');
  15564. var clickModule = _dereq_('./click');
  15565. module.exports = {
  15566. moduleType: 'component',
  15567. name: 'annotations',
  15568. layoutAttributes: _dereq_('./attributes'),
  15569. supplyLayoutDefaults: _dereq_('./defaults'),
  15570. includeBasePlot: _dereq_('../../plots/cartesian/include_components')('annotations'),
  15571. calcAutorange: _dereq_('./calc_autorange'),
  15572. draw: drawModule.draw,
  15573. drawOne: drawModule.drawOne,
  15574. drawRaw: drawModule.drawRaw,
  15575. hasClickToShow: clickModule.hasClickToShow,
  15576. onClick: clickModule.onClick,
  15577. convertCoords: _dereq_('./convert_coords')
  15578. };
  15579. },{"../../plots/cartesian/include_components":223,"./attributes":36,"./calc_autorange":37,"./click":38,"./convert_coords":40,"./defaults":41,"./draw":42}],45:[function(_dereq_,module,exports){
  15580. /**
  15581. * Copyright 2012-2019, Plotly, Inc.
  15582. * All rights reserved.
  15583. *
  15584. * This source code is licensed under the MIT license found in the
  15585. * LICENSE file in the root directory of this source tree.
  15586. */
  15587. 'use strict';
  15588. var annAtts = _dereq_('../annotations/attributes');
  15589. var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
  15590. var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;
  15591. module.exports = overrideAll(templatedArray('annotation', {
  15592. visible: annAtts.visible,
  15593. x: {
  15594. valType: 'any',
  15595. },
  15596. y: {
  15597. valType: 'any',
  15598. },
  15599. z: {
  15600. valType: 'any',
  15601. },
  15602. ax: {
  15603. valType: 'number',
  15604. },
  15605. ay: {
  15606. valType: 'number',
  15607. },
  15608. xanchor: annAtts.xanchor,
  15609. xshift: annAtts.xshift,
  15610. yanchor: annAtts.yanchor,
  15611. yshift: annAtts.yshift,
  15612. text: annAtts.text,
  15613. textangle: annAtts.textangle,
  15614. font: annAtts.font,
  15615. width: annAtts.width,
  15616. height: annAtts.height,
  15617. opacity: annAtts.opacity,
  15618. align: annAtts.align,
  15619. valign: annAtts.valign,
  15620. bgcolor: annAtts.bgcolor,
  15621. bordercolor: annAtts.bordercolor,
  15622. borderpad: annAtts.borderpad,
  15623. borderwidth: annAtts.borderwidth,
  15624. showarrow: annAtts.showarrow,
  15625. arrowcolor: annAtts.arrowcolor,
  15626. arrowhead: annAtts.arrowhead,
  15627. startarrowhead: annAtts.startarrowhead,
  15628. arrowside: annAtts.arrowside,
  15629. arrowsize: annAtts.arrowsize,
  15630. startarrowsize: annAtts.startarrowsize,
  15631. arrowwidth: annAtts.arrowwidth,
  15632. standoff: annAtts.standoff,
  15633. startstandoff: annAtts.startstandoff,
  15634. hovertext: annAtts.hovertext,
  15635. hoverlabel: annAtts.hoverlabel,
  15636. captureevents: annAtts.captureevents,
  15637. // maybes later?
  15638. // clicktoshow: annAtts.clicktoshow,
  15639. // xclick: annAtts.xclick,
  15640. // yclick: annAtts.yclick,
  15641. // not needed!
  15642. // axref: 'pixel'
  15643. // ayref: 'pixel'
  15644. // xref: 'x'
  15645. // yref: 'y
  15646. // zref: 'z'
  15647. }), 'calc', 'from-root');
  15648. },{"../../plot_api/edit_types":195,"../../plot_api/plot_template":202,"../annotations/attributes":36}],46:[function(_dereq_,module,exports){
  15649. /**
  15650. * Copyright 2012-2019, Plotly, Inc.
  15651. * All rights reserved.
  15652. *
  15653. * This source code is licensed under the MIT license found in the
  15654. * LICENSE file in the root directory of this source tree.
  15655. */
  15656. 'use strict';
  15657. var Lib = _dereq_('../../lib');
  15658. var Axes = _dereq_('../../plots/cartesian/axes');
  15659. module.exports = function convert(scene) {
  15660. var fullSceneLayout = scene.fullSceneLayout;
  15661. var anns = fullSceneLayout.annotations;
  15662. for(var i = 0; i < anns.length; i++) {
  15663. mockAnnAxes(anns[i], scene);
  15664. }
  15665. scene.fullLayout._infolayer
  15666. .selectAll('.annotation-' + scene.id)
  15667. .remove();
  15668. };
  15669. function mockAnnAxes(ann, scene) {
  15670. var fullSceneLayout = scene.fullSceneLayout;
  15671. var domain = fullSceneLayout.domain;
  15672. var size = scene.fullLayout._size;
  15673. var base = {
  15674. // this gets fill in on render
  15675. pdata: null,
  15676. // to get setConvert to not execute cleanly
  15677. type: 'linear',
  15678. // don't try to update them on `editable: true`
  15679. autorange: false,
  15680. // set infinite range so that annotation draw routine
  15681. // does not try to remove 'outside-range' annotations,
  15682. // this case is handled in the render loop
  15683. range: [-Infinity, Infinity]
  15684. };
  15685. ann._xa = {};
  15686. Lib.extendFlat(ann._xa, base);
  15687. Axes.setConvert(ann._xa);
  15688. ann._xa._offset = size.l + domain.x[0] * size.w;
  15689. ann._xa.l2p = function() {
  15690. return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain.x[1] - domain.x[0]);
  15691. };
  15692. ann._ya = {};
  15693. Lib.extendFlat(ann._ya, base);
  15694. Axes.setConvert(ann._ya);
  15695. ann._ya._offset = size.t + (1 - domain.y[1]) * size.h;
  15696. ann._ya.l2p = function() {
  15697. return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain.y[1] - domain.y[0]);
  15698. };
  15699. }
  15700. },{"../../lib":168,"../../plots/cartesian/axes":212}],47:[function(_dereq_,module,exports){
  15701. /**
  15702. * Copyright 2012-2019, Plotly, Inc.
  15703. * All rights reserved.
  15704. *
  15705. * This source code is licensed under the MIT license found in the
  15706. * LICENSE file in the root directory of this source tree.
  15707. */
  15708. 'use strict';
  15709. var Lib = _dereq_('../../lib');
  15710. var Axes = _dereq_('../../plots/cartesian/axes');
  15711. var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');
  15712. var handleAnnotationCommonDefaults = _dereq_('../annotations/common_defaults');
  15713. var attributes = _dereq_('./attributes');
  15714. module.exports = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) {
  15715. handleArrayContainerDefaults(sceneLayoutIn, sceneLayoutOut, {
  15716. name: 'annotations',
  15717. handleItemDefaults: handleAnnotationDefaults,
  15718. fullLayout: opts.fullLayout
  15719. });
  15720. };
  15721. function handleAnnotationDefaults(annIn, annOut, sceneLayout, opts) {
  15722. function coerce(attr, dflt) {
  15723. return Lib.coerce(annIn, annOut, attributes, attr, dflt);
  15724. }
  15725. function coercePosition(axLetter) {
  15726. var axName = axLetter + 'axis';
  15727. // mock in such way that getFromId grabs correct 3D axis
  15728. var gdMock = { _fullLayout: {} };
  15729. gdMock._fullLayout[axName] = sceneLayout[axName];
  15730. return Axes.coercePosition(annOut, gdMock, coerce, axLetter, axLetter, 0.5);
  15731. }
  15732. var visible = coerce('visible');
  15733. if(!visible) return;
  15734. handleAnnotationCommonDefaults(annIn, annOut, opts.fullLayout, coerce);
  15735. coercePosition('x');
  15736. coercePosition('y');
  15737. coercePosition('z');
  15738. // if you have one coordinate you should all three
  15739. Lib.noneOrAll(annIn, annOut, ['x', 'y', 'z']);
  15740. // hard-set here for completeness
  15741. annOut.xref = 'x';
  15742. annOut.yref = 'y';
  15743. annOut.zref = 'z';
  15744. coerce('xanchor');
  15745. coerce('yanchor');
  15746. coerce('xshift');
  15747. coerce('yshift');
  15748. if(annOut.showarrow) {
  15749. annOut.axref = 'pixel';
  15750. annOut.ayref = 'pixel';
  15751. // TODO maybe default values should be bigger than the 2D case?
  15752. coerce('ax', -10);
  15753. coerce('ay', -30);
  15754. // if you have one part of arrow length you should have both
  15755. Lib.noneOrAll(annIn, annOut, ['ax', 'ay']);
  15756. }
  15757. }
  15758. },{"../../lib":168,"../../plots/array_container_defaults":208,"../../plots/cartesian/axes":212,"../annotations/common_defaults":39,"./attributes":45}],48:[function(_dereq_,module,exports){
  15759. /**
  15760. * Copyright 2012-2019, Plotly, Inc.
  15761. * All rights reserved.
  15762. *
  15763. * This source code is licensed under the MIT license found in the
  15764. * LICENSE file in the root directory of this source tree.
  15765. */
  15766. 'use strict';
  15767. var drawRaw = _dereq_('../annotations/draw').drawRaw;
  15768. var project = _dereq_('../../plots/gl3d/project');
  15769. var axLetters = ['x', 'y', 'z'];
  15770. module.exports = function draw(scene) {
  15771. var fullSceneLayout = scene.fullSceneLayout;
  15772. var dataScale = scene.dataScale;
  15773. var anns = fullSceneLayout.annotations;
  15774. for(var i = 0; i < anns.length; i++) {
  15775. var ann = anns[i];
  15776. var annotationIsOffscreen = false;
  15777. for(var j = 0; j < 3; j++) {
  15778. var axLetter = axLetters[j];
  15779. var pos = ann[axLetter];
  15780. var ax = fullSceneLayout[axLetter + 'axis'];
  15781. var posFraction = ax.r2fraction(pos);
  15782. if(posFraction < 0 || posFraction > 1) {
  15783. annotationIsOffscreen = true;
  15784. break;
  15785. }
  15786. }
  15787. if(annotationIsOffscreen) {
  15788. scene.fullLayout._infolayer
  15789. .select('.annotation-' + scene.id + '[data-index="' + i + '"]')
  15790. .remove();
  15791. } else {
  15792. ann._pdata = project(scene.glplot.cameraParams, [
  15793. fullSceneLayout.xaxis.r2l(ann.x) * dataScale[0],
  15794. fullSceneLayout.yaxis.r2l(ann.y) * dataScale[1],
  15795. fullSceneLayout.zaxis.r2l(ann.z) * dataScale[2]
  15796. ]);
  15797. drawRaw(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya);
  15798. }
  15799. }
  15800. };
  15801. },{"../../plots/gl3d/project":242,"../annotations/draw":42}],49:[function(_dereq_,module,exports){
  15802. /**
  15803. * Copyright 2012-2019, Plotly, Inc.
  15804. * All rights reserved.
  15805. *
  15806. * This source code is licensed under the MIT license found in the
  15807. * LICENSE file in the root directory of this source tree.
  15808. */
  15809. 'use strict';
  15810. var Registry = _dereq_('../../registry');
  15811. var Lib = _dereq_('../../lib');
  15812. module.exports = {
  15813. moduleType: 'component',
  15814. name: 'annotations3d',
  15815. schema: {
  15816. subplots: {
  15817. scene: {annotations: _dereq_('./attributes')}
  15818. }
  15819. },
  15820. layoutAttributes: _dereq_('./attributes'),
  15821. handleDefaults: _dereq_('./defaults'),
  15822. includeBasePlot: includeGL3D,
  15823. convert: _dereq_('./convert'),
  15824. draw: _dereq_('./draw')
  15825. };
  15826. function includeGL3D(layoutIn, layoutOut) {
  15827. var GL3D = Registry.subplotsRegistry.gl3d;
  15828. if(!GL3D) return;
  15829. var attrRegex = GL3D.attrRegex;
  15830. var keys = Object.keys(layoutIn);
  15831. for(var i = 0; i < keys.length; i++) {
  15832. var k = keys[i];
  15833. if(attrRegex.test(k) && (layoutIn[k].annotations || []).length) {
  15834. Lib.pushUnique(layoutOut._basePlotModules, GL3D);
  15835. Lib.pushUnique(layoutOut._subplots.gl3d, k);
  15836. }
  15837. }
  15838. }
  15839. },{"../../lib":168,"../../registry":257,"./attributes":45,"./convert":46,"./defaults":47,"./draw":48}],50:[function(_dereq_,module,exports){
  15840. /**
  15841. * Copyright 2012-2019, Plotly, Inc.
  15842. * All rights reserved.
  15843. *
  15844. * This source code is licensed under the MIT license found in the
  15845. * LICENSE file in the root directory of this source tree.
  15846. */
  15847. 'use strict';
  15848. // IMPORTANT - default colors should be in hex for compatibility
  15849. exports.defaults = [
  15850. '#1f77b4', // muted blue
  15851. '#ff7f0e', // safety orange
  15852. '#2ca02c', // cooked asparagus green
  15853. '#d62728', // brick red
  15854. '#9467bd', // muted purple
  15855. '#8c564b', // chestnut brown
  15856. '#e377c2', // raspberry yogurt pink
  15857. '#7f7f7f', // middle gray
  15858. '#bcbd22', // curry yellow-green
  15859. '#17becf' // blue-teal
  15860. ];
  15861. exports.defaultLine = '#444';
  15862. exports.lightLine = '#eee';
  15863. exports.background = '#fff';
  15864. exports.borderLine = '#BEC8D9';
  15865. // with axis.color and Color.interp we aren't using lightLine
  15866. // itself anymore, instead interpolating between axis.color
  15867. // and the background color using tinycolor.mix. lightFraction
  15868. // gives back exactly lightLine if the other colors are defaults.
  15869. exports.lightFraction = 100 * (0xe - 0x4) / (0xf - 0x4);
  15870. },{}],51:[function(_dereq_,module,exports){
  15871. /**
  15872. * Copyright 2012-2019, Plotly, Inc.
  15873. * All rights reserved.
  15874. *
  15875. * This source code is licensed under the MIT license found in the
  15876. * LICENSE file in the root directory of this source tree.
  15877. */
  15878. 'use strict';
  15879. var tinycolor = _dereq_('tinycolor2');
  15880. var isNumeric = _dereq_('fast-isnumeric');
  15881. var color = module.exports = {};
  15882. var colorAttrs = _dereq_('./attributes');
  15883. color.defaults = colorAttrs.defaults;
  15884. var defaultLine = color.defaultLine = colorAttrs.defaultLine;
  15885. color.lightLine = colorAttrs.lightLine;
  15886. var background = color.background = colorAttrs.background;
  15887. /*
  15888. * tinyRGB: turn a tinycolor into an rgb string, but
  15889. * unlike the built-in tinycolor.toRgbString this never includes alpha
  15890. */
  15891. color.tinyRGB = function(tc) {
  15892. var c = tc.toRgb();
  15893. return 'rgb(' + Math.round(c.r) + ', ' +
  15894. Math.round(c.g) + ', ' + Math.round(c.b) + ')';
  15895. };
  15896. color.rgb = function(cstr) { return color.tinyRGB(tinycolor(cstr)); };
  15897. color.opacity = function(cstr) { return cstr ? tinycolor(cstr).getAlpha() : 0; };
  15898. color.addOpacity = function(cstr, op) {
  15899. var c = tinycolor(cstr).toRgb();
  15900. return 'rgba(' + Math.round(c.r) + ', ' +
  15901. Math.round(c.g) + ', ' + Math.round(c.b) + ', ' + op + ')';
  15902. };
  15903. // combine two colors into one apparent color
  15904. // if back has transparency or is missing,
  15905. // color.background is assumed behind it
  15906. color.combine = function(front, back) {
  15907. var fc = tinycolor(front).toRgb();
  15908. if(fc.a === 1) return tinycolor(front).toRgbString();
  15909. var bc = tinycolor(back || background).toRgb();
  15910. var bcflat = bc.a === 1 ? bc : {
  15911. r: 255 * (1 - bc.a) + bc.r * bc.a,
  15912. g: 255 * (1 - bc.a) + bc.g * bc.a,
  15913. b: 255 * (1 - bc.a) + bc.b * bc.a
  15914. };
  15915. var fcflat = {
  15916. r: bcflat.r * (1 - fc.a) + fc.r * fc.a,
  15917. g: bcflat.g * (1 - fc.a) + fc.g * fc.a,
  15918. b: bcflat.b * (1 - fc.a) + fc.b * fc.a
  15919. };
  15920. return tinycolor(fcflat).toRgbString();
  15921. };
  15922. /*
  15923. * Create a color that contrasts with cstr.
  15924. *
  15925. * If cstr is a dark color, we lighten it; if it's light, we darken.
  15926. *
  15927. * If lightAmount / darkAmount are used, we adjust by these percentages,
  15928. * otherwise we go all the way to white or black.
  15929. */
  15930. color.contrast = function(cstr, lightAmount, darkAmount) {
  15931. var tc = tinycolor(cstr);
  15932. if(tc.getAlpha() !== 1) tc = tinycolor(color.combine(cstr, background));
  15933. var newColor = tc.isDark() ?
  15934. (lightAmount ? tc.lighten(lightAmount) : background) :
  15935. (darkAmount ? tc.darken(darkAmount) : defaultLine);
  15936. return newColor.toString();
  15937. };
  15938. color.stroke = function(s, c) {
  15939. var tc = tinycolor(c);
  15940. s.style({'stroke': color.tinyRGB(tc), 'stroke-opacity': tc.getAlpha()});
  15941. };
  15942. color.fill = function(s, c) {
  15943. var tc = tinycolor(c);
  15944. s.style({
  15945. 'fill': color.tinyRGB(tc),
  15946. 'fill-opacity': tc.getAlpha()
  15947. });
  15948. };
  15949. // search container for colors with the deprecated rgb(fractions) format
  15950. // and convert them to rgb(0-255 values)
  15951. color.clean = function(container) {
  15952. if(!container || typeof container !== 'object') return;
  15953. var keys = Object.keys(container);
  15954. var i, j, key, val;
  15955. for(i = 0; i < keys.length; i++) {
  15956. key = keys[i];
  15957. val = container[key];
  15958. // only sanitize keys that end in "color" or "colorscale"
  15959. if(key.substr(key.length - 5) === 'color') {
  15960. if(Array.isArray(val)) {
  15961. for(j = 0; j < val.length; j++) val[j] = cleanOne(val[j]);
  15962. }
  15963. else container[key] = cleanOne(val);
  15964. }
  15965. else if(key.substr(key.length - 10) === 'colorscale' && Array.isArray(val)) {
  15966. // colorscales have the format [[0, color1], [frac, color2], ... [1, colorN]]
  15967. for(j = 0; j < val.length; j++) {
  15968. if(Array.isArray(val[j])) val[j][1] = cleanOne(val[j][1]);
  15969. }
  15970. }
  15971. // recurse into arrays of objects, and plain objects
  15972. else if(Array.isArray(val)) {
  15973. var el0 = val[0];
  15974. if(!Array.isArray(el0) && el0 && typeof el0 === 'object') {
  15975. for(j = 0; j < val.length; j++) color.clean(val[j]);
  15976. }
  15977. }
  15978. else if(val && typeof val === 'object') color.clean(val);
  15979. }
  15980. };
  15981. function cleanOne(val) {
  15982. if(isNumeric(val) || typeof val !== 'string') return val;
  15983. var valTrim = val.trim();
  15984. if(valTrim.substr(0, 3) !== 'rgb') return val;
  15985. var match = valTrim.match(/^rgba?\s*\(([^()]*)\)$/);
  15986. if(!match) return val;
  15987. var parts = match[1].trim().split(/\s*[\s,]\s*/);
  15988. var rgba = valTrim.charAt(3) === 'a' && parts.length === 4;
  15989. if(!rgba && parts.length !== 3) return val;
  15990. for(var i = 0; i < parts.length; i++) {
  15991. if(!parts[i].length) return val;
  15992. parts[i] = Number(parts[i]);
  15993. // all parts must be non-negative numbers
  15994. if(!(parts[i] >= 0)) return val;
  15995. // alpha>1 gets clipped to 1
  15996. if(i === 3) {
  15997. if(parts[i] > 1) parts[i] = 1;
  15998. }
  15999. // r, g, b must be < 1 (ie 1 itself is not allowed)
  16000. else if(parts[i] >= 1) return val;
  16001. }
  16002. var rgbStr = Math.round(parts[0] * 255) + ', ' +
  16003. Math.round(parts[1] * 255) + ', ' +
  16004. Math.round(parts[2] * 255);
  16005. if(rgba) return 'rgba(' + rgbStr + ', ' + parts[3] + ')';
  16006. return 'rgb(' + rgbStr + ')';
  16007. }
  16008. },{"./attributes":50,"fast-isnumeric":18,"tinycolor2":34}],52:[function(_dereq_,module,exports){
  16009. /**
  16010. * Copyright 2012-2019, Plotly, Inc.
  16011. * All rights reserved.
  16012. *
  16013. * This source code is licensed under the MIT license found in the
  16014. * LICENSE file in the root directory of this source tree.
  16015. */
  16016. 'use strict';
  16017. var axesAttrs = _dereq_('../../plots/cartesian/layout_attributes');
  16018. var fontAttrs = _dereq_('../../plots/font_attributes');
  16019. var extendFlat = _dereq_('../../lib/extend').extendFlat;
  16020. var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
  16021. module.exports = overrideAll({
  16022. // TODO: only right is supported currently
  16023. // orient: {
  16024. // valType: 'enumerated',
  16025. //
  16026. // values: ['left', 'right', 'top', 'bottom'],
  16027. // dflt: 'right',
  16028. //
  16029. // },
  16030. thicknessmode: {
  16031. valType: 'enumerated',
  16032. values: ['fraction', 'pixels'],
  16033. dflt: 'pixels',
  16034. },
  16035. thickness: {
  16036. valType: 'number',
  16037. min: 0,
  16038. dflt: 30,
  16039. },
  16040. lenmode: {
  16041. valType: 'enumerated',
  16042. values: ['fraction', 'pixels'],
  16043. dflt: 'fraction',
  16044. },
  16045. len: {
  16046. valType: 'number',
  16047. min: 0,
  16048. dflt: 1,
  16049. },
  16050. x: {
  16051. valType: 'number',
  16052. dflt: 1.02,
  16053. min: -2,
  16054. max: 3,
  16055. },
  16056. xanchor: {
  16057. valType: 'enumerated',
  16058. values: ['left', 'center', 'right'],
  16059. dflt: 'left',
  16060. },
  16061. xpad: {
  16062. valType: 'number',
  16063. min: 0,
  16064. dflt: 10,
  16065. },
  16066. y: {
  16067. valType: 'number',
  16068. dflt: 0.5,
  16069. min: -2,
  16070. max: 3,
  16071. },
  16072. yanchor: {
  16073. valType: 'enumerated',
  16074. values: ['top', 'middle', 'bottom'],
  16075. dflt: 'middle',
  16076. },
  16077. ypad: {
  16078. valType: 'number',
  16079. min: 0,
  16080. dflt: 10,
  16081. },
  16082. // a possible line around the bar itself
  16083. outlinecolor: axesAttrs.linecolor,
  16084. outlinewidth: axesAttrs.linewidth,
  16085. // Should outlinewidth have {dflt: 0} ?
  16086. // another possible line outside the padding and tick labels
  16087. bordercolor: axesAttrs.linecolor,
  16088. borderwidth: {
  16089. valType: 'number',
  16090. min: 0,
  16091. dflt: 0,
  16092. },
  16093. bgcolor: {
  16094. valType: 'color',
  16095. dflt: 'rgba(0,0,0,0)',
  16096. },
  16097. // tick and title properties named and function exactly as in axes
  16098. tickmode: axesAttrs.tickmode,
  16099. nticks: axesAttrs.nticks,
  16100. tick0: axesAttrs.tick0,
  16101. dtick: axesAttrs.dtick,
  16102. tickvals: axesAttrs.tickvals,
  16103. ticktext: axesAttrs.ticktext,
  16104. ticks: extendFlat({}, axesAttrs.ticks, {dflt: ''}),
  16105. ticklen: axesAttrs.ticklen,
  16106. tickwidth: axesAttrs.tickwidth,
  16107. tickcolor: axesAttrs.tickcolor,
  16108. showticklabels: axesAttrs.showticklabels,
  16109. tickfont: fontAttrs({
  16110. }),
  16111. tickangle: axesAttrs.tickangle,
  16112. tickformat: axesAttrs.tickformat,
  16113. tickformatstops: axesAttrs.tickformatstops,
  16114. tickprefix: axesAttrs.tickprefix,
  16115. showtickprefix: axesAttrs.showtickprefix,
  16116. ticksuffix: axesAttrs.ticksuffix,
  16117. showticksuffix: axesAttrs.showticksuffix,
  16118. separatethousands: axesAttrs.separatethousands,
  16119. exponentformat: axesAttrs.exponentformat,
  16120. showexponent: axesAttrs.showexponent,
  16121. title: {
  16122. text: {
  16123. valType: 'string',
  16124. },
  16125. font: fontAttrs({
  16126. }),
  16127. side: {
  16128. valType: 'enumerated',
  16129. values: ['right', 'top', 'bottom'],
  16130. dflt: 'top',
  16131. }
  16132. },
  16133. _deprecated: {
  16134. title: {
  16135. valType: 'string',
  16136. },
  16137. titlefont: fontAttrs({
  16138. }),
  16139. titleside: {
  16140. valType: 'enumerated',
  16141. values: ['right', 'top', 'bottom'],
  16142. dflt: 'top',
  16143. }
  16144. }
  16145. }, 'colorbars', 'from-root');
  16146. },{"../../lib/extend":162,"../../plot_api/edit_types":195,"../../plots/cartesian/layout_attributes":225,"../../plots/font_attributes":239}],53:[function(_dereq_,module,exports){
  16147. /**
  16148. * Copyright 2012-2019, Plotly, Inc.
  16149. * All rights reserved.
  16150. *
  16151. * This source code is licensed under the MIT license found in the
  16152. * LICENSE file in the root directory of this source tree.
  16153. */
  16154. 'use strict';
  16155. var drawColorbar = _dereq_('./draw');
  16156. var flipScale = _dereq_('../colorscale/helpers').flipScale;
  16157. /**
  16158. * connectColorbar: create a colorbar from a trace, using its module to
  16159. * describe the connection.
  16160. *
  16161. * @param {DOM element} gd
  16162. *
  16163. * @param {Array} cd
  16164. * calcdata entry for this trace. cd[0].trace is the trace itself, and the
  16165. * colorbar object will be stashed in cd[0].t.cb
  16166. *
  16167. * @param {object|function} moduleOpts
  16168. * may be a function(gd, cd) to override the standard handling below. If
  16169. * an object, should have these keys:
  16170. * @param {Optional(string)} moduleOpts.container
  16171. * name of the container inside the trace where the colorbar and colorscale
  16172. * attributes live (ie 'marker', 'line') - omit if they're at the trace root.
  16173. * @param {string} moduleOpts.min
  16174. * name of the attribute holding the value of the minimum color
  16175. * @param {string} moduleOpts.max
  16176. * name of the attribute holding the value of the maximum color
  16177. * @param {Optional(string)} moduleOpts.vals
  16178. * name of the attribute holding the (numeric) color data
  16179. * used only if min/max fail. May be omitted if these are always
  16180. * pre-calculated.
  16181. */
  16182. module.exports = function connectColorbar(gd, cd, moduleOpts) {
  16183. if(typeof moduleOpts === 'function') return moduleOpts(gd, cd);
  16184. var trace = cd[0].trace;
  16185. var cbId = 'cb' + trace.uid;
  16186. moduleOpts = Array.isArray(moduleOpts) ? moduleOpts : [moduleOpts];
  16187. for(var i = 0; i < moduleOpts.length; i++) {
  16188. var containerName = moduleOpts[i].container;
  16189. var container = containerName ? trace[containerName] : trace;
  16190. gd._fullLayout._infolayer.selectAll('.' + cbId).remove();
  16191. if(!container || !container.showscale) continue;
  16192. var cb = cd[0].t.cb = drawColorbar(gd, cbId);
  16193. var scl = container.reversescale ?
  16194. flipScale(container.colorscale) :
  16195. container.colorscale;
  16196. cb.fillgradient(scl)
  16197. .zrange([container[moduleOpts[i].min], container[moduleOpts[i].max]])
  16198. .options(container.colorbar)();
  16199. return;
  16200. }
  16201. };
  16202. },{"../colorscale/helpers":62,"./draw":56}],54:[function(_dereq_,module,exports){
  16203. /**
  16204. * Copyright 2012-2019, Plotly, Inc.
  16205. * All rights reserved.
  16206. *
  16207. * This source code is licensed under the MIT license found in the
  16208. * LICENSE file in the root directory of this source tree.
  16209. */
  16210. 'use strict';
  16211. module.exports = {
  16212. cn: {
  16213. colorbar: 'colorbar',
  16214. cbbg: 'cbbg',
  16215. cbfill: 'cbfill',
  16216. cbfills: 'cbfills',
  16217. cbline: 'cbline',
  16218. cblines: 'cblines',
  16219. cbaxis: 'cbaxis',
  16220. cbtitleunshift: 'cbtitleunshift',
  16221. cbtitle: 'cbtitle',
  16222. cboutline: 'cboutline',
  16223. crisp: 'crisp',
  16224. jsPlaceholder: 'js-placeholder'
  16225. }
  16226. };
  16227. },{}],55:[function(_dereq_,module,exports){
  16228. /**
  16229. * Copyright 2012-2019, Plotly, Inc.
  16230. * All rights reserved.
  16231. *
  16232. * This source code is licensed under the MIT license found in the
  16233. * LICENSE file in the root directory of this source tree.
  16234. */
  16235. 'use strict';
  16236. var Lib = _dereq_('../../lib');
  16237. var Template = _dereq_('../../plot_api/plot_template');
  16238. var handleTickValueDefaults = _dereq_('../../plots/cartesian/tick_value_defaults');
  16239. var handleTickMarkDefaults = _dereq_('../../plots/cartesian/tick_mark_defaults');
  16240. var handleTickLabelDefaults = _dereq_('../../plots/cartesian/tick_label_defaults');
  16241. var attributes = _dereq_('./attributes');
  16242. module.exports = function colorbarDefaults(containerIn, containerOut, layout) {
  16243. var colorbarOut = Template.newContainer(containerOut, 'colorbar');
  16244. var colorbarIn = containerIn.colorbar || {};
  16245. function coerce(attr, dflt) {
  16246. return Lib.coerce(colorbarIn, colorbarOut, attributes, attr, dflt);
  16247. }
  16248. var thicknessmode = coerce('thicknessmode');
  16249. coerce('thickness', (thicknessmode === 'fraction') ?
  16250. 30 / (layout.width - layout.margin.l - layout.margin.r) :
  16251. 30
  16252. );
  16253. var lenmode = coerce('lenmode');
  16254. coerce('len', (lenmode === 'fraction') ?
  16255. 1 :
  16256. layout.height - layout.margin.t - layout.margin.b
  16257. );
  16258. coerce('x');
  16259. coerce('xanchor');
  16260. coerce('xpad');
  16261. coerce('y');
  16262. coerce('yanchor');
  16263. coerce('ypad');
  16264. Lib.noneOrAll(colorbarIn, colorbarOut, ['x', 'y']);
  16265. coerce('outlinecolor');
  16266. coerce('outlinewidth');
  16267. coerce('bordercolor');
  16268. coerce('borderwidth');
  16269. coerce('bgcolor');
  16270. handleTickValueDefaults(colorbarIn, colorbarOut, coerce, 'linear');
  16271. var opts = {outerTicks: false, font: layout.font};
  16272. handleTickLabelDefaults(colorbarIn, colorbarOut, coerce, 'linear', opts);
  16273. handleTickMarkDefaults(colorbarIn, colorbarOut, coerce, 'linear', opts);
  16274. coerce('title.text', layout._dfltTitle.colorbar);
  16275. Lib.coerceFont(coerce, 'title.font', layout.font);
  16276. coerce('title.side');
  16277. };
  16278. },{"../../lib":168,"../../plot_api/plot_template":202,"../../plots/cartesian/tick_label_defaults":232,"../../plots/cartesian/tick_mark_defaults":233,"../../plots/cartesian/tick_value_defaults":234,"./attributes":52}],56:[function(_dereq_,module,exports){
  16279. /**
  16280. * Copyright 2012-2019, Plotly, Inc.
  16281. * All rights reserved.
  16282. *
  16283. * This source code is licensed under the MIT license found in the
  16284. * LICENSE file in the root directory of this source tree.
  16285. */
  16286. 'use strict';
  16287. var d3 = _dereq_('d3');
  16288. var tinycolor = _dereq_('tinycolor2');
  16289. var Plots = _dereq_('../../plots/plots');
  16290. var Registry = _dereq_('../../registry');
  16291. var Axes = _dereq_('../../plots/cartesian/axes');
  16292. var dragElement = _dereq_('../dragelement');
  16293. var Lib = _dereq_('../../lib');
  16294. var extendFlat = _dereq_('../../lib/extend').extendFlat;
  16295. var setCursor = _dereq_('../../lib/setcursor');
  16296. var Drawing = _dereq_('../drawing');
  16297. var Color = _dereq_('../color');
  16298. var Titles = _dereq_('../titles');
  16299. var svgTextUtils = _dereq_('../../lib/svg_text_utils');
  16300. var alignmentConstants = _dereq_('../../constants/alignment');
  16301. var LINE_SPACING = alignmentConstants.LINE_SPACING;
  16302. var FROM_TL = alignmentConstants.FROM_TL;
  16303. var FROM_BR = alignmentConstants.FROM_BR;
  16304. var handleAxisDefaults = _dereq_('../../plots/cartesian/axis_defaults');
  16305. var handleAxisPositionDefaults = _dereq_('../../plots/cartesian/position_defaults');
  16306. var axisLayoutAttrs = _dereq_('../../plots/cartesian/layout_attributes');
  16307. var attributes = _dereq_('./attributes');
  16308. var cn = _dereq_('./constants').cn;
  16309. module.exports = function draw(gd, id) {
  16310. // opts: options object, containing everything from attributes
  16311. // plus a few others that are the equivalent of the colorbar "data"
  16312. var opts = {};
  16313. for(var k in attributes) {
  16314. opts[k] = null;
  16315. }
  16316. // fillcolor can be a d3 scale, domain is z values, range is colors
  16317. // or leave it out for no fill,
  16318. // or set to a string constant for single-color fill
  16319. opts.fillcolor = null;
  16320. // line.color has the same options as fillcolor
  16321. opts.line = {color: null, width: null, dash: null};
  16322. // levels of lines to draw.
  16323. // note that this DOES NOT determine the extent of the bar
  16324. // that's given by the domain of fillcolor
  16325. // (or line.color if no fillcolor domain)
  16326. opts.levels = {start: null, end: null, size: null};
  16327. // separate fill levels (for example, heatmap coloring of a
  16328. // contour map) if this is omitted, fillcolors will be
  16329. // evaluated halfway between levels
  16330. opts.filllevels = null;
  16331. // for continuous colorscales: fill with a gradient instead of explicit levels
  16332. // value should be the colorscale [[0, c0], [v1, c1], ..., [1, cEnd]]
  16333. opts.fillgradient = null;
  16334. // when using a gradient, we need the data range specified separately
  16335. opts.zrange = null;
  16336. function component() {
  16337. var fullLayout = gd._fullLayout;
  16338. var gs = fullLayout._size;
  16339. if((typeof opts.fillcolor !== 'function') &&
  16340. (typeof opts.line.color !== 'function') &&
  16341. !opts.fillgradient) {
  16342. fullLayout._infolayer.selectAll('g.' + id).remove();
  16343. return;
  16344. }
  16345. var zrange = opts.zrange || (d3.extent(((typeof opts.fillcolor === 'function') ?
  16346. opts.fillcolor : opts.line.color).domain()));
  16347. var linelevels = [];
  16348. var filllevels = [];
  16349. var linecolormap = typeof opts.line.color === 'function' ?
  16350. opts.line.color : function() { return opts.line.color; };
  16351. var fillcolormap = typeof opts.fillcolor === 'function' ?
  16352. opts.fillcolor : function() { return opts.fillcolor; };
  16353. var l;
  16354. var i;
  16355. var l0 = opts.levels.end + opts.levels.size / 100;
  16356. var ls = opts.levels.size;
  16357. var zr0 = (1.001 * zrange[0] - 0.001 * zrange[1]);
  16358. var zr1 = (1.001 * zrange[1] - 0.001 * zrange[0]);
  16359. for(i = 0; i < 1e5; i++) {
  16360. l = opts.levels.start + i * ls;
  16361. if(ls > 0 ? (l >= l0) : (l <= l0)) break;
  16362. if(l > zr0 && l < zr1) linelevels.push(l);
  16363. }
  16364. if(opts.fillgradient) {
  16365. filllevels = [0];
  16366. }
  16367. else if(typeof opts.fillcolor === 'function') {
  16368. if(opts.filllevels) {
  16369. l0 = opts.filllevels.end + opts.filllevels.size / 100;
  16370. ls = opts.filllevels.size;
  16371. for(i = 0; i < 1e5; i++) {
  16372. l = opts.filllevels.start + i * ls;
  16373. if(ls > 0 ? (l >= l0) : (l <= l0)) break;
  16374. if(l > zrange[0] && l < zrange[1]) filllevels.push(l);
  16375. }
  16376. }
  16377. else {
  16378. filllevels = linelevels.map(function(v) {
  16379. return v - opts.levels.size / 2;
  16380. });
  16381. filllevels.push(filllevels[filllevels.length - 1] +
  16382. opts.levels.size);
  16383. }
  16384. }
  16385. else if(opts.fillcolor && typeof opts.fillcolor === 'string') {
  16386. // doesn't matter what this value is, with a single value
  16387. // we'll make a single fill rect covering the whole bar
  16388. filllevels = [0];
  16389. }
  16390. if(opts.levels.size < 0) {
  16391. linelevels.reverse();
  16392. filllevels.reverse();
  16393. }
  16394. // now make a Plotly Axes object to scale with and draw ticks
  16395. // TODO: does not support orientation other than right
  16396. // we calculate pixel sizes based on the specified graph size,
  16397. // not the actual (in case something pushed the margins around)
  16398. // which is a little odd but avoids an odd iterative effect
  16399. // when the colorbar itself is pushing the margins.
  16400. // but then the fractional size is calculated based on the
  16401. // actual graph size, so that the axes will size correctly.
  16402. var plotHeight = gs.h;
  16403. var plotWidth = gs.w;
  16404. var thickPx = Math.round(opts.thickness * (opts.thicknessmode === 'fraction' ? plotWidth : 1));
  16405. var thickFrac = thickPx / gs.w;
  16406. var lenPx = Math.round(opts.len * (opts.lenmode === 'fraction' ? plotHeight : 1));
  16407. var lenFrac = lenPx / gs.h;
  16408. var xpadFrac = opts.xpad / gs.w;
  16409. var yExtraPx = (opts.borderwidth + opts.outlinewidth) / 2;
  16410. var ypadFrac = opts.ypad / gs.h;
  16411. // x positioning: do it initially just for left anchor,
  16412. // then fix at the end (since we don't know the width yet)
  16413. var xLeft = Math.round(opts.x * gs.w + opts.xpad);
  16414. // for dragging... this is getting a little muddled...
  16415. var xLeftFrac = opts.x - thickFrac * ({middle: 0.5, right: 1}[opts.xanchor]||0);
  16416. // y positioning we can do correctly from the start
  16417. var yBottomFrac = opts.y + lenFrac * (({top: -0.5, bottom: 0.5}[opts.yanchor] || 0) - 0.5);
  16418. var yBottomPx = Math.round(gs.h * (1 - yBottomFrac));
  16419. var yTopPx = yBottomPx - lenPx;
  16420. var titleEl;
  16421. var cbAxisIn = {
  16422. type: 'linear',
  16423. range: zrange,
  16424. tickmode: opts.tickmode,
  16425. nticks: opts.nticks,
  16426. tick0: opts.tick0,
  16427. dtick: opts.dtick,
  16428. tickvals: opts.tickvals,
  16429. ticktext: opts.ticktext,
  16430. ticks: opts.ticks,
  16431. ticklen: opts.ticklen,
  16432. tickwidth: opts.tickwidth,
  16433. tickcolor: opts.tickcolor,
  16434. showticklabels: opts.showticklabels,
  16435. tickfont: opts.tickfont,
  16436. tickangle: opts.tickangle,
  16437. tickformat: opts.tickformat,
  16438. exponentformat: opts.exponentformat,
  16439. separatethousands: opts.separatethousands,
  16440. showexponent: opts.showexponent,
  16441. showtickprefix: opts.showtickprefix,
  16442. tickprefix: opts.tickprefix,
  16443. showticksuffix: opts.showticksuffix,
  16444. ticksuffix: opts.ticksuffix,
  16445. title: opts.title,
  16446. showline: true,
  16447. anchor: 'free',
  16448. side: 'right',
  16449. position: 1
  16450. };
  16451. var cbAxisOut = {
  16452. type: 'linear',
  16453. _id: 'y' + id
  16454. };
  16455. var axisOptions = {
  16456. letter: 'y',
  16457. font: fullLayout.font,
  16458. noHover: true,
  16459. noTickson: true,
  16460. calendar: fullLayout.calendar // not really necessary (yet?)
  16461. };
  16462. // Coerce w.r.t. Axes layoutAttributes:
  16463. // re-use axes.js logic without updating _fullData
  16464. function coerce(attr, dflt) {
  16465. return Lib.coerce(cbAxisIn, cbAxisOut, axisLayoutAttrs, attr, dflt);
  16466. }
  16467. // Prepare the Plotly axis object
  16468. handleAxisDefaults(cbAxisIn, cbAxisOut, coerce, axisOptions, fullLayout);
  16469. handleAxisPositionDefaults(cbAxisIn, cbAxisOut, coerce, axisOptions);
  16470. // position can't go in through supplyDefaults
  16471. // because that restricts it to [0,1]
  16472. cbAxisOut.position = opts.x + xpadFrac + thickFrac;
  16473. // save for other callers to access this axis
  16474. component.axis = cbAxisOut;
  16475. if(['top', 'bottom'].indexOf(opts.title.side) !== -1) {
  16476. cbAxisOut.title.side = opts.title.side;
  16477. cbAxisOut.titlex = opts.x + xpadFrac;
  16478. cbAxisOut.titley = yBottomFrac +
  16479. (opts.title.side === 'top' ? lenFrac - ypadFrac : ypadFrac);
  16480. }
  16481. if(opts.line.color && opts.tickmode === 'auto') {
  16482. cbAxisOut.tickmode = 'linear';
  16483. cbAxisOut.tick0 = opts.levels.start;
  16484. var dtick = opts.levels.size;
  16485. // expand if too many contours, so we don't get too many ticks
  16486. var autoNtick = Lib.constrain((yBottomPx - yTopPx) / 50, 4, 15) + 1;
  16487. var dtFactor = (zrange[1] - zrange[0]) / ((opts.nticks || autoNtick) * dtick);
  16488. if(dtFactor > 1) {
  16489. var dtexp = Math.pow(10, Math.floor(
  16490. Math.log(dtFactor) / Math.LN10));
  16491. dtick *= dtexp * Lib.roundUp(dtFactor / dtexp, [2, 5, 10]);
  16492. // if the contours are at round multiples, reset tick0
  16493. // so they're still at round multiples. Otherwise,
  16494. // keep the first label on the first contour level
  16495. if((Math.abs(opts.levels.start) /
  16496. opts.levels.size + 1e-6) % 1 < 2e-6) {
  16497. cbAxisOut.tick0 = 0;
  16498. }
  16499. }
  16500. cbAxisOut.dtick = dtick;
  16501. }
  16502. // set domain after init, because we may want to
  16503. // allow it outside [0,1]
  16504. cbAxisOut.domain = [
  16505. yBottomFrac + ypadFrac,
  16506. yBottomFrac + lenFrac - ypadFrac
  16507. ];
  16508. cbAxisOut.setScale();
  16509. // now draw the elements
  16510. var container = Lib.ensureSingle(fullLayout._infolayer, 'g', id, function(s) {
  16511. s.classed(cn.colorbar, true)
  16512. .each(function() {
  16513. var s = d3.select(this);
  16514. s.append('rect').classed(cn.cbbg, true);
  16515. s.append('g').classed(cn.cbfills, true);
  16516. s.append('g').classed(cn.cblines, true);
  16517. s.append('g').classed(cn.cbaxis, true).classed(cn.crisp, true);
  16518. s.append('g').classed(cn.cbtitleunshift, true)
  16519. .append('g').classed(cn.cbtitle, true);
  16520. s.append('rect').classed(cn.cboutline, true);
  16521. s.select('.cbtitle').datum(0);
  16522. });
  16523. });
  16524. container.attr('transform', 'translate(' + Math.round(gs.l) +
  16525. ',' + Math.round(gs.t) + ')');
  16526. // TODO: this opposite transform is a hack until we make it
  16527. // more rational which items get this offset
  16528. var titleCont = container.select('.cbtitleunshift')
  16529. .attr('transform', 'translate(-' +
  16530. Math.round(gs.l) + ',-' +
  16531. Math.round(gs.t) + ')');
  16532. var axisLayer = container.select('.cbaxis');
  16533. var titleHeight = 0;
  16534. if(['top', 'bottom'].indexOf(opts.title.side) !== -1) {
  16535. // draw the title so we know how much room it needs
  16536. // when we squish the axis. This one only applies to
  16537. // top or bottom titles, not right side.
  16538. var x = gs.l + (opts.x + xpadFrac) * gs.w;
  16539. var fontSize = cbAxisOut.title.font.size;
  16540. var y;
  16541. if(opts.title.side === 'top') {
  16542. y = (1 - (yBottomFrac + lenFrac - ypadFrac)) * gs.h +
  16543. gs.t + 3 + fontSize * 0.75;
  16544. }
  16545. else {
  16546. y = (1 - (yBottomFrac + ypadFrac)) * gs.h +
  16547. gs.t - 3 - fontSize * 0.25;
  16548. }
  16549. drawTitle(cbAxisOut._id + 'title', {
  16550. attributes: {x: x, y: y, 'text-anchor': 'start'}
  16551. });
  16552. }
  16553. function drawAxis() {
  16554. if(['top', 'bottom'].indexOf(opts.title.side) !== -1) {
  16555. // squish the axis top to make room for the title
  16556. var titleGroup = container.select('.cbtitle');
  16557. var titleText = titleGroup.select('text');
  16558. var titleTrans = [-opts.outlinewidth / 2, opts.outlinewidth / 2];
  16559. var mathJaxNode = titleGroup
  16560. .select('.h' + cbAxisOut._id + 'title-math-group')
  16561. .node();
  16562. var lineSize = 15.6;
  16563. if(titleText.node()) {
  16564. lineSize =
  16565. parseInt(titleText.node().style.fontSize, 10) * LINE_SPACING;
  16566. }
  16567. if(mathJaxNode) {
  16568. titleHeight = Drawing.bBox(mathJaxNode).height;
  16569. if(titleHeight > lineSize) {
  16570. // not entirely sure how mathjax is doing
  16571. // vertical alignment, but this seems to work.
  16572. titleTrans[1] -= (titleHeight - lineSize) / 2;
  16573. }
  16574. }
  16575. else if(titleText.node() &&
  16576. !titleText.classed(cn.jsPlaceholder)) {
  16577. titleHeight = Drawing.bBox(titleText.node()).height;
  16578. }
  16579. if(titleHeight) {
  16580. // buffer btwn colorbar and title
  16581. // TODO: configurable
  16582. titleHeight += 5;
  16583. if(opts.title.side === 'top') {
  16584. cbAxisOut.domain[1] -= titleHeight / gs.h;
  16585. titleTrans[1] *= -1;
  16586. }
  16587. else {
  16588. cbAxisOut.domain[0] += titleHeight / gs.h;
  16589. var nlines = svgTextUtils.lineCount(titleText);
  16590. titleTrans[1] += (1 - nlines) * lineSize;
  16591. }
  16592. titleGroup.attr('transform',
  16593. 'translate(' + titleTrans + ')');
  16594. cbAxisOut.setScale();
  16595. }
  16596. }
  16597. container.selectAll('.cbfills,.cblines')
  16598. .attr('transform', 'translate(0,' +
  16599. Math.round(gs.h * (1 - cbAxisOut.domain[1])) + ')');
  16600. axisLayer.attr('transform', 'translate(0,' + Math.round(-gs.t) + ')');
  16601. var fills = container.select('.cbfills')
  16602. .selectAll('rect.cbfill')
  16603. .data(filllevels);
  16604. fills.enter().append('rect')
  16605. .classed(cn.cbfill, true)
  16606. .style('stroke', 'none');
  16607. fills.exit().remove();
  16608. var zBounds = zrange
  16609. .map(cbAxisOut.c2p)
  16610. .map(Math.round)
  16611. .sort(function(a, b) { return a - b; });
  16612. fills.each(function(d, i) {
  16613. var z = [
  16614. (i === 0) ? zrange[0] :
  16615. (filllevels[i] + filllevels[i - 1]) / 2,
  16616. (i === filllevels.length - 1) ? zrange[1] :
  16617. (filllevels[i] + filllevels[i + 1]) / 2
  16618. ]
  16619. .map(cbAxisOut.c2p)
  16620. .map(Math.round);
  16621. // offset the side adjoining the next rectangle so they
  16622. // overlap, to prevent antialiasing gaps
  16623. z[1] = Lib.constrain(z[1] + (z[1] > z[0]) ? 1 : -1, zBounds[0], zBounds[1]);
  16624. // Colorbar cannot currently support opacities so we
  16625. // use an opaque fill even when alpha channels present
  16626. var fillEl = d3.select(this).attr({
  16627. x: xLeft,
  16628. width: Math.max(thickPx, 2),
  16629. y: d3.min(z),
  16630. height: Math.max(d3.max(z) - d3.min(z), 2),
  16631. });
  16632. if(opts.fillgradient) {
  16633. Drawing.gradient(fillEl, gd, id, 'vertical',
  16634. opts.fillgradient, 'fill');
  16635. }
  16636. else {
  16637. // Tinycolor can't handle exponents and
  16638. // at this scale, removing it makes no difference.
  16639. var colorString = fillcolormap(d).replace('e-', '');
  16640. fillEl.attr('fill', tinycolor(colorString).toHexString());
  16641. }
  16642. });
  16643. var lines = container.select('.cblines')
  16644. .selectAll('path.cbline')
  16645. .data(opts.line.color && opts.line.width ?
  16646. linelevels : []);
  16647. lines.enter().append('path')
  16648. .classed(cn.cbline, true);
  16649. lines.exit().remove();
  16650. lines.each(function(d) {
  16651. d3.select(this)
  16652. .attr('d', 'M' + xLeft + ',' +
  16653. (Math.round(cbAxisOut.c2p(d)) + (opts.line.width / 2) % 1) +
  16654. 'h' + thickPx)
  16655. .call(Drawing.lineGroupStyle,
  16656. opts.line.width, linecolormap(d), opts.line.dash);
  16657. });
  16658. // force full redraw of labels and ticks
  16659. axisLayer.selectAll('g.' + cbAxisOut._id + 'tick,path').remove();
  16660. // separate out axis and title drawing,
  16661. // so we don't need such complicated logic in Titles.draw
  16662. // if title is on the top or bottom, we've already drawn it
  16663. // this title call only handles side=right
  16664. return Lib.syncOrAsync([
  16665. function() {
  16666. var shift = xLeft + thickPx +
  16667. (opts.outlinewidth || 0) / 2 - (opts.ticks === 'outside' ? 1 : 0);
  16668. var vals = Axes.calcTicks(cbAxisOut);
  16669. var transFn = Axes.makeTransFn(cbAxisOut);
  16670. var labelFns = Axes.makeLabelFns(cbAxisOut, shift);
  16671. var tickSign = Axes.getTickSigns(cbAxisOut)[2];
  16672. Axes.drawTicks(gd, cbAxisOut, {
  16673. vals: cbAxisOut.ticks === 'inside' ? Axes.clipEnds(cbAxisOut, vals) : vals,
  16674. layer: axisLayer,
  16675. path: Axes.makeTickPath(cbAxisOut, shift, tickSign),
  16676. transFn: transFn
  16677. });
  16678. return Axes.drawLabels(gd, cbAxisOut, {
  16679. vals: vals,
  16680. layer: axisLayer,
  16681. transFn: transFn,
  16682. labelXFn: labelFns.labelXFn,
  16683. labelYFn: labelFns.labelYFn,
  16684. labelAnchorFn: labelFns.labelAnchorFn
  16685. });
  16686. },
  16687. function() {
  16688. if(['top', 'bottom'].indexOf(opts.title.side) === -1) {
  16689. var fontSize = cbAxisOut.title.font.size;
  16690. var y = cbAxisOut._offset + cbAxisOut._length / 2;
  16691. var x = gs.l + (cbAxisOut.position || 0) * gs.w + ((cbAxisOut.side === 'right') ?
  16692. 10 + fontSize * ((cbAxisOut.showticklabels ? 1 : 0.5)) :
  16693. -10 - fontSize * ((cbAxisOut.showticklabels ? 0.5 : 0)));
  16694. // the 'h' + is a hack to get around the fact that
  16695. // convertToTspans rotates any 'y...' class by 90 degrees.
  16696. // TODO: find a better way to control this.
  16697. drawTitle('h' + cbAxisOut._id + 'title', {
  16698. avoid: {
  16699. selection: d3.select(gd).selectAll('g.' + cbAxisOut._id + 'tick'),
  16700. side: opts.title.side,
  16701. offsetLeft: gs.l,
  16702. offsetTop: 0,
  16703. maxShift: fullLayout.width
  16704. },
  16705. attributes: {x: x, y: y, 'text-anchor': 'middle'},
  16706. transform: {rotate: '-90', offset: 0}
  16707. });
  16708. }
  16709. }]);
  16710. }
  16711. function drawTitle(titleClass, titleOpts) {
  16712. var dfltTitleOpts = {
  16713. propContainer: cbAxisOut,
  16714. propName: getPropName('title'),
  16715. traceIndex: getTrace().index,
  16716. placeholder: fullLayout._dfltTitle.colorbar,
  16717. containerGroup: container.select('.cbtitle')
  16718. };
  16719. // this class-to-rotate thing with convertToTspans is
  16720. // getting hackier and hackier... delete groups with the
  16721. // wrong class (in case earlier the colorbar was drawn on
  16722. // a different side, I think?)
  16723. var otherClass = titleClass.charAt(0) === 'h' ?
  16724. titleClass.substr(1) : ('h' + titleClass);
  16725. container.selectAll('.' + otherClass + ',.' + otherClass + '-math-group')
  16726. .remove();
  16727. Titles.draw(gd, titleClass,
  16728. extendFlat(dfltTitleOpts, titleOpts || {}));
  16729. }
  16730. function positionCB() {
  16731. // wait for the axis & title to finish rendering before
  16732. // continuing positioning
  16733. // TODO: why are we redrawing multiple times now with this?
  16734. // I guess autoMargin doesn't like being post-promise?
  16735. var innerWidth = thickPx + opts.outlinewidth / 2 +
  16736. Drawing.bBox(axisLayer.node()).width;
  16737. titleEl = titleCont.select('text');
  16738. if(titleEl.node() && !titleEl.classed(cn.jsPlaceholder)) {
  16739. var mathJaxNode = titleCont
  16740. .select('.h' + cbAxisOut._id + 'title-math-group')
  16741. .node();
  16742. var titleWidth;
  16743. if(mathJaxNode &&
  16744. ['top', 'bottom'].indexOf(opts.title.side) !== -1) {
  16745. titleWidth = Drawing.bBox(mathJaxNode).width;
  16746. }
  16747. else {
  16748. // note: the formula below works for all title sides,
  16749. // (except for top/bottom mathjax, above)
  16750. // but the weird gs.l is because the titleunshift
  16751. // transform gets removed by Drawing.bBox
  16752. titleWidth =
  16753. Drawing.bBox(titleCont.node()).right -
  16754. xLeft - gs.l;
  16755. }
  16756. innerWidth = Math.max(innerWidth, titleWidth);
  16757. }
  16758. var outerwidth = 2 * opts.xpad + innerWidth +
  16759. opts.borderwidth + opts.outlinewidth / 2;
  16760. var outerheight = yBottomPx - yTopPx;
  16761. container.select('.cbbg').attr({
  16762. x: xLeft - opts.xpad -
  16763. (opts.borderwidth + opts.outlinewidth) / 2,
  16764. y: yTopPx - yExtraPx,
  16765. width: Math.max(outerwidth, 2),
  16766. height: Math.max(outerheight + 2 * yExtraPx, 2)
  16767. })
  16768. .call(Color.fill, opts.bgcolor)
  16769. .call(Color.stroke, opts.bordercolor)
  16770. .style({'stroke-width': opts.borderwidth});
  16771. container.selectAll('.cboutline').attr({
  16772. x: xLeft,
  16773. y: yTopPx + opts.ypad +
  16774. (opts.title.side === 'top' ? titleHeight : 0),
  16775. width: Math.max(thickPx, 2),
  16776. height: Math.max(outerheight - 2 * opts.ypad - titleHeight, 2)
  16777. })
  16778. .call(Color.stroke, opts.outlinecolor)
  16779. .style({
  16780. fill: 'None',
  16781. 'stroke-width': opts.outlinewidth
  16782. });
  16783. // fix positioning for xanchor!='left'
  16784. var xoffset = ({center: 0.5, right: 1}[opts.xanchor] || 0) *
  16785. outerwidth;
  16786. container.attr('transform',
  16787. 'translate(' + (gs.l - xoffset) + ',' + gs.t + ')');
  16788. // auto margin adjustment
  16789. var marginOpts = {};
  16790. var tFrac = FROM_TL[opts.yanchor];
  16791. var bFrac = FROM_BR[opts.yanchor];
  16792. if(opts.lenmode === 'pixels') {
  16793. marginOpts.y = opts.y;
  16794. marginOpts.t = outerheight * tFrac;
  16795. marginOpts.b = outerheight * bFrac;
  16796. }
  16797. else {
  16798. marginOpts.t = marginOpts.b = 0;
  16799. marginOpts.yt = opts.y + opts.len * tFrac;
  16800. marginOpts.yb = opts.y - opts.len * bFrac;
  16801. }
  16802. var lFrac = FROM_TL[opts.xanchor];
  16803. var rFrac = FROM_BR[opts.xanchor];
  16804. if(opts.thicknessmode === 'pixels') {
  16805. marginOpts.x = opts.x;
  16806. marginOpts.l = outerwidth * lFrac;
  16807. marginOpts.r = outerwidth * rFrac;
  16808. }
  16809. else {
  16810. var extraThickness = outerwidth - thickPx;
  16811. marginOpts.l = extraThickness * lFrac;
  16812. marginOpts.r = extraThickness * rFrac;
  16813. marginOpts.xl = opts.x - opts.thickness * lFrac;
  16814. marginOpts.xr = opts.x + opts.thickness * rFrac;
  16815. }
  16816. Plots.autoMargin(gd, id, marginOpts);
  16817. }
  16818. var cbDone = Lib.syncOrAsync([
  16819. Plots.previousPromises,
  16820. drawAxis,
  16821. Plots.previousPromises,
  16822. positionCB
  16823. ], gd);
  16824. if(cbDone && cbDone.then) (gd._promises || []).push(cbDone);
  16825. // dragging...
  16826. if(gd._context.edits.colorbarPosition) {
  16827. var t0,
  16828. xf,
  16829. yf;
  16830. dragElement.init({
  16831. element: container.node(),
  16832. gd: gd,
  16833. prepFn: function() {
  16834. t0 = container.attr('transform');
  16835. setCursor(container);
  16836. },
  16837. moveFn: function(dx, dy) {
  16838. container.attr('transform',
  16839. t0 + ' ' + 'translate(' + dx + ',' + dy + ')');
  16840. xf = dragElement.align(xLeftFrac + (dx / gs.w), thickFrac,
  16841. 0, 1, opts.xanchor);
  16842. yf = dragElement.align(yBottomFrac - (dy / gs.h), lenFrac,
  16843. 0, 1, opts.yanchor);
  16844. var csr = dragElement.getCursor(xf, yf,
  16845. opts.xanchor, opts.yanchor);
  16846. setCursor(container, csr);
  16847. },
  16848. doneFn: function() {
  16849. setCursor(container);
  16850. if(xf !== undefined && yf !== undefined) {
  16851. var update = {};
  16852. update[getPropName('x')] = xf;
  16853. update[getPropName('y')] = yf;
  16854. Registry.call('_guiRestyle', gd, update, getTrace().index);
  16855. }
  16856. }
  16857. });
  16858. }
  16859. return cbDone;
  16860. }
  16861. function getTrace() {
  16862. var idNum = id.substr(2);
  16863. for(var i = 0; i < gd._fullData.length; i++) {
  16864. var trace = gd._fullData[i];
  16865. if(trace.uid === idNum) return trace;
  16866. }
  16867. }
  16868. function getPropName(suffix) {
  16869. var trace = getTrace();
  16870. var propName = 'colorbar.';
  16871. var containerName = trace._module.colorbar.container;
  16872. if(containerName) propName = containerName + '.' + propName;
  16873. return propName + suffix;
  16874. }
  16875. // setter/getters for every item defined in opts
  16876. Object.keys(opts).forEach(function(name) {
  16877. component[name] = function(v) {
  16878. // getter
  16879. if(!arguments.length) return opts[name];
  16880. // setter - for multi-part properties,
  16881. // set only the parts that are provided
  16882. opts[name] = Lib.isPlainObject(opts[name]) ?
  16883. Lib.extendFlat(opts[name], v) :
  16884. v;
  16885. return component;
  16886. };
  16887. });
  16888. // or use .options to set multiple options at once via a dictionary
  16889. component.options = function(o) {
  16890. for(var name in o) {
  16891. // in case something random comes through
  16892. // that's not an option, ignore it
  16893. if(typeof component[name] === 'function') {
  16894. component[name](o[name]);
  16895. }
  16896. }
  16897. return component;
  16898. };
  16899. component._opts = opts;
  16900. return component;
  16901. };
  16902. },{"../../constants/alignment":146,"../../lib":168,"../../lib/extend":162,"../../lib/setcursor":187,"../../lib/svg_text_utils":189,"../../plots/cartesian/axes":212,"../../plots/cartesian/axis_defaults":214,"../../plots/cartesian/layout_attributes":225,"../../plots/cartesian/position_defaults":228,"../../plots/plots":245,"../../registry":257,"../color":51,"../dragelement":69,"../drawing":72,"../titles":139,"./attributes":52,"./constants":54,"d3":16,"tinycolor2":34}],57:[function(_dereq_,module,exports){
  16903. /**
  16904. * Copyright 2012-2019, Plotly, Inc.
  16905. * All rights reserved.
  16906. *
  16907. * This source code is licensed under the MIT license found in the
  16908. * LICENSE file in the root directory of this source tree.
  16909. */
  16910. 'use strict';
  16911. var Lib = _dereq_('../../lib');
  16912. module.exports = function hasColorbar(container) {
  16913. return Lib.isPlainObject(container.colorbar);
  16914. };
  16915. },{"../../lib":168}],58:[function(_dereq_,module,exports){
  16916. /**
  16917. * Copyright 2012-2019, Plotly, Inc.
  16918. * All rights reserved.
  16919. *
  16920. * This source code is licensed under the MIT license found in the
  16921. * LICENSE file in the root directory of this source tree.
  16922. */
  16923. 'use strict';
  16924. var palettes = _dereq_('./scales.js').scales;
  16925. var paletteStr = Object.keys(palettes);
  16926. function code(s) {
  16927. return '`' + s + '`';
  16928. }
  16929. /**
  16930. * Make colorscale attribute declarations for
  16931. *
  16932. * - colorscale,
  16933. * - (c|z)auto, (c|z)min, (c|z)max,
  16934. * - autocolorscale, reversescale,
  16935. * - showscale (optionally)
  16936. * - color (optionally)
  16937. *
  16938. * @param {string} context (dflt: '', i.e. from trace root):
  16939. * the container this is in ('', *marker*, *marker.line* etc)
  16940. *
  16941. * @param {object} opts:
  16942. * - cLetter {string} (dflt: 'c'):
  16943. * leading letter for 'min', 'max and 'auto' attribute (either 'z' or 'c')
  16944. *
  16945. * - colorAttr {string} (dflt: 'z' if `cLetter: 'z'`, 'color' if `cLetter: 'c'`):
  16946. * (for descriptions) sets the name of the color attribute that maps to the colorscale.
  16947. *
  16948. * N.B. if `colorAttr: 'color'`, we include the `color` declaration here.
  16949. *
  16950. * - onlyIfNumerical {string} (dflt: false' if `cLetter: 'z'`, true if `cLetter: 'c'`):
  16951. * (for descriptions) set to true if colorscale attribute only
  16952. *
  16953. * - colorscaleDflt {string}:
  16954. * overrides the colorscale dflt
  16955. *
  16956. * - autoColorDflt {boolean} (dflt true):
  16957. * normally autocolorscale.dflt is `true`, but pass `false` to override
  16958. *
  16959. * - noScale {boolean} (dflt: true if `context: 'marker.line'`, false otherwise):
  16960. * set to `false` to not include showscale attribute (e.g. for 'marker.line')
  16961. *
  16962. * - showScaleDflt {boolean} (dflt: true if `cLetter: 'z'`, false otherwise)
  16963. *
  16964. * - editTypeOverride {boolean} (dflt: ''):
  16965. * most of these attributes already require a recalc, but the ones that do not
  16966. * have editType *style* or *plot* unless you override (presumably with *calc*)
  16967. *
  16968. * - anim {boolean) (dflt: undefined): is 'color' animatable?
  16969. *
  16970. * @return {object}
  16971. */
  16972. module.exports = function colorScaleAttrs(context, opts) {
  16973. context = context || '';
  16974. opts = opts || {};
  16975. var cLetter = opts.cLetter || 'c';
  16976. var onlyIfNumerical = ('onlyIfNumerical' in opts) ? opts.onlyIfNumerical : Boolean(context);
  16977. var noScale = ('noScale' in opts) ? opts.noScale : context === 'marker.line';
  16978. var showScaleDflt = ('showScaleDflt' in opts) ? opts.showScaleDflt : cLetter === 'z';
  16979. var colorscaleDflt = typeof opts.colorscaleDflt === 'string' ? palettes[opts.colorscaleDflt] : null;
  16980. var editTypeOverride = opts.editTypeOverride || '';
  16981. var contextHead = context ? (context + '.') : '';
  16982. var colorAttr, colorAttrFull;
  16983. if('colorAttr' in opts) {
  16984. colorAttr = opts.colorAttr;
  16985. colorAttrFull = opts.colorAttr;
  16986. } else {
  16987. colorAttr = {z: 'z', c: 'color'}[cLetter];
  16988. colorAttrFull = 'in ' + code(contextHead + colorAttr);
  16989. }
  16990. var effectDesc = onlyIfNumerical ?
  16991. ' Has an effect only if ' + colorAttrFull + 'is set to a numerical array.' :
  16992. '';
  16993. var auto = cLetter + 'auto';
  16994. var min = cLetter + 'min';
  16995. var max = cLetter + 'max';
  16996. var minFull = code(contextHead + min);
  16997. var maxFull = code(contextHead + max);
  16998. var minmaxFull = minFull + ' and ' + maxFull;
  16999. var autoImpliedEdits = {};
  17000. autoImpliedEdits[min] = autoImpliedEdits[max] = undefined;
  17001. var minmaxImpliedEdits = {};
  17002. minmaxImpliedEdits[auto] = false;
  17003. var attrs = {};
  17004. if(colorAttr === 'color') {
  17005. attrs.color = {
  17006. valType: 'color',
  17007. arrayOk: true,
  17008. editType: editTypeOverride || 'style',
  17009. };
  17010. if(opts.anim) {
  17011. attrs.color.anim = true;
  17012. }
  17013. }
  17014. attrs[auto] = {
  17015. valType: 'boolean',
  17016. dflt: true,
  17017. editType: 'calc',
  17018. impliedEdits: autoImpliedEdits,
  17019. };
  17020. attrs[min] = {
  17021. valType: 'number',
  17022. dflt: null,
  17023. editType: editTypeOverride || 'plot',
  17024. impliedEdits: minmaxImpliedEdits,
  17025. };
  17026. attrs[max] = {
  17027. valType: 'number',
  17028. dflt: null,
  17029. editType: editTypeOverride || 'plot',
  17030. impliedEdits: minmaxImpliedEdits,
  17031. };
  17032. attrs.colorscale = {
  17033. valType: 'colorscale',
  17034. editType: 'calc',
  17035. dflt: colorscaleDflt,
  17036. impliedEdits: {autocolorscale: false},
  17037. };
  17038. attrs.autocolorscale = {
  17039. valType: 'boolean',
  17040. // gets overrode in 'heatmap' & 'surface' for backwards comp.
  17041. dflt: opts.autoColorDflt === false ? false : true,
  17042. editType: 'calc',
  17043. impliedEdits: {colorscale: undefined},
  17044. };
  17045. attrs.reversescale = {
  17046. valType: 'boolean',
  17047. dflt: false,
  17048. editType: 'plot',
  17049. };
  17050. if(!noScale) {
  17051. attrs.showscale = {
  17052. valType: 'boolean',
  17053. dflt: showScaleDflt,
  17054. editType: 'calc',
  17055. };
  17056. }
  17057. return attrs;
  17058. };
  17059. },{"./scales.js":66}],59:[function(_dereq_,module,exports){
  17060. /**
  17061. * Copyright 2012-2019, Plotly, Inc.
  17062. * All rights reserved.
  17063. *
  17064. * This source code is licensed under the MIT license found in the
  17065. * LICENSE file in the root directory of this source tree.
  17066. */
  17067. 'use strict';
  17068. var Lib = _dereq_('../../lib');
  17069. module.exports = function calc(gd, trace, opts) {
  17070. var fullLayout = gd._fullLayout;
  17071. var vals = opts.vals;
  17072. var containerStr = opts.containerStr;
  17073. var cLetter = opts.cLetter;
  17074. var container = containerStr ?
  17075. Lib.nestedProperty(trace, containerStr).get() :
  17076. trace;
  17077. var autoAttr = cLetter + 'auto';
  17078. var minAttr = cLetter + 'min';
  17079. var maxAttr = cLetter + 'max';
  17080. var auto = container[autoAttr];
  17081. var min = container[minAttr];
  17082. var max = container[maxAttr];
  17083. var scl = container.colorscale;
  17084. if(auto !== false || min === undefined) {
  17085. min = Lib.aggNums(Math.min, null, vals);
  17086. }
  17087. if(auto !== false || max === undefined) {
  17088. max = Lib.aggNums(Math.max, null, vals);
  17089. }
  17090. if(min === max) {
  17091. min -= 0.5;
  17092. max += 0.5;
  17093. }
  17094. container['_' + minAttr] = container[minAttr] = min;
  17095. container['_' + maxAttr] = container[maxAttr] = max;
  17096. if(container.autocolorscale) {
  17097. if(min * max < 0) scl = fullLayout.colorscale.diverging;
  17098. else if(min >= 0) scl = fullLayout.colorscale.sequential;
  17099. else scl = fullLayout.colorscale.sequentialminus;
  17100. container._colorscale = container.colorscale = scl;
  17101. }
  17102. };
  17103. },{"../../lib":168}],60:[function(_dereq_,module,exports){
  17104. /**
  17105. * Copyright 2012-2019, Plotly, Inc.
  17106. * All rights reserved.
  17107. *
  17108. * This source code is licensed under the MIT license found in the
  17109. * LICENSE file in the root directory of this source tree.
  17110. */
  17111. 'use strict';
  17112. var Lib = _dereq_('../../lib');
  17113. var hasColorscale = _dereq_('./helpers').hasColorscale;
  17114. module.exports = function crossTraceDefaults(fullData) {
  17115. function replace(cont, k) {
  17116. var val = cont['_' + k];
  17117. if(val !== undefined) {
  17118. cont[k] = val;
  17119. }
  17120. }
  17121. function relinkColorAtts(trace, cAttrs) {
  17122. var cont = cAttrs.container ?
  17123. Lib.nestedProperty(trace, cAttrs.container).get() :
  17124. trace;
  17125. if(cont) {
  17126. var isAuto = cont.zauto || cont.cauto;
  17127. var minAttr = cAttrs.min;
  17128. var maxAttr = cAttrs.max;
  17129. if(isAuto || cont[minAttr] === undefined) {
  17130. replace(cont, minAttr);
  17131. }
  17132. if(isAuto || cont[maxAttr] === undefined) {
  17133. replace(cont, maxAttr);
  17134. }
  17135. if(cont.autocolorscale) {
  17136. replace(cont, 'colorscale');
  17137. }
  17138. }
  17139. }
  17140. for(var i = 0; i < fullData.length; i++) {
  17141. var trace = fullData[i];
  17142. var _module = trace._module;
  17143. if(_module.colorbar) {
  17144. relinkColorAtts(trace, _module.colorbar);
  17145. }
  17146. // TODO could generalize _module.colorscale and use it here?
  17147. if(hasColorscale(trace, 'marker.line')) {
  17148. relinkColorAtts(trace, {
  17149. container: 'marker.line',
  17150. min: 'cmin',
  17151. max: 'cmax'
  17152. });
  17153. }
  17154. if(hasColorscale(trace, 'line')) {
  17155. relinkColorAtts(trace, {
  17156. container: 'line',
  17157. min: 'cmin',
  17158. max: 'cmax'
  17159. });
  17160. }
  17161. }
  17162. };
  17163. },{"../../lib":168,"./helpers":62}],61:[function(_dereq_,module,exports){
  17164. /**
  17165. * Copyright 2012-2019, Plotly, Inc.
  17166. * All rights reserved.
  17167. *
  17168. * This source code is licensed under the MIT license found in the
  17169. * LICENSE file in the root directory of this source tree.
  17170. */
  17171. 'use strict';
  17172. var isNumeric = _dereq_('fast-isnumeric');
  17173. var Lib = _dereq_('../../lib');
  17174. var hasColorbar = _dereq_('../colorbar/has_colorbar');
  17175. var colorbarDefaults = _dereq_('../colorbar/defaults');
  17176. var isValidScale = _dereq_('./scales').isValid;
  17177. function npMaybe(cont, prefix) {
  17178. var containerStr = prefix.slice(0, prefix.length - 1);
  17179. return prefix ?
  17180. Lib.nestedProperty(cont, containerStr).get() || {} :
  17181. cont;
  17182. }
  17183. module.exports = function colorScaleDefaults(traceIn, traceOut, layout, coerce, opts) {
  17184. var prefix = opts.prefix;
  17185. var cLetter = opts.cLetter;
  17186. var containerIn = npMaybe(traceIn, prefix);
  17187. var containerOut = npMaybe(traceOut, prefix);
  17188. var template = npMaybe(traceOut._template || {}, prefix) || {};
  17189. var minIn = containerIn[cLetter + 'min'];
  17190. var maxIn = containerIn[cLetter + 'max'];
  17191. var validMinMax = isNumeric(minIn) && isNumeric(maxIn) && (minIn < maxIn);
  17192. coerce(prefix + cLetter + 'auto', !validMinMax);
  17193. coerce(prefix + cLetter + 'min');
  17194. coerce(prefix + cLetter + 'max');
  17195. // handles both the trace case (autocolorscale is false by default) and
  17196. // the marker and marker.line case (autocolorscale is true by default)
  17197. var sclIn = containerIn.colorscale;
  17198. var sclTemplate = template.colorscale;
  17199. var autoColorscaleDflt;
  17200. if(sclIn !== undefined) autoColorscaleDflt = !isValidScale(sclIn);
  17201. if(sclTemplate !== undefined) autoColorscaleDflt = !isValidScale(sclTemplate);
  17202. coerce(prefix + 'autocolorscale', autoColorscaleDflt);
  17203. coerce(prefix + 'colorscale');
  17204. coerce(prefix + 'reversescale');
  17205. if(!opts.noScale && prefix !== 'marker.line.') {
  17206. // handles both the trace case where the dflt is listed in attributes and
  17207. // the marker case where the dflt is determined by hasColorbar
  17208. var showScaleDflt;
  17209. if(prefix) showScaleDflt = hasColorbar(containerIn);
  17210. var showScale = coerce(prefix + 'showscale', showScaleDflt);
  17211. if(showScale) colorbarDefaults(containerIn, containerOut, layout);
  17212. }
  17213. };
  17214. },{"../../lib":168,"../colorbar/defaults":55,"../colorbar/has_colorbar":57,"./scales":66,"fast-isnumeric":18}],62:[function(_dereq_,module,exports){
  17215. /**
  17216. * Copyright 2012-2019, Plotly, Inc.
  17217. * All rights reserved.
  17218. *
  17219. * This source code is licensed under the MIT license found in the
  17220. * LICENSE file in the root directory of this source tree.
  17221. */
  17222. 'use strict';
  17223. var d3 = _dereq_('d3');
  17224. var tinycolor = _dereq_('tinycolor2');
  17225. var isNumeric = _dereq_('fast-isnumeric');
  17226. var Lib = _dereq_('../../lib');
  17227. var Color = _dereq_('../color');
  17228. var isValidScale = _dereq_('./scales').isValid;
  17229. function hasColorscale(trace, containerStr) {
  17230. var container = containerStr ?
  17231. Lib.nestedProperty(trace, containerStr).get() || {} :
  17232. trace;
  17233. var color = container.color;
  17234. var isArrayWithOneNumber = false;
  17235. if(Lib.isArrayOrTypedArray(color)) {
  17236. for(var i = 0; i < color.length; i++) {
  17237. if(isNumeric(color[i])) {
  17238. isArrayWithOneNumber = true;
  17239. break;
  17240. }
  17241. }
  17242. }
  17243. return (
  17244. Lib.isPlainObject(container) && (
  17245. isArrayWithOneNumber ||
  17246. container.showscale === true ||
  17247. (isNumeric(container.cmin) && isNumeric(container.cmax)) ||
  17248. isValidScale(container.colorscale) ||
  17249. Lib.isPlainObject(container.colorbar)
  17250. )
  17251. );
  17252. }
  17253. /**
  17254. * Extract colorscale into numeric domain and color range.
  17255. *
  17256. * @param {object} cont colorscale container (e.g. trace, marker)
  17257. * - colorscale {array of arrays}
  17258. * - cmin/zmin {number}
  17259. * - cmax/zmax {number}
  17260. * - reversescale {boolean}
  17261. * @param {object} opts
  17262. * - cLetter {string} 'c' (for cmin/cmax) or 'z' (for zmin/zmax)
  17263. *
  17264. * @return {object}
  17265. * - domain {array}
  17266. * - range {array}
  17267. */
  17268. function extractScale(cont, opts) {
  17269. var cLetter = opts.cLetter;
  17270. var scl = cont.reversescale ?
  17271. flipScale(cont.colorscale) :
  17272. cont.colorscale;
  17273. // minimum color value (used to clamp scale)
  17274. var cmin = cont[cLetter + 'min'];
  17275. // maximum color value (used to clamp scale)
  17276. var cmax = cont[cLetter + 'max'];
  17277. var N = scl.length;
  17278. var domain = new Array(N);
  17279. var range = new Array(N);
  17280. for(var i = 0; i < N; i++) {
  17281. var si = scl[i];
  17282. domain[i] = cmin + si[0] * (cmax - cmin);
  17283. range[i] = si[1];
  17284. }
  17285. return {
  17286. domain: domain,
  17287. range: range
  17288. };
  17289. }
  17290. function flipScale(scl) {
  17291. var N = scl.length;
  17292. var sclNew = new Array(N);
  17293. for(var i = N - 1, j = 0; i >= 0; i--, j++) {
  17294. var si = scl[i];
  17295. sclNew[j] = [1 - si[0], si[1]];
  17296. }
  17297. return sclNew;
  17298. }
  17299. /**
  17300. * General colorscale function generator.
  17301. *
  17302. * @param {object} specs output of Colorscale.extractScale or precomputed domain, range.
  17303. * - domain {array}
  17304. * - range {array}
  17305. *
  17306. * @param {object} opts
  17307. * - noNumericCheck {boolean} if true, scale func bypasses numeric checks
  17308. * - returnArray {boolean} if true, scale func return 4-item array instead of color strings
  17309. *
  17310. * @return {function}
  17311. */
  17312. function makeColorScaleFunc(specs, opts) {
  17313. opts = opts || {};
  17314. var domain = specs.domain;
  17315. var range = specs.range;
  17316. var N = range.length;
  17317. var _range = new Array(N);
  17318. for(var i = 0; i < N; i++) {
  17319. var rgba = tinycolor(range[i]).toRgb();
  17320. _range[i] = [rgba.r, rgba.g, rgba.b, rgba.a];
  17321. }
  17322. var _sclFunc = d3.scale.linear()
  17323. .domain(domain)
  17324. .range(_range)
  17325. .clamp(true);
  17326. var noNumericCheck = opts.noNumericCheck;
  17327. var returnArray = opts.returnArray;
  17328. var sclFunc;
  17329. if(noNumericCheck && returnArray) {
  17330. sclFunc = _sclFunc;
  17331. }
  17332. else if(noNumericCheck) {
  17333. sclFunc = function(v) {
  17334. return colorArray2rbga(_sclFunc(v));
  17335. };
  17336. }
  17337. else if(returnArray) {
  17338. sclFunc = function(v) {
  17339. if(isNumeric(v)) return _sclFunc(v);
  17340. else if(tinycolor(v).isValid()) return v;
  17341. else return Color.defaultLine;
  17342. };
  17343. }
  17344. else {
  17345. sclFunc = function(v) {
  17346. if(isNumeric(v)) return colorArray2rbga(_sclFunc(v));
  17347. else if(tinycolor(v).isValid()) return v;
  17348. else return Color.defaultLine;
  17349. };
  17350. }
  17351. // colorbar draw looks into the d3 scale closure for domain and range
  17352. sclFunc.domain = _sclFunc.domain;
  17353. sclFunc.range = function() { return range; };
  17354. return sclFunc;
  17355. }
  17356. function colorArray2rbga(colorArray) {
  17357. var colorObj = {
  17358. r: colorArray[0],
  17359. g: colorArray[1],
  17360. b: colorArray[2],
  17361. a: colorArray[3]
  17362. };
  17363. return tinycolor(colorObj).toRgbString();
  17364. }
  17365. module.exports = {
  17366. hasColorscale: hasColorscale,
  17367. extractScale: extractScale,
  17368. flipScale: flipScale,
  17369. makeColorScaleFunc: makeColorScaleFunc
  17370. };
  17371. },{"../../lib":168,"../color":51,"./scales":66,"d3":16,"fast-isnumeric":18,"tinycolor2":34}],63:[function(_dereq_,module,exports){
  17372. /**
  17373. * Copyright 2012-2019, Plotly, Inc.
  17374. * All rights reserved.
  17375. *
  17376. * This source code is licensed under the MIT license found in the
  17377. * LICENSE file in the root directory of this source tree.
  17378. */
  17379. 'use strict';
  17380. var scales = _dereq_('./scales');
  17381. var helpers = _dereq_('./helpers');
  17382. module.exports = {
  17383. moduleType: 'component',
  17384. name: 'colorscale',
  17385. attributes: _dereq_('./attributes'),
  17386. layoutAttributes: _dereq_('./layout_attributes'),
  17387. supplyLayoutDefaults: _dereq_('./layout_defaults'),
  17388. handleDefaults: _dereq_('./defaults'),
  17389. crossTraceDefaults: _dereq_('./cross_trace_defaults'),
  17390. calc: _dereq_('./calc'),
  17391. // ./scales.js is required in lib/coerce.js ;
  17392. // it needs to be a seperate module to avoid circular a dependency
  17393. scales: scales.scales,
  17394. defaultScale: scales.defaultScale,
  17395. getScale: scales.get,
  17396. isValidScale: scales.isValid,
  17397. hasColorscale: helpers.hasColorscale,
  17398. flipScale: helpers.flipScale,
  17399. extractScale: helpers.extractScale,
  17400. makeColorScaleFunc: helpers.makeColorScaleFunc
  17401. };
  17402. },{"./attributes":58,"./calc":59,"./cross_trace_defaults":60,"./defaults":61,"./helpers":62,"./layout_attributes":64,"./layout_defaults":65,"./scales":66}],64:[function(_dereq_,module,exports){
  17403. /**
  17404. * Copyright 2012-2019, Plotly, Inc.
  17405. * All rights reserved.
  17406. *
  17407. * This source code is licensed under the MIT license found in the
  17408. * LICENSE file in the root directory of this source tree.
  17409. */
  17410. 'use strict';
  17411. var scales = _dereq_('./scales').scales;
  17412. var msg = 'Note that `autocolorscale` must be true for this attribute to work.';
  17413. module.exports = {
  17414. editType: 'calc',
  17415. sequential: {
  17416. valType: 'colorscale',
  17417. dflt: scales.Reds,
  17418. editType: 'calc',
  17419. },
  17420. sequentialminus: {
  17421. valType: 'colorscale',
  17422. dflt: scales.Blues,
  17423. editType: 'calc',
  17424. },
  17425. diverging: {
  17426. valType: 'colorscale',
  17427. dflt: scales.RdBu,
  17428. editType: 'calc',
  17429. }
  17430. };
  17431. },{"./scales":66}],65:[function(_dereq_,module,exports){
  17432. /**
  17433. * Copyright 2012-2019, Plotly, Inc.
  17434. * All rights reserved.
  17435. *
  17436. * This source code is licensed under the MIT license found in the
  17437. * LICENSE file in the root directory of this source tree.
  17438. */
  17439. 'use strict';
  17440. var Lib = _dereq_('../../lib');
  17441. var colorscaleAttrs = _dereq_('./layout_attributes');
  17442. var Template = _dereq_('../../plot_api/plot_template');
  17443. module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
  17444. var colorscaleIn = layoutIn.colorscale;
  17445. var colorscaleOut = Template.newContainer(layoutOut, 'colorscale');
  17446. function coerce(attr, dflt) {
  17447. return Lib.coerce(colorscaleIn, colorscaleOut, colorscaleAttrs, attr, dflt);
  17448. }
  17449. coerce('sequential');
  17450. coerce('sequentialminus');
  17451. coerce('diverging');
  17452. };
  17453. },{"../../lib":168,"../../plot_api/plot_template":202,"./layout_attributes":64}],66:[function(_dereq_,module,exports){
  17454. /**
  17455. * Copyright 2012-2019, Plotly, Inc.
  17456. * All rights reserved.
  17457. *
  17458. * This source code is licensed under the MIT license found in the
  17459. * LICENSE file in the root directory of this source tree.
  17460. */
  17461. 'use strict';
  17462. var tinycolor = _dereq_('tinycolor2');
  17463. var scales = {
  17464. 'Greys': [
  17465. [0, 'rgb(0,0,0)'], [1, 'rgb(255,255,255)']
  17466. ],
  17467. 'YlGnBu': [
  17468. [0, 'rgb(8,29,88)'], [0.125, 'rgb(37,52,148)'],
  17469. [0.25, 'rgb(34,94,168)'], [0.375, 'rgb(29,145,192)'],
  17470. [0.5, 'rgb(65,182,196)'], [0.625, 'rgb(127,205,187)'],
  17471. [0.75, 'rgb(199,233,180)'], [0.875, 'rgb(237,248,217)'],
  17472. [1, 'rgb(255,255,217)']
  17473. ],
  17474. 'Greens': [
  17475. [0, 'rgb(0,68,27)'], [0.125, 'rgb(0,109,44)'],
  17476. [0.25, 'rgb(35,139,69)'], [0.375, 'rgb(65,171,93)'],
  17477. [0.5, 'rgb(116,196,118)'], [0.625, 'rgb(161,217,155)'],
  17478. [0.75, 'rgb(199,233,192)'], [0.875, 'rgb(229,245,224)'],
  17479. [1, 'rgb(247,252,245)']
  17480. ],
  17481. 'YlOrRd': [
  17482. [0, 'rgb(128,0,38)'], [0.125, 'rgb(189,0,38)'],
  17483. [0.25, 'rgb(227,26,28)'], [0.375, 'rgb(252,78,42)'],
  17484. [0.5, 'rgb(253,141,60)'], [0.625, 'rgb(254,178,76)'],
  17485. [0.75, 'rgb(254,217,118)'], [0.875, 'rgb(255,237,160)'],
  17486. [1, 'rgb(255,255,204)']
  17487. ],
  17488. 'Bluered': [
  17489. [0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']
  17490. ],
  17491. // modified RdBu based on
  17492. // www.sandia.gov/~kmorel/documents/ColorMaps/ColorMapsExpanded.pdf
  17493. 'RdBu': [
  17494. [0, 'rgb(5,10,172)'], [0.35, 'rgb(106,137,247)'],
  17495. [0.5, 'rgb(190,190,190)'], [0.6, 'rgb(220,170,132)'],
  17496. [0.7, 'rgb(230,145,90)'], [1, 'rgb(178,10,28)']
  17497. ],
  17498. // Scale for non-negative numeric values
  17499. 'Reds': [
  17500. [0, 'rgb(220,220,220)'], [0.2, 'rgb(245,195,157)'],
  17501. [0.4, 'rgb(245,160,105)'], [1, 'rgb(178,10,28)']
  17502. ],
  17503. // Scale for non-positive numeric values
  17504. 'Blues': [
  17505. [0, 'rgb(5,10,172)'], [0.35, 'rgb(40,60,190)'],
  17506. [0.5, 'rgb(70,100,245)'], [0.6, 'rgb(90,120,245)'],
  17507. [0.7, 'rgb(106,137,247)'], [1, 'rgb(220,220,220)']
  17508. ],
  17509. 'Picnic': [
  17510. [0, 'rgb(0,0,255)'], [0.1, 'rgb(51,153,255)'],
  17511. [0.2, 'rgb(102,204,255)'], [0.3, 'rgb(153,204,255)'],
  17512. [0.4, 'rgb(204,204,255)'], [0.5, 'rgb(255,255,255)'],
  17513. [0.6, 'rgb(255,204,255)'], [0.7, 'rgb(255,153,255)'],
  17514. [0.8, 'rgb(255,102,204)'], [0.9, 'rgb(255,102,102)'],
  17515. [1, 'rgb(255,0,0)']
  17516. ],
  17517. 'Rainbow': [
  17518. [0, 'rgb(150,0,90)'], [0.125, 'rgb(0,0,200)'],
  17519. [0.25, 'rgb(0,25,255)'], [0.375, 'rgb(0,152,255)'],
  17520. [0.5, 'rgb(44,255,150)'], [0.625, 'rgb(151,255,0)'],
  17521. [0.75, 'rgb(255,234,0)'], [0.875, 'rgb(255,111,0)'],
  17522. [1, 'rgb(255,0,0)']
  17523. ],
  17524. 'Portland': [
  17525. [0, 'rgb(12,51,131)'], [0.25, 'rgb(10,136,186)'],
  17526. [0.5, 'rgb(242,211,56)'], [0.75, 'rgb(242,143,56)'],
  17527. [1, 'rgb(217,30,30)']
  17528. ],
  17529. 'Jet': [
  17530. [0, 'rgb(0,0,131)'], [0.125, 'rgb(0,60,170)'],
  17531. [0.375, 'rgb(5,255,255)'], [0.625, 'rgb(255,255,0)'],
  17532. [0.875, 'rgb(250,0,0)'], [1, 'rgb(128,0,0)']
  17533. ],
  17534. 'Hot': [
  17535. [0, 'rgb(0,0,0)'], [0.3, 'rgb(230,0,0)'],
  17536. [0.6, 'rgb(255,210,0)'], [1, 'rgb(255,255,255)']
  17537. ],
  17538. 'Blackbody': [
  17539. [0, 'rgb(0,0,0)'], [0.2, 'rgb(230,0,0)'],
  17540. [0.4, 'rgb(230,210,0)'], [0.7, 'rgb(255,255,255)'],
  17541. [1, 'rgb(160,200,255)']
  17542. ],
  17543. 'Earth': [
  17544. [0, 'rgb(0,0,130)'], [0.1, 'rgb(0,180,180)'],
  17545. [0.2, 'rgb(40,210,40)'], [0.4, 'rgb(230,230,50)'],
  17546. [0.6, 'rgb(120,70,20)'], [1, 'rgb(255,255,255)']
  17547. ],
  17548. 'Electric': [
  17549. [0, 'rgb(0,0,0)'], [0.15, 'rgb(30,0,100)'],
  17550. [0.4, 'rgb(120,0,100)'], [0.6, 'rgb(160,90,0)'],
  17551. [0.8, 'rgb(230,200,0)'], [1, 'rgb(255,250,220)']
  17552. ],
  17553. 'Viridis': [
  17554. [0, '#440154'], [0.06274509803921569, '#48186a'],
  17555. [0.12549019607843137, '#472d7b'], [0.18823529411764706, '#424086'],
  17556. [0.25098039215686274, '#3b528b'], [0.3137254901960784, '#33638d'],
  17557. [0.3764705882352941, '#2c728e'], [0.4392156862745098, '#26828e'],
  17558. [0.5019607843137255, '#21918c'], [0.5647058823529412, '#1fa088'],
  17559. [0.6274509803921569, '#28ae80'], [0.6901960784313725, '#3fbc73'],
  17560. [0.7529411764705882, '#5ec962'], [0.8156862745098039, '#84d44b'],
  17561. [0.8784313725490196, '#addc30'], [0.9411764705882353, '#d8e219'],
  17562. [1, '#fde725']
  17563. ],
  17564. 'Cividis': [
  17565. [0.000000, 'rgb(0,32,76)'], [0.058824, 'rgb(0,42,102)'],
  17566. [0.117647, 'rgb(0,52,110)'], [0.176471, 'rgb(39,63,108)'],
  17567. [0.235294, 'rgb(60,74,107)'], [0.294118, 'rgb(76,85,107)'],
  17568. [0.352941, 'rgb(91,95,109)'], [0.411765, 'rgb(104,106,112)'],
  17569. [0.470588, 'rgb(117,117,117)'], [0.529412, 'rgb(131,129,120)'],
  17570. [0.588235, 'rgb(146,140,120)'], [0.647059, 'rgb(161,152,118)'],
  17571. [0.705882, 'rgb(176,165,114)'], [0.764706, 'rgb(192,177,109)'],
  17572. [0.823529, 'rgb(209,191,102)'], [0.882353, 'rgb(225,204,92)'],
  17573. [0.941176, 'rgb(243,219,79)'], [1.000000, 'rgb(255,233,69)']
  17574. ]
  17575. };
  17576. var defaultScale = scales.RdBu;
  17577. function getScale(scl, dflt) {
  17578. if(!dflt) dflt = defaultScale;
  17579. if(!scl) return dflt;
  17580. function parseScale() {
  17581. try {
  17582. scl = scales[scl] || JSON.parse(scl);
  17583. } catch(e) {
  17584. scl = dflt;
  17585. }
  17586. }
  17587. if(typeof scl === 'string') {
  17588. parseScale();
  17589. // occasionally scl is double-JSON encoded...
  17590. if(typeof scl === 'string') parseScale();
  17591. }
  17592. if(!isValidScaleArray(scl)) return dflt;
  17593. return scl;
  17594. }
  17595. function isValidScaleArray(scl) {
  17596. var highestVal = 0;
  17597. if(!Array.isArray(scl) || scl.length < 2) return false;
  17598. if(!scl[0] || !scl[scl.length - 1]) return false;
  17599. if(+scl[0][0] !== 0 || +scl[scl.length - 1][0] !== 1) return false;
  17600. for(var i = 0; i < scl.length; i++) {
  17601. var si = scl[i];
  17602. if(si.length !== 2 || +si[0] < highestVal || !tinycolor(si[1]).isValid()) {
  17603. return false;
  17604. }
  17605. highestVal = +si[0];
  17606. }
  17607. return true;
  17608. }
  17609. function isValidScale(scl) {
  17610. if(scales[scl] !== undefined) return true;
  17611. else return isValidScaleArray(scl);
  17612. }
  17613. module.exports = {
  17614. scales: scales,
  17615. defaultScale: defaultScale,
  17616. get: getScale,
  17617. isValid: isValidScale
  17618. };
  17619. },{"tinycolor2":34}],67:[function(_dereq_,module,exports){
  17620. /**
  17621. * Copyright 2012-2019, Plotly, Inc.
  17622. * All rights reserved.
  17623. *
  17624. * This source code is licensed under the MIT license found in the
  17625. * LICENSE file in the root directory of this source tree.
  17626. */
  17627. 'use strict';
  17628. // for automatic alignment on dragging, <1/3 means left align,
  17629. // >2/3 means right, and between is center. Pick the right fraction
  17630. // based on where you are, and return the fraction corresponding to
  17631. // that position on the object
  17632. module.exports = function align(v, dv, v0, v1, anchor) {
  17633. var vmin = (v - v0) / (v1 - v0);
  17634. var vmax = vmin + dv / (v1 - v0);
  17635. var vc = (vmin + vmax) / 2;
  17636. // explicitly specified anchor
  17637. if(anchor === 'left' || anchor === 'bottom') return vmin;
  17638. if(anchor === 'center' || anchor === 'middle') return vc;
  17639. if(anchor === 'right' || anchor === 'top') return vmax;
  17640. // automatic based on position
  17641. if(vmin < (2 / 3) - vc) return vmin;
  17642. if(vmax > (4 / 3) - vc) return vmax;
  17643. return vc;
  17644. };
  17645. },{}],68:[function(_dereq_,module,exports){
  17646. /**
  17647. * Copyright 2012-2019, Plotly, Inc.
  17648. * All rights reserved.
  17649. *
  17650. * This source code is licensed under the MIT license found in the
  17651. * LICENSE file in the root directory of this source tree.
  17652. */
  17653. 'use strict';
  17654. var Lib = _dereq_('../../lib');
  17655. // set cursors pointing toward the closest corner/side,
  17656. // to indicate alignment
  17657. // x and y are 0-1, fractions of the plot area
  17658. var cursorset = [
  17659. ['sw-resize', 's-resize', 'se-resize'],
  17660. ['w-resize', 'move', 'e-resize'],
  17661. ['nw-resize', 'n-resize', 'ne-resize']
  17662. ];
  17663. module.exports = function getCursor(x, y, xanchor, yanchor) {
  17664. if(xanchor === 'left') x = 0;
  17665. else if(xanchor === 'center') x = 1;
  17666. else if(xanchor === 'right') x = 2;
  17667. else x = Lib.constrain(Math.floor(x * 3), 0, 2);
  17668. if(yanchor === 'bottom') y = 0;
  17669. else if(yanchor === 'middle') y = 1;
  17670. else if(yanchor === 'top') y = 2;
  17671. else y = Lib.constrain(Math.floor(y * 3), 0, 2);
  17672. return cursorset[y][x];
  17673. };
  17674. },{"../../lib":168}],69:[function(_dereq_,module,exports){
  17675. /**
  17676. * Copyright 2012-2019, Plotly, Inc.
  17677. * All rights reserved.
  17678. *
  17679. * This source code is licensed under the MIT license found in the
  17680. * LICENSE file in the root directory of this source tree.
  17681. */
  17682. 'use strict';
  17683. var mouseOffset = _dereq_('mouse-event-offset');
  17684. var hasHover = _dereq_('has-hover');
  17685. var supportsPassive = _dereq_('has-passive-events');
  17686. var Registry = _dereq_('../../registry');
  17687. var Lib = _dereq_('../../lib');
  17688. var constants = _dereq_('../../plots/cartesian/constants');
  17689. var interactConstants = _dereq_('../../constants/interactions');
  17690. var dragElement = module.exports = {};
  17691. dragElement.align = _dereq_('./align');
  17692. dragElement.getCursor = _dereq_('./cursor');
  17693. var unhover = _dereq_('./unhover');
  17694. dragElement.unhover = unhover.wrapped;
  17695. dragElement.unhoverRaw = unhover.raw;
  17696. /**
  17697. * Abstracts click & drag interactions
  17698. *
  17699. * During the interaction, a "coverSlip" element - a transparent
  17700. * div covering the whole page - is created, which has two key effects:
  17701. * - Lets you drag beyond the boundaries of the plot itself without
  17702. * dropping (but if you drag all the way out of the browser window the
  17703. * interaction will end)
  17704. * - Freezes the cursor: whatever mouse cursor the drag element had when the
  17705. * interaction started gets copied to the coverSlip for use until mouseup
  17706. *
  17707. * If the user executes a drag bigger than MINDRAG, callbacks will fire as:
  17708. * prepFn, moveFn (1 or more times), doneFn
  17709. * If the user does not drag enough, prepFn and clickFn will fire.
  17710. *
  17711. * Note: If you cancel contextmenu, clickFn will fire even with a right click
  17712. * (unlike native events) so you'll get a `plotly_click` event. Cancel context eg:
  17713. * gd.addEventListener('contextmenu', function(e) { e.preventDefault(); });
  17714. * TODO: we should probably turn this into a `config` parameter, so we can fix it
  17715. * such that if you *don't* cancel contextmenu, we can prevent partial drags, which
  17716. * put you in a weird state.
  17717. *
  17718. * If the user clicks multiple times quickly, clickFn will fire each time
  17719. * but numClicks will increase to help you recognize doubleclicks.
  17720. *
  17721. * @param {object} options with keys:
  17722. * element (required) the DOM element to drag
  17723. * prepFn (optional) function(event, startX, startY)
  17724. * executed on mousedown
  17725. * startX and startY are the clientX and clientY pixel position
  17726. * of the mousedown event
  17727. * moveFn (optional) function(dx, dy)
  17728. * executed on move, ONLY after we've exceeded MINDRAG
  17729. * (we keep executing moveFn if you move back to where you started)
  17730. * dx and dy are the net pixel offset of the drag,
  17731. * dragged is true/false, has the mouse moved enough to
  17732. * constitute a drag
  17733. * doneFn (optional) function(e)
  17734. * executed on mouseup, ONLY if we exceeded MINDRAG (so you can be
  17735. * sure that moveFn has been called at least once)
  17736. * numClicks is how many clicks we've registered within
  17737. * a doubleclick time
  17738. * e is the original mouseup event
  17739. * clickFn (optional) function(numClicks, e)
  17740. * executed on mouseup if we have NOT exceeded MINDRAG (ie moveFn
  17741. * has not been called at all)
  17742. * numClicks is how many clicks we've registered within
  17743. * a doubleclick time
  17744. * e is the original mousedown event
  17745. * clampFn (optional, function(dx, dy) return [dx2, dy2])
  17746. * Provide custom clamping function for small displacements.
  17747. * By default, clamping is done using `minDrag` to x and y displacements
  17748. * independently.
  17749. */
  17750. dragElement.init = function init(options) {
  17751. var gd = options.gd;
  17752. var numClicks = 1;
  17753. var DBLCLICKDELAY = interactConstants.DBLCLICKDELAY;
  17754. var element = options.element;
  17755. var startX,
  17756. startY,
  17757. newMouseDownTime,
  17758. cursor,
  17759. dragCover,
  17760. initialEvent,
  17761. initialTarget,
  17762. rightClick;
  17763. if(!gd._mouseDownTime) gd._mouseDownTime = 0;
  17764. element.style.pointerEvents = 'all';
  17765. element.onmousedown = onStart;
  17766. if(!supportsPassive) {
  17767. element.ontouchstart = onStart;
  17768. }
  17769. else {
  17770. if(element._ontouchstart) {
  17771. element.removeEventListener('touchstart', element._ontouchstart);
  17772. }
  17773. element._ontouchstart = onStart;
  17774. element.addEventListener('touchstart', onStart, {passive: false});
  17775. }
  17776. function _clampFn(dx, dy, minDrag) {
  17777. if(Math.abs(dx) < minDrag) dx = 0;
  17778. if(Math.abs(dy) < minDrag) dy = 0;
  17779. return [dx, dy];
  17780. }
  17781. var clampFn = options.clampFn || _clampFn;
  17782. function onStart(e) {
  17783. // make dragging and dragged into properties of gd
  17784. // so that others can look at and modify them
  17785. gd._dragged = false;
  17786. gd._dragging = true;
  17787. var offset = pointerOffset(e);
  17788. startX = offset[0];
  17789. startY = offset[1];
  17790. initialTarget = e.target;
  17791. initialEvent = e;
  17792. rightClick = e.buttons === 2 || e.ctrlKey;
  17793. // fix Fx.hover for touch events
  17794. if(typeof e.clientX === 'undefined' && typeof e.clientY === 'undefined') {
  17795. e.clientX = startX;
  17796. e.clientY = startY;
  17797. }
  17798. newMouseDownTime = (new Date()).getTime();
  17799. if(newMouseDownTime - gd._mouseDownTime < DBLCLICKDELAY) {
  17800. // in a click train
  17801. numClicks += 1;
  17802. }
  17803. else {
  17804. // new click train
  17805. numClicks = 1;
  17806. gd._mouseDownTime = newMouseDownTime;
  17807. }
  17808. if(options.prepFn) options.prepFn(e, startX, startY);
  17809. if(hasHover && !rightClick) {
  17810. dragCover = coverSlip();
  17811. dragCover.style.cursor = window.getComputedStyle(element).cursor;
  17812. }
  17813. else if(!hasHover) {
  17814. // document acts as a dragcover for mobile, bc we can't create dragcover dynamically
  17815. dragCover = document;
  17816. cursor = window.getComputedStyle(document.documentElement).cursor;
  17817. document.documentElement.style.cursor = window.getComputedStyle(element).cursor;
  17818. }
  17819. document.addEventListener('mouseup', onDone);
  17820. document.addEventListener('touchend', onDone);
  17821. if(options.dragmode !== false) {
  17822. e.preventDefault();
  17823. document.addEventListener('mousemove', onMove);
  17824. document.addEventListener('touchmove', onMove);
  17825. }
  17826. return;
  17827. }
  17828. function onMove(e) {
  17829. e.preventDefault();
  17830. var offset = pointerOffset(e);
  17831. var minDrag = options.minDrag || constants.MINDRAG;
  17832. var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag);
  17833. var dx = dxdy[0];
  17834. var dy = dxdy[1];
  17835. if(dx || dy) {
  17836. gd._dragged = true;
  17837. dragElement.unhover(gd);
  17838. }
  17839. if(gd._dragged && options.moveFn && !rightClick) options.moveFn(dx, dy);
  17840. return;
  17841. }
  17842. function onDone(e) {
  17843. if(options.dragmode !== false) {
  17844. e.preventDefault();
  17845. document.removeEventListener('mousemove', onMove);
  17846. document.removeEventListener('touchmove', onMove);
  17847. }
  17848. document.removeEventListener('mouseup', onDone);
  17849. document.removeEventListener('touchend', onDone);
  17850. if(hasHover) {
  17851. Lib.removeElement(dragCover);
  17852. }
  17853. else if(cursor) {
  17854. dragCover.documentElement.style.cursor = cursor;
  17855. cursor = null;
  17856. }
  17857. if(!gd._dragging) {
  17858. gd._dragged = false;
  17859. return;
  17860. }
  17861. gd._dragging = false;
  17862. // don't count as a dblClick unless the mouseUp is also within
  17863. // the dblclick delay
  17864. if((new Date()).getTime() - gd._mouseDownTime > DBLCLICKDELAY) {
  17865. numClicks = Math.max(numClicks - 1, 1);
  17866. }
  17867. if(gd._dragged) {
  17868. if(options.doneFn) options.doneFn();
  17869. }
  17870. else {
  17871. if(options.clickFn) options.clickFn(numClicks, initialEvent);
  17872. // If we haven't dragged, this should be a click. But because of the
  17873. // coverSlip changing the element, the natural system might not generate one,
  17874. // so we need to make our own. But right clicks don't normally generate
  17875. // click events, only contextmenu events, which happen on mousedown.
  17876. if(!rightClick) {
  17877. var e2;
  17878. try {
  17879. e2 = new MouseEvent('click', e);
  17880. }
  17881. catch(err) {
  17882. var offset = pointerOffset(e);
  17883. e2 = document.createEvent('MouseEvents');
  17884. e2.initMouseEvent('click',
  17885. e.bubbles, e.cancelable,
  17886. e.view, e.detail,
  17887. e.screenX, e.screenY,
  17888. offset[0], offset[1],
  17889. e.ctrlKey, e.altKey, e.shiftKey, e.metaKey,
  17890. e.button, e.relatedTarget);
  17891. }
  17892. initialTarget.dispatchEvent(e2);
  17893. }
  17894. }
  17895. finishDrag(gd);
  17896. gd._dragged = false;
  17897. return;
  17898. }
  17899. };
  17900. function coverSlip() {
  17901. var cover = document.createElement('div');
  17902. cover.className = 'dragcover';
  17903. var cStyle = cover.style;
  17904. cStyle.position = 'fixed';
  17905. cStyle.left = 0;
  17906. cStyle.right = 0;
  17907. cStyle.top = 0;
  17908. cStyle.bottom = 0;
  17909. cStyle.zIndex = 999999999;
  17910. cStyle.background = 'none';
  17911. document.body.appendChild(cover);
  17912. return cover;
  17913. }
  17914. dragElement.coverSlip = coverSlip;
  17915. function finishDrag(gd) {
  17916. gd._dragging = false;
  17917. if(gd._replotPending) Registry.call('plot', gd);
  17918. }
  17919. function pointerOffset(e) {
  17920. return mouseOffset(
  17921. e.changedTouches ? e.changedTouches[0] : e,
  17922. document.body
  17923. );
  17924. }
  17925. },{"../../constants/interactions":148,"../../lib":168,"../../plots/cartesian/constants":218,"../../registry":257,"./align":67,"./cursor":68,"./unhover":70,"has-hover":20,"has-passive-events":21,"mouse-event-offset":24}],70:[function(_dereq_,module,exports){
  17926. /**
  17927. * Copyright 2012-2019, Plotly, Inc.
  17928. * All rights reserved.
  17929. *
  17930. * This source code is licensed under the MIT license found in the
  17931. * LICENSE file in the root directory of this source tree.
  17932. */
  17933. 'use strict';
  17934. var Events = _dereq_('../../lib/events');
  17935. var throttle = _dereq_('../../lib/throttle');
  17936. var getGraphDiv = _dereq_('../../lib/get_graph_div');
  17937. var hoverConstants = _dereq_('../fx/constants');
  17938. var unhover = module.exports = {};
  17939. unhover.wrapped = function(gd, evt, subplot) {
  17940. gd = getGraphDiv(gd);
  17941. // Important, clear any queued hovers
  17942. if(gd._fullLayout) {
  17943. throttle.clear(gd._fullLayout._uid + hoverConstants.HOVERID);
  17944. }
  17945. unhover.raw(gd, evt, subplot);
  17946. };
  17947. // remove hover effects on mouse out, and emit unhover event
  17948. unhover.raw = function unhoverRaw(gd, evt) {
  17949. var fullLayout = gd._fullLayout;
  17950. var oldhoverdata = gd._hoverdata;
  17951. if(!evt) evt = {};
  17952. if(evt.target &&
  17953. Events.triggerHandler(gd, 'plotly_beforehover', evt) === false) {
  17954. return;
  17955. }
  17956. fullLayout._hoverlayer.selectAll('g').remove();
  17957. fullLayout._hoverlayer.selectAll('line').remove();
  17958. fullLayout._hoverlayer.selectAll('circle').remove();
  17959. gd._hoverdata = undefined;
  17960. if(evt.target && oldhoverdata) {
  17961. gd.emit('plotly_unhover', {
  17962. event: evt,
  17963. points: oldhoverdata
  17964. });
  17965. }
  17966. };
  17967. },{"../../lib/events":161,"../../lib/get_graph_div":166,"../../lib/throttle":190,"../fx/constants":84}],71:[function(_dereq_,module,exports){
  17968. /**
  17969. * Copyright 2012-2019, Plotly, Inc.
  17970. * All rights reserved.
  17971. *
  17972. * This source code is licensed under the MIT license found in the
  17973. * LICENSE file in the root directory of this source tree.
  17974. */
  17975. 'use strict';
  17976. exports.dash = {
  17977. valType: 'string',
  17978. // string type usually doesn't take values... this one should really be
  17979. // a special type or at least a special coercion function, from the GUI
  17980. // you only get these values but elsewhere the user can supply a list of
  17981. // dash lengths in px, and it will be honored
  17982. values: ['solid', 'dot', 'dash', 'longdash', 'dashdot', 'longdashdot'],
  17983. dflt: 'solid',
  17984. editType: 'style',
  17985. };
  17986. },{}],72:[function(_dereq_,module,exports){
  17987. /**
  17988. * Copyright 2012-2019, Plotly, Inc.
  17989. * All rights reserved.
  17990. *
  17991. * This source code is licensed under the MIT license found in the
  17992. * LICENSE file in the root directory of this source tree.
  17993. */
  17994. 'use strict';
  17995. var d3 = _dereq_('d3');
  17996. var isNumeric = _dereq_('fast-isnumeric');
  17997. var tinycolor = _dereq_('tinycolor2');
  17998. var Registry = _dereq_('../../registry');
  17999. var Color = _dereq_('../color');
  18000. var Colorscale = _dereq_('../colorscale');
  18001. var Lib = _dereq_('../../lib');
  18002. var svgTextUtils = _dereq_('../../lib/svg_text_utils');
  18003. var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');
  18004. var alignment = _dereq_('../../constants/alignment');
  18005. var LINE_SPACING = alignment.LINE_SPACING;
  18006. var DESELECTDIM = _dereq_('../../constants/interactions').DESELECTDIM;
  18007. var subTypes = _dereq_('../../traces/scatter/subtypes');
  18008. var makeBubbleSizeFn = _dereq_('../../traces/scatter/make_bubble_size_func');
  18009. var drawing = module.exports = {};
  18010. // -----------------------------------------------------
  18011. // styling functions for plot elements
  18012. // -----------------------------------------------------
  18013. drawing.font = function(s, family, size, color) {
  18014. // also allow the form font(s, {family, size, color})
  18015. if(Lib.isPlainObject(family)) {
  18016. color = family.color;
  18017. size = family.size;
  18018. family = family.family;
  18019. }
  18020. if(family) s.style('font-family', family);
  18021. if(size + 1) s.style('font-size', size + 'px');
  18022. if(color) s.call(Color.fill, color);
  18023. };
  18024. /*
  18025. * Positioning helpers
  18026. * Note: do not use `setPosition` with <text> nodes modified by
  18027. * `svgTextUtils.convertToTspans`. Use `svgTextUtils.positionText`
  18028. * instead, so that <tspan.line> elements get updated to match.
  18029. */
  18030. drawing.setPosition = function(s, x, y) { s.attr('x', x).attr('y', y); };
  18031. drawing.setSize = function(s, w, h) { s.attr('width', w).attr('height', h); };
  18032. drawing.setRect = function(s, x, y, w, h) {
  18033. s.call(drawing.setPosition, x, y).call(drawing.setSize, w, h);
  18034. };
  18035. /** Translate node
  18036. *
  18037. * @param {object} d : calcdata point item
  18038. * @param {sel} sel : d3 selction of node to translate
  18039. * @param {object} xa : corresponding full xaxis object
  18040. * @param {object} ya : corresponding full yaxis object
  18041. *
  18042. * @return {boolean} :
  18043. * true if selection got translated
  18044. * false if selection could not get translated
  18045. */
  18046. drawing.translatePoint = function(d, sel, xa, ya) {
  18047. var x = xa.c2p(d.x);
  18048. var y = ya.c2p(d.y);
  18049. if(isNumeric(x) && isNumeric(y) && sel.node()) {
  18050. // for multiline text this works better
  18051. if(sel.node().nodeName === 'text') {
  18052. sel.attr('x', x).attr('y', y);
  18053. } else {
  18054. sel.attr('transform', 'translate(' + x + ',' + y + ')');
  18055. }
  18056. } else {
  18057. return false;
  18058. }
  18059. return true;
  18060. };
  18061. drawing.translatePoints = function(s, xa, ya) {
  18062. s.each(function(d) {
  18063. var sel = d3.select(this);
  18064. drawing.translatePoint(d, sel, xa, ya);
  18065. });
  18066. };
  18067. drawing.hideOutsideRangePoint = function(d, sel, xa, ya, xcalendar, ycalendar) {
  18068. sel.attr(
  18069. 'display',
  18070. (xa.isPtWithinRange(d, xcalendar) && ya.isPtWithinRange(d, ycalendar)) ? null : 'none'
  18071. );
  18072. };
  18073. drawing.hideOutsideRangePoints = function(traceGroups, subplot) {
  18074. if(!subplot._hasClipOnAxisFalse) return;
  18075. var xa = subplot.xaxis;
  18076. var ya = subplot.yaxis;
  18077. traceGroups.each(function(d) {
  18078. var trace = d[0].trace;
  18079. var xcalendar = trace.xcalendar;
  18080. var ycalendar = trace.ycalendar;
  18081. var selector = trace.type === 'bar' ? '.bartext' : '.point,.textpoint';
  18082. traceGroups.selectAll(selector).each(function(d) {
  18083. drawing.hideOutsideRangePoint(d, d3.select(this), xa, ya, xcalendar, ycalendar);
  18084. });
  18085. });
  18086. };
  18087. drawing.crispRound = function(gd, lineWidth, dflt) {
  18088. // for lines that disable antialiasing we want to
  18089. // make sure the width is an integer, and at least 1 if it's nonzero
  18090. if(!lineWidth || !isNumeric(lineWidth)) return dflt || 0;
  18091. // but not for static plots - these don't get antialiased anyway.
  18092. if(gd._context.staticPlot) return lineWidth;
  18093. if(lineWidth < 1) return 1;
  18094. return Math.round(lineWidth);
  18095. };
  18096. drawing.singleLineStyle = function(d, s, lw, lc, ld) {
  18097. s.style('fill', 'none');
  18098. var line = (((d || [])[0] || {}).trace || {}).line || {};
  18099. var lw1 = lw || line.width||0;
  18100. var dash = ld || line.dash || '';
  18101. Color.stroke(s, lc || line.color);
  18102. drawing.dashLine(s, dash, lw1);
  18103. };
  18104. drawing.lineGroupStyle = function(s, lw, lc, ld) {
  18105. s.style('fill', 'none')
  18106. .each(function(d) {
  18107. var line = (((d || [])[0] || {}).trace || {}).line || {};
  18108. var lw1 = lw || line.width||0;
  18109. var dash = ld || line.dash || '';
  18110. d3.select(this)
  18111. .call(Color.stroke, lc || line.color)
  18112. .call(drawing.dashLine, dash, lw1);
  18113. });
  18114. };
  18115. drawing.dashLine = function(s, dash, lineWidth) {
  18116. lineWidth = +lineWidth || 0;
  18117. dash = drawing.dashStyle(dash, lineWidth);
  18118. s.style({
  18119. 'stroke-dasharray': dash,
  18120. 'stroke-width': lineWidth + 'px'
  18121. });
  18122. };
  18123. drawing.dashStyle = function(dash, lineWidth) {
  18124. lineWidth = +lineWidth || 1;
  18125. var dlw = Math.max(lineWidth, 3);
  18126. if(dash === 'solid') dash = '';
  18127. else if(dash === 'dot') dash = dlw + 'px,' + dlw + 'px';
  18128. else if(dash === 'dash') dash = (3 * dlw) + 'px,' + (3 * dlw) + 'px';
  18129. else if(dash === 'longdash') dash = (5 * dlw) + 'px,' + (5 * dlw) + 'px';
  18130. else if(dash === 'dashdot') {
  18131. dash = (3 * dlw) + 'px,' + dlw + 'px,' + dlw + 'px,' + dlw + 'px';
  18132. }
  18133. else if(dash === 'longdashdot') {
  18134. dash = (5 * dlw) + 'px,' + (2 * dlw) + 'px,' + dlw + 'px,' + (2 * dlw) + 'px';
  18135. }
  18136. // otherwise user wrote the dasharray themselves - leave it be
  18137. return dash;
  18138. };
  18139. // Same as fillGroupStyle, except in this case the selection may be a transition
  18140. drawing.singleFillStyle = function(sel) {
  18141. var node = d3.select(sel.node());
  18142. var data = node.data();
  18143. var fillcolor = (((data[0] || [])[0] || {}).trace || {}).fillcolor;
  18144. if(fillcolor) {
  18145. sel.call(Color.fill, fillcolor);
  18146. }
  18147. };
  18148. drawing.fillGroupStyle = function(s) {
  18149. s.style('stroke-width', 0)
  18150. .each(function(d) {
  18151. var shape = d3.select(this);
  18152. // N.B. 'd' won't be a calcdata item when
  18153. // fill !== 'none' on a segment-less and marker-less trace
  18154. if(d[0].trace) {
  18155. shape.call(Color.fill, d[0].trace.fillcolor);
  18156. }
  18157. });
  18158. };
  18159. var SYMBOLDEFS = _dereq_('./symbol_defs');
  18160. drawing.symbolNames = [];
  18161. drawing.symbolFuncs = [];
  18162. drawing.symbolNeedLines = {};
  18163. drawing.symbolNoDot = {};
  18164. drawing.symbolNoFill = {};
  18165. drawing.symbolList = [];
  18166. Object.keys(SYMBOLDEFS).forEach(function(k) {
  18167. var symDef = SYMBOLDEFS[k];
  18168. drawing.symbolList = drawing.symbolList.concat(
  18169. [symDef.n, k, symDef.n + 100, k + '-open']);
  18170. drawing.symbolNames[symDef.n] = k;
  18171. drawing.symbolFuncs[symDef.n] = symDef.f;
  18172. if(symDef.needLine) {
  18173. drawing.symbolNeedLines[symDef.n] = true;
  18174. }
  18175. if(symDef.noDot) {
  18176. drawing.symbolNoDot[symDef.n] = true;
  18177. }
  18178. else {
  18179. drawing.symbolList = drawing.symbolList.concat(
  18180. [symDef.n + 200, k + '-dot', symDef.n + 300, k + '-open-dot']);
  18181. }
  18182. if(symDef.noFill) {
  18183. drawing.symbolNoFill[symDef.n] = true;
  18184. }
  18185. });
  18186. var MAXSYMBOL = drawing.symbolNames.length;
  18187. // add a dot in the middle of the symbol
  18188. var DOTPATH = 'M0,0.5L0.5,0L0,-0.5L-0.5,0Z';
  18189. drawing.symbolNumber = function(v) {
  18190. if(typeof v === 'string') {
  18191. var vbase = 0;
  18192. if(v.indexOf('-open') > 0) {
  18193. vbase = 100;
  18194. v = v.replace('-open', '');
  18195. }
  18196. if(v.indexOf('-dot') > 0) {
  18197. vbase += 200;
  18198. v = v.replace('-dot', '');
  18199. }
  18200. v = drawing.symbolNames.indexOf(v);
  18201. if(v >= 0) { v += vbase; }
  18202. }
  18203. if((v % 100 >= MAXSYMBOL) || v >= 400) { return 0; }
  18204. return Math.floor(Math.max(v, 0));
  18205. };
  18206. function makePointPath(symbolNumber, r) {
  18207. var base = symbolNumber % 100;
  18208. return drawing.symbolFuncs[base](r) + (symbolNumber >= 200 ? DOTPATH : '');
  18209. }
  18210. var HORZGRADIENT = {x1: 1, x2: 0, y1: 0, y2: 0};
  18211. var VERTGRADIENT = {x1: 0, x2: 0, y1: 1, y2: 0};
  18212. var stopFormatter = d3.format('~.1f');
  18213. var gradientInfo = {
  18214. radial: {node: 'radialGradient'},
  18215. radialreversed: {node: 'radialGradient', reversed: true},
  18216. horizontal: {node: 'linearGradient', attrs: HORZGRADIENT},
  18217. horizontalreversed: {node: 'linearGradient', attrs: HORZGRADIENT, reversed: true},
  18218. vertical: {node: 'linearGradient', attrs: VERTGRADIENT},
  18219. verticalreversed: {node: 'linearGradient', attrs: VERTGRADIENT, reversed: true}
  18220. };
  18221. /**
  18222. * gradient: create and apply a gradient fill
  18223. *
  18224. * @param {object} sel: d3 selection to apply this gradient to
  18225. * You can use `selection.call(Drawing.gradient, ...)`
  18226. * @param {DOM element} gd: the graph div `sel` is part of
  18227. * @param {string} gradientID: a unique (within this plot) identifier
  18228. * for this gradient, so that we don't create unnecessary definitions
  18229. * @param {string} type: 'radial', 'horizontal', or 'vertical', optionally with
  18230. * 'reversed' at the end. Normally radial goes center to edge,
  18231. * horizontal goes right to left, and vertical goes bottom to top
  18232. * @param {array} colorscale: as in attribute values, [[fraction, color], ...]
  18233. * @param {string} prop: the property to apply to, 'fill' or 'stroke'
  18234. */
  18235. drawing.gradient = function(sel, gd, gradientID, type, colorscale, prop) {
  18236. var len = colorscale.length;
  18237. var info = gradientInfo[type];
  18238. var colorStops = new Array(len);
  18239. for(var i = 0; i < len; i++) {
  18240. if(info.reversed) {
  18241. colorStops[len - 1 - i] = [stopFormatter((1 - colorscale[i][0]) * 100), colorscale[i][1]];
  18242. }
  18243. else {
  18244. colorStops[i] = [stopFormatter(colorscale[i][0] * 100), colorscale[i][1]];
  18245. }
  18246. }
  18247. var fullID = 'g' + gd._fullLayout._uid + '-' + gradientID;
  18248. var gradient = gd._fullLayout._defs.select('.gradients')
  18249. .selectAll('#' + fullID)
  18250. .data([type + colorStops.join(';')], Lib.identity);
  18251. gradient.exit().remove();
  18252. gradient.enter()
  18253. .append(info.node)
  18254. .each(function() {
  18255. var el = d3.select(this);
  18256. if(info.attrs) el.attr(info.attrs);
  18257. el.attr('id', fullID);
  18258. var stops = el.selectAll('stop')
  18259. .data(colorStops);
  18260. stops.exit().remove();
  18261. stops.enter().append('stop');
  18262. stops.each(function(d) {
  18263. var tc = tinycolor(d[1]);
  18264. d3.select(this).attr({
  18265. offset: d[0] + '%',
  18266. 'stop-color': Color.tinyRGB(tc),
  18267. 'stop-opacity': tc.getAlpha()
  18268. });
  18269. });
  18270. });
  18271. sel.style(prop, 'url(#' + fullID + ')')
  18272. .style(prop + '-opacity', null);
  18273. };
  18274. /*
  18275. * Make the gradients container and clear out any previous gradients.
  18276. * We never collect all the gradients we need in one place,
  18277. * so we can't ever remove gradients that have stopped being useful,
  18278. * except all at once before a full redraw.
  18279. * The upside of this is arbitrary points can share gradient defs
  18280. */
  18281. drawing.initGradients = function(gd) {
  18282. var gradientsGroup = Lib.ensureSingle(gd._fullLayout._defs, 'g', 'gradients');
  18283. gradientsGroup.selectAll('linearGradient,radialGradient').remove();
  18284. };
  18285. drawing.pointStyle = function(s, trace, gd) {
  18286. if(!s.size()) return;
  18287. var fns = drawing.makePointStyleFns(trace);
  18288. s.each(function(d) {
  18289. drawing.singlePointStyle(d, d3.select(this), trace, fns, gd);
  18290. });
  18291. };
  18292. drawing.singlePointStyle = function(d, sel, trace, fns, gd) {
  18293. var marker = trace.marker;
  18294. var markerLine = marker.line;
  18295. sel.style('opacity',
  18296. fns.selectedOpacityFn ? fns.selectedOpacityFn(d) :
  18297. (d.mo === undefined ? marker.opacity : d.mo)
  18298. );
  18299. if(fns.ms2mrc) {
  18300. var r;
  18301. // handle multi-trace graph edit case
  18302. if(d.ms === 'various' || marker.size === 'various') {
  18303. r = 3;
  18304. } else {
  18305. r = fns.ms2mrc(d.ms);
  18306. }
  18307. // store the calculated size so hover can use it
  18308. d.mrc = r;
  18309. if(fns.selectedSizeFn) {
  18310. r = d.mrc = fns.selectedSizeFn(d);
  18311. }
  18312. // turn the symbol into a sanitized number
  18313. var x = drawing.symbolNumber(d.mx || marker.symbol) || 0;
  18314. // save if this marker is open
  18315. // because that impacts how to handle colors
  18316. d.om = x % 200 >= 100;
  18317. sel.attr('d', makePointPath(x, r));
  18318. }
  18319. var perPointGradient = false;
  18320. var fillColor, lineColor, lineWidth;
  18321. // 'so' is suspected outliers, for box plots
  18322. if(d.so) {
  18323. lineWidth = markerLine.outlierwidth;
  18324. lineColor = markerLine.outliercolor;
  18325. fillColor = marker.outliercolor;
  18326. } else {
  18327. var markerLineWidth = (markerLine || {}).width;
  18328. lineWidth = (
  18329. d.mlw + 1 ||
  18330. markerLineWidth + 1 ||
  18331. // TODO: we need the latter for legends... can we get rid of it?
  18332. (d.trace ? (d.trace.marker.line || {}).width : 0) + 1
  18333. ) - 1 || 0;
  18334. if('mlc' in d) lineColor = d.mlcc = fns.lineScale(d.mlc);
  18335. // weird case: array wasn't long enough to apply to every point
  18336. else if(Lib.isArrayOrTypedArray(markerLine.color)) lineColor = Color.defaultLine;
  18337. else lineColor = markerLine.color;
  18338. if(Lib.isArrayOrTypedArray(marker.color)) {
  18339. fillColor = Color.defaultLine;
  18340. perPointGradient = true;
  18341. }
  18342. if('mc' in d) {
  18343. fillColor = d.mcc = fns.markerScale(d.mc);
  18344. } else {
  18345. fillColor = marker.color || 'rgba(0,0,0,0)';
  18346. }
  18347. if(fns.selectedColorFn) {
  18348. fillColor = fns.selectedColorFn(d);
  18349. }
  18350. }
  18351. if(d.om) {
  18352. // open markers can't have zero linewidth, default to 1px,
  18353. // and use fill color as stroke color
  18354. sel.call(Color.stroke, fillColor)
  18355. .style({
  18356. 'stroke-width': (lineWidth || 1) + 'px',
  18357. fill: 'none'
  18358. });
  18359. } else {
  18360. sel.style('stroke-width', lineWidth + 'px');
  18361. var markerGradient = marker.gradient;
  18362. var gradientType = d.mgt;
  18363. if(gradientType) perPointGradient = true;
  18364. else gradientType = markerGradient && markerGradient.type;
  18365. // for legend - arrays will propagate through here, but we don't need
  18366. // to treat it as per-point.
  18367. if(Array.isArray(gradientType)) {
  18368. gradientType = gradientType[0];
  18369. if(!gradientInfo[gradientType]) gradientType = 0;
  18370. }
  18371. if(gradientType && gradientType !== 'none') {
  18372. var gradientColor = d.mgc;
  18373. if(gradientColor) perPointGradient = true;
  18374. else gradientColor = markerGradient.color;
  18375. var gradientID = trace.uid;
  18376. if(perPointGradient) gradientID += '-' + d.i;
  18377. drawing.gradient(sel, gd, gradientID, gradientType,
  18378. [[0, gradientColor], [1, fillColor]], 'fill');
  18379. } else {
  18380. Color.fill(sel, fillColor);
  18381. }
  18382. if(lineWidth) {
  18383. Color.stroke(sel, lineColor);
  18384. }
  18385. }
  18386. };
  18387. drawing.makePointStyleFns = function(trace) {
  18388. var out = {};
  18389. var marker = trace.marker;
  18390. // allow array marker and marker line colors to be
  18391. // scaled by given max and min to colorscales
  18392. out.markerScale = drawing.tryColorscale(marker, '');
  18393. out.lineScale = drawing.tryColorscale(marker, 'line');
  18394. if(Registry.traceIs(trace, 'symbols')) {
  18395. out.ms2mrc = subTypes.isBubble(trace) ?
  18396. makeBubbleSizeFn(trace) :
  18397. function() { return (marker.size || 6) / 2; };
  18398. }
  18399. if(trace.selectedpoints) {
  18400. Lib.extendFlat(out, drawing.makeSelectedPointStyleFns(trace));
  18401. }
  18402. return out;
  18403. };
  18404. drawing.makeSelectedPointStyleFns = function(trace) {
  18405. var out = {};
  18406. var selectedAttrs = trace.selected || {};
  18407. var unselectedAttrs = trace.unselected || {};
  18408. var marker = trace.marker || {};
  18409. var selectedMarker = selectedAttrs.marker || {};
  18410. var unselectedMarker = unselectedAttrs.marker || {};
  18411. var mo = marker.opacity;
  18412. var smo = selectedMarker.opacity;
  18413. var usmo = unselectedMarker.opacity;
  18414. var smoIsDefined = smo !== undefined;
  18415. var usmoIsDefined = usmo !== undefined;
  18416. if(Lib.isArrayOrTypedArray(mo) || smoIsDefined || usmoIsDefined) {
  18417. out.selectedOpacityFn = function(d) {
  18418. var base = d.mo === undefined ? marker.opacity : d.mo;
  18419. if(d.selected) {
  18420. return smoIsDefined ? smo : base;
  18421. } else {
  18422. return usmoIsDefined ? usmo : DESELECTDIM * base;
  18423. }
  18424. };
  18425. }
  18426. var mc = marker.color;
  18427. var smc = selectedMarker.color;
  18428. var usmc = unselectedMarker.color;
  18429. if(smc || usmc) {
  18430. out.selectedColorFn = function(d) {
  18431. var base = d.mcc || mc;
  18432. if(d.selected) {
  18433. return smc || base;
  18434. } else {
  18435. return usmc || base;
  18436. }
  18437. };
  18438. }
  18439. var ms = marker.size;
  18440. var sms = selectedMarker.size;
  18441. var usms = unselectedMarker.size;
  18442. var smsIsDefined = sms !== undefined;
  18443. var usmsIsDefined = usms !== undefined;
  18444. if(Registry.traceIs(trace, 'symbols') && (smsIsDefined || usmsIsDefined)) {
  18445. out.selectedSizeFn = function(d) {
  18446. var base = d.mrc || ms / 2;
  18447. if(d.selected) {
  18448. return smsIsDefined ? sms / 2 : base;
  18449. } else {
  18450. return usmsIsDefined ? usms / 2 : base;
  18451. }
  18452. };
  18453. }
  18454. return out;
  18455. };
  18456. drawing.makeSelectedTextStyleFns = function(trace) {
  18457. var out = {};
  18458. var selectedAttrs = trace.selected || {};
  18459. var unselectedAttrs = trace.unselected || {};
  18460. var textFont = trace.textfont || {};
  18461. var selectedTextFont = selectedAttrs.textfont || {};
  18462. var unselectedTextFont = unselectedAttrs.textfont || {};
  18463. var tc = textFont.color;
  18464. var stc = selectedTextFont.color;
  18465. var utc = unselectedTextFont.color;
  18466. out.selectedTextColorFn = function(d) {
  18467. var base = d.tc || tc;
  18468. if(d.selected) {
  18469. return stc || base;
  18470. } else {
  18471. if(utc) return utc;
  18472. else return stc ? base : Color.addOpacity(base, DESELECTDIM);
  18473. }
  18474. };
  18475. return out;
  18476. };
  18477. drawing.selectedPointStyle = function(s, trace) {
  18478. if(!s.size() || !trace.selectedpoints) return;
  18479. var fns = drawing.makeSelectedPointStyleFns(trace);
  18480. var marker = trace.marker || {};
  18481. var seq = [];
  18482. if(fns.selectedOpacityFn) {
  18483. seq.push(function(pt, d) {
  18484. pt.style('opacity', fns.selectedOpacityFn(d));
  18485. });
  18486. }
  18487. if(fns.selectedColorFn) {
  18488. seq.push(function(pt, d) {
  18489. Color.fill(pt, fns.selectedColorFn(d));
  18490. });
  18491. }
  18492. if(fns.selectedSizeFn) {
  18493. seq.push(function(pt, d) {
  18494. var mx = d.mx || marker.symbol || 0;
  18495. var mrc2 = fns.selectedSizeFn(d);
  18496. pt.attr('d', makePointPath(drawing.symbolNumber(mx), mrc2));
  18497. // save for Drawing.selectedTextStyle
  18498. d.mrc2 = mrc2;
  18499. });
  18500. }
  18501. if(seq.length) {
  18502. s.each(function(d) {
  18503. var pt = d3.select(this);
  18504. for(var i = 0; i < seq.length; i++) {
  18505. seq[i](pt, d);
  18506. }
  18507. });
  18508. }
  18509. };
  18510. drawing.tryColorscale = function(marker, prefix) {
  18511. var cont = prefix ? Lib.nestedProperty(marker, prefix).get() : marker;
  18512. if(cont) {
  18513. var scl = cont.colorscale;
  18514. var colorArray = cont.color;
  18515. if(scl && Lib.isArrayOrTypedArray(colorArray)) {
  18516. return Colorscale.makeColorScaleFunc(
  18517. Colorscale.extractScale(cont, {cLetter: 'c'})
  18518. );
  18519. }
  18520. }
  18521. return Lib.identity;
  18522. };
  18523. var TEXTOFFSETSIGN = {
  18524. start: 1, end: -1, middle: 0, bottom: 1, top: -1
  18525. };
  18526. function textPointPosition(s, textPosition, fontSize, markerRadius) {
  18527. var group = d3.select(s.node().parentNode);
  18528. var v = textPosition.indexOf('top') !== -1 ?
  18529. 'top' :
  18530. textPosition.indexOf('bottom') !== -1 ? 'bottom' : 'middle';
  18531. var h = textPosition.indexOf('left') !== -1 ?
  18532. 'end' :
  18533. textPosition.indexOf('right') !== -1 ? 'start' : 'middle';
  18534. // if markers are shown, offset a little more than
  18535. // the nominal marker size
  18536. // ie 2/1.6 * nominal, bcs some markers are a bit bigger
  18537. var r = markerRadius ? markerRadius / 0.8 + 1 : 0;
  18538. var numLines = (svgTextUtils.lineCount(s) - 1) * LINE_SPACING + 1;
  18539. var dx = TEXTOFFSETSIGN[h] * r;
  18540. var dy = fontSize * 0.75 + TEXTOFFSETSIGN[v] * r +
  18541. (TEXTOFFSETSIGN[v] - 1) * numLines * fontSize / 2;
  18542. // fix the overall text group position
  18543. s.attr('text-anchor', h);
  18544. group.attr('transform', 'translate(' + dx + ',' + dy + ')');
  18545. }
  18546. function extracTextFontSize(d, trace) {
  18547. var fontSize = d.ts || trace.textfont.size;
  18548. return (isNumeric(fontSize) && fontSize > 0) ? fontSize : 0;
  18549. }
  18550. // draw text at points
  18551. drawing.textPointStyle = function(s, trace, gd) {
  18552. if(!s.size()) return;
  18553. var selectedTextColorFn;
  18554. if(trace.selectedpoints) {
  18555. var fns = drawing.makeSelectedTextStyleFns(trace);
  18556. selectedTextColorFn = fns.selectedTextColorFn;
  18557. }
  18558. s.each(function(d) {
  18559. var p = d3.select(this);
  18560. var text = Lib.extractOption(d, trace, 'tx', 'text');
  18561. if(!text && text !== 0) {
  18562. p.remove();
  18563. return;
  18564. }
  18565. var pos = d.tp || trace.textposition;
  18566. var fontSize = extracTextFontSize(d, trace);
  18567. var fontColor = selectedTextColorFn ?
  18568. selectedTextColorFn(d) :
  18569. (d.tc || trace.textfont.color);
  18570. p.call(drawing.font,
  18571. d.tf || trace.textfont.family,
  18572. fontSize,
  18573. fontColor)
  18574. .text(text)
  18575. .call(svgTextUtils.convertToTspans, gd)
  18576. .call(textPointPosition, pos, fontSize, d.mrc);
  18577. });
  18578. };
  18579. drawing.selectedTextStyle = function(s, trace) {
  18580. if(!s.size() || !trace.selectedpoints) return;
  18581. var fns = drawing.makeSelectedTextStyleFns(trace);
  18582. s.each(function(d) {
  18583. var tx = d3.select(this);
  18584. var tc = fns.selectedTextColorFn(d);
  18585. var tp = d.tp || trace.textposition;
  18586. var fontSize = extracTextFontSize(d, trace);
  18587. Color.fill(tx, tc);
  18588. textPointPosition(tx, tp, fontSize, d.mrc2 || d.mrc);
  18589. });
  18590. };
  18591. // generalized Catmull-Rom splines, per
  18592. // http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
  18593. var CatmullRomExp = 0.5;
  18594. drawing.smoothopen = function(pts, smoothness) {
  18595. if(pts.length < 3) { return 'M' + pts.join('L');}
  18596. var path = 'M' + pts[0];
  18597. var tangents = [];
  18598. var i;
  18599. for(i = 1; i < pts.length - 1; i++) {
  18600. tangents.push(makeTangent(pts[i - 1], pts[i], pts[i + 1], smoothness));
  18601. }
  18602. path += 'Q' + tangents[0][0] + ' ' + pts[1];
  18603. for(i = 2; i < pts.length - 1; i++) {
  18604. path += 'C' + tangents[i - 2][1] + ' ' + tangents[i - 1][0] + ' ' + pts[i];
  18605. }
  18606. path += 'Q' + tangents[pts.length - 3][1] + ' ' + pts[pts.length - 1];
  18607. return path;
  18608. };
  18609. drawing.smoothclosed = function(pts, smoothness) {
  18610. if(pts.length < 3) { return 'M' + pts.join('L') + 'Z'; }
  18611. var path = 'M' + pts[0];
  18612. var pLast = pts.length - 1;
  18613. var tangents = [makeTangent(pts[pLast], pts[0], pts[1], smoothness)];
  18614. var i;
  18615. for(i = 1; i < pLast; i++) {
  18616. tangents.push(makeTangent(pts[i - 1], pts[i], pts[i + 1], smoothness));
  18617. }
  18618. tangents.push(
  18619. makeTangent(pts[pLast - 1], pts[pLast], pts[0], smoothness)
  18620. );
  18621. for(i = 1; i <= pLast; i++) {
  18622. path += 'C' + tangents[i - 1][1] + ' ' + tangents[i][0] + ' ' + pts[i];
  18623. }
  18624. path += 'C' + tangents[pLast][1] + ' ' + tangents[0][0] + ' ' + pts[0] + 'Z';
  18625. return path;
  18626. };
  18627. function makeTangent(prevpt, thispt, nextpt, smoothness) {
  18628. var d1x = prevpt[0] - thispt[0];
  18629. var d1y = prevpt[1] - thispt[1];
  18630. var d2x = nextpt[0] - thispt[0];
  18631. var d2y = nextpt[1] - thispt[1];
  18632. var d1a = Math.pow(d1x * d1x + d1y * d1y, CatmullRomExp / 2);
  18633. var d2a = Math.pow(d2x * d2x + d2y * d2y, CatmullRomExp / 2);
  18634. var numx = (d2a * d2a * d1x - d1a * d1a * d2x) * smoothness;
  18635. var numy = (d2a * d2a * d1y - d1a * d1a * d2y) * smoothness;
  18636. var denom1 = 3 * d2a * (d1a + d2a);
  18637. var denom2 = 3 * d1a * (d1a + d2a);
  18638. return [
  18639. [
  18640. d3.round(thispt[0] + (denom1 && numx / denom1), 2),
  18641. d3.round(thispt[1] + (denom1 && numy / denom1), 2)
  18642. ], [
  18643. d3.round(thispt[0] - (denom2 && numx / denom2), 2),
  18644. d3.round(thispt[1] - (denom2 && numy / denom2), 2)
  18645. ]
  18646. ];
  18647. }
  18648. // step paths - returns a generator function for paths
  18649. // with the given step shape
  18650. var STEPPATH = {
  18651. hv: function(p0, p1) {
  18652. return 'H' + d3.round(p1[0], 2) + 'V' + d3.round(p1[1], 2);
  18653. },
  18654. vh: function(p0, p1) {
  18655. return 'V' + d3.round(p1[1], 2) + 'H' + d3.round(p1[0], 2);
  18656. },
  18657. hvh: function(p0, p1) {
  18658. return 'H' + d3.round((p0[0] + p1[0]) / 2, 2) + 'V' +
  18659. d3.round(p1[1], 2) + 'H' + d3.round(p1[0], 2);
  18660. },
  18661. vhv: function(p0, p1) {
  18662. return 'V' + d3.round((p0[1] + p1[1]) / 2, 2) + 'H' +
  18663. d3.round(p1[0], 2) + 'V' + d3.round(p1[1], 2);
  18664. }
  18665. };
  18666. var STEPLINEAR = function(p0, p1) {
  18667. return 'L' + d3.round(p1[0], 2) + ',' + d3.round(p1[1], 2);
  18668. };
  18669. drawing.steps = function(shape) {
  18670. var onestep = STEPPATH[shape] || STEPLINEAR;
  18671. return function(pts) {
  18672. var path = 'M' + d3.round(pts[0][0], 2) + ',' + d3.round(pts[0][1], 2);
  18673. for(var i = 1; i < pts.length; i++) {
  18674. path += onestep(pts[i - 1], pts[i]);
  18675. }
  18676. return path;
  18677. };
  18678. };
  18679. // off-screen svg render testing element, shared by the whole page
  18680. // uses the id 'js-plotly-tester' and stores it in drawing.tester
  18681. drawing.makeTester = function() {
  18682. var tester = Lib.ensureSingleById(d3.select('body'), 'svg', 'js-plotly-tester', function(s) {
  18683. s.attr(xmlnsNamespaces.svgAttrs)
  18684. .style({
  18685. position: 'absolute',
  18686. left: '-10000px',
  18687. top: '-10000px',
  18688. width: '9000px',
  18689. height: '9000px',
  18690. 'z-index': '1'
  18691. });
  18692. });
  18693. // browsers differ on how they describe the bounding rect of
  18694. // the svg if its contents spill over... so make a 1x1px
  18695. // reference point we can measure off of.
  18696. var testref = Lib.ensureSingle(tester, 'path', 'js-reference-point', function(s) {
  18697. s.attr('d', 'M0,0H1V1H0Z')
  18698. .style({
  18699. 'stroke-width': 0,
  18700. fill: 'black'
  18701. });
  18702. });
  18703. drawing.tester = tester;
  18704. drawing.testref = testref;
  18705. };
  18706. /*
  18707. * use our offscreen tester to get a clientRect for an element,
  18708. * in a reference frame where it isn't translated (or transformed) and
  18709. * its anchor point is at (0,0)
  18710. * always returns a copy of the bbox, so the caller can modify it safely
  18711. *
  18712. * @param {SVGElement} node: the element to measure. If possible this should be
  18713. * a <text> or MathJax <g> element that's already passed through
  18714. * `convertToTspans` because in that case we can cache the results, but it's
  18715. * possible to pass in any svg element.
  18716. *
  18717. * @param {boolean} inTester: is this element already in `drawing.tester`?
  18718. * If you are measuring a dummy element, rather than one you really intend
  18719. * to use on the plot, making it in `drawing.tester` in the first place
  18720. * allows us to test faster because it cuts out cloning and appending it.
  18721. *
  18722. * @param {string} hash: for internal use only, if we already know the cache key
  18723. * for this element beforehand.
  18724. *
  18725. * @return {object}: a plain object containing the width, height, left, right,
  18726. * top, and bottom of `node`
  18727. */
  18728. drawing.savedBBoxes = {};
  18729. var savedBBoxesCount = 0;
  18730. var maxSavedBBoxes = 10000;
  18731. drawing.bBox = function(node, inTester, hash) {
  18732. /*
  18733. * Cache elements we've already measured so we don't have to
  18734. * remeasure the same thing many times
  18735. * We have a few bBox callers though who pass a node larger than
  18736. * a <text> or a MathJax <g>, such as an axis group containing many labels.
  18737. * These will not generate a hash (unless we figure out an appropriate
  18738. * hash key for them) and thus we will not hash them.
  18739. */
  18740. if(!hash) hash = nodeHash(node);
  18741. var out;
  18742. if(hash) {
  18743. out = drawing.savedBBoxes[hash];
  18744. if(out) return Lib.extendFlat({}, out);
  18745. }
  18746. else if(node.childNodes.length === 1) {
  18747. /*
  18748. * If we have only one child element, which is itself hashable, make
  18749. * a new hash from this element plus its x,y,transform
  18750. * These bounding boxes *include* x,y,transform - mostly for use by
  18751. * callers trying to avoid overlaps (ie titles)
  18752. */
  18753. var innerNode = node.childNodes[0];
  18754. hash = nodeHash(innerNode);
  18755. if(hash) {
  18756. var x = +innerNode.getAttribute('x') || 0;
  18757. var y = +innerNode.getAttribute('y') || 0;
  18758. var transform = innerNode.getAttribute('transform');
  18759. if(!transform) {
  18760. // in this case, just varying x and y, don't bother caching
  18761. // the final bBox because the alteration is quick.
  18762. var innerBB = drawing.bBox(innerNode, false, hash);
  18763. if(x) {
  18764. innerBB.left += x;
  18765. innerBB.right += x;
  18766. }
  18767. if(y) {
  18768. innerBB.top += y;
  18769. innerBB.bottom += y;
  18770. }
  18771. return innerBB;
  18772. }
  18773. /*
  18774. * else we have a transform - rather than make a complicated
  18775. * (and error-prone and probably slow) transform parser/calculator,
  18776. * just continue on calculating the boundingClientRect of the group
  18777. * and use the new composite hash to cache it.
  18778. * That said, `innerNode.transform.baseVal` is an array of
  18779. * `SVGTransform` objects, that *do* seem to have a nice matrix
  18780. * multiplication interface that we could use to avoid making
  18781. * another getBoundingClientRect call...
  18782. */
  18783. hash += '~' + x + '~' + y + '~' + transform;
  18784. out = drawing.savedBBoxes[hash];
  18785. if(out) return Lib.extendFlat({}, out);
  18786. }
  18787. }
  18788. var testNode, tester;
  18789. if(inTester) {
  18790. testNode = node;
  18791. }
  18792. else {
  18793. tester = drawing.tester.node();
  18794. // copy the node to test into the tester
  18795. testNode = node.cloneNode(true);
  18796. tester.appendChild(testNode);
  18797. }
  18798. // standardize its position (and newline tspans if any)
  18799. d3.select(testNode)
  18800. .attr('transform', null)
  18801. .call(svgTextUtils.positionText, 0, 0);
  18802. var testRect = testNode.getBoundingClientRect();
  18803. var refRect = drawing.testref
  18804. .node()
  18805. .getBoundingClientRect();
  18806. if(!inTester) tester.removeChild(testNode);
  18807. var bb = {
  18808. height: testRect.height,
  18809. width: testRect.width,
  18810. left: testRect.left - refRect.left,
  18811. top: testRect.top - refRect.top,
  18812. right: testRect.right - refRect.left,
  18813. bottom: testRect.bottom - refRect.top
  18814. };
  18815. // make sure we don't have too many saved boxes,
  18816. // or a long session could overload on memory
  18817. // by saving boxes for long-gone elements
  18818. if(savedBBoxesCount >= maxSavedBBoxes) {
  18819. drawing.savedBBoxes = {};
  18820. savedBBoxesCount = 0;
  18821. }
  18822. // cache this bbox
  18823. if(hash) drawing.savedBBoxes[hash] = bb;
  18824. savedBBoxesCount++;
  18825. return Lib.extendFlat({}, bb);
  18826. };
  18827. // capture everything about a node (at least in our usage) that
  18828. // impacts its bounding box, given that bBox clears x, y, and transform
  18829. function nodeHash(node) {
  18830. var inputText = node.getAttribute('data-unformatted');
  18831. if(inputText === null) return;
  18832. return inputText +
  18833. node.getAttribute('data-math') +
  18834. node.getAttribute('text-anchor') +
  18835. node.getAttribute('style');
  18836. }
  18837. /**
  18838. * Set clipPath URL in a way that work for all situations.
  18839. *
  18840. * In details, graphs on pages with <base> HTML tags need to prepend
  18841. * the clip path ids with the page's base url EXCEPT during toImage exports.
  18842. *
  18843. * @param {d3 selection} s : node to add clip-path attribute
  18844. * @param {string} localId : local clip-path (w/o base url) id
  18845. * @param {DOM element || object} gd
  18846. * - context._baseUrl {string}
  18847. * - context._exportedPlot {boolean}
  18848. */
  18849. drawing.setClipUrl = function(s, localId, gd) {
  18850. if(!localId) {
  18851. s.attr('clip-path', null);
  18852. return;
  18853. }
  18854. var context = gd._context;
  18855. var baseUrl = context._exportedPlot ? '' : (context._baseUrl || '');
  18856. s.attr('clip-path', 'url(' + baseUrl + '#' + localId + ')');
  18857. };
  18858. drawing.getTranslate = function(element) {
  18859. // Note the separator [^\d] between x and y in this regex
  18860. // We generally use ',' but IE will convert it to ' '
  18861. var re = /.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/;
  18862. var getter = element.attr ? 'attr' : 'getAttribute';
  18863. var transform = element[getter]('transform') || '';
  18864. var translate = transform.replace(re, function(match, p1, p2) {
  18865. return [p1, p2].join(' ');
  18866. })
  18867. .split(' ');
  18868. return {
  18869. x: +translate[0] || 0,
  18870. y: +translate[1] || 0
  18871. };
  18872. };
  18873. drawing.setTranslate = function(element, x, y) {
  18874. var re = /(\btranslate\(.*?\);?)/;
  18875. var getter = element.attr ? 'attr' : 'getAttribute';
  18876. var setter = element.attr ? 'attr' : 'setAttribute';
  18877. var transform = element[getter]('transform') || '';
  18878. x = x || 0;
  18879. y = y || 0;
  18880. transform = transform.replace(re, '').trim();
  18881. transform += ' translate(' + x + ', ' + y + ')';
  18882. transform = transform.trim();
  18883. element[setter]('transform', transform);
  18884. return transform;
  18885. };
  18886. drawing.getScale = function(element) {
  18887. var re = /.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/;
  18888. var getter = element.attr ? 'attr' : 'getAttribute';
  18889. var transform = element[getter]('transform') || '';
  18890. var translate = transform.replace(re, function(match, p1, p2) {
  18891. return [p1, p2].join(' ');
  18892. })
  18893. .split(' ');
  18894. return {
  18895. x: +translate[0] || 1,
  18896. y: +translate[1] || 1
  18897. };
  18898. };
  18899. drawing.setScale = function(element, x, y) {
  18900. var re = /(\bscale\(.*?\);?)/;
  18901. var getter = element.attr ? 'attr' : 'getAttribute';
  18902. var setter = element.attr ? 'attr' : 'setAttribute';
  18903. var transform = element[getter]('transform') || '';
  18904. x = x || 1;
  18905. y = y || 1;
  18906. transform = transform.replace(re, '').trim();
  18907. transform += ' scale(' + x + ', ' + y + ')';
  18908. transform = transform.trim();
  18909. element[setter]('transform', transform);
  18910. return transform;
  18911. };
  18912. var SCALE_RE = /\s*sc.*/;
  18913. drawing.setPointGroupScale = function(selection, xScale, yScale) {
  18914. xScale = xScale || 1;
  18915. yScale = yScale || 1;
  18916. if(!selection) return;
  18917. // The same scale transform for every point:
  18918. var scale = (xScale === 1 && yScale === 1) ?
  18919. '' :
  18920. ' scale(' + xScale + ',' + yScale + ')';
  18921. selection.each(function() {
  18922. var t = (this.getAttribute('transform') || '').replace(SCALE_RE, '');
  18923. t += scale;
  18924. t = t.trim();
  18925. this.setAttribute('transform', t);
  18926. });
  18927. };
  18928. var TEXT_POINT_LAST_TRANSLATION_RE = /translate\([^)]*\)\s*$/;
  18929. drawing.setTextPointsScale = function(selection, xScale, yScale) {
  18930. if(!selection) return;
  18931. selection.each(function() {
  18932. var transforms;
  18933. var el = d3.select(this);
  18934. var text = el.select('text');
  18935. if(!text.node()) return;
  18936. var x = parseFloat(text.attr('x') || 0);
  18937. var y = parseFloat(text.attr('y') || 0);
  18938. var existingTransform = (el.attr('transform') || '').match(TEXT_POINT_LAST_TRANSLATION_RE);
  18939. if(xScale === 1 && yScale === 1) {
  18940. transforms = [];
  18941. } else {
  18942. transforms = [
  18943. 'translate(' + x + ',' + y + ')',
  18944. 'scale(' + xScale + ',' + yScale + ')',
  18945. 'translate(' + (-x) + ',' + (-y) + ')',
  18946. ];
  18947. }
  18948. if(existingTransform) {
  18949. transforms.push(existingTransform);
  18950. }
  18951. el.attr('transform', transforms.join(' '));
  18952. });
  18953. };
  18954. },{"../../constants/alignment":146,"../../constants/interactions":148,"../../constants/xmlns_namespaces":150,"../../lib":168,"../../lib/svg_text_utils":189,"../../registry":257,"../../traces/scatter/make_bubble_size_func":384,"../../traces/scatter/subtypes":391,"../color":51,"../colorscale":63,"./symbol_defs":73,"d3":16,"fast-isnumeric":18,"tinycolor2":34}],73:[function(_dereq_,module,exports){
  18955. /**
  18956. * Copyright 2012-2019, Plotly, Inc.
  18957. * All rights reserved.
  18958. *
  18959. * This source code is licensed under the MIT license found in the
  18960. * LICENSE file in the root directory of this source tree.
  18961. */
  18962. 'use strict';
  18963. var d3 = _dereq_('d3');
  18964. /** Marker symbol definitions
  18965. * users can specify markers either by number or name
  18966. * add 100 (or '-open') and you get an open marker
  18967. * open markers have no fill and use line color as the stroke color
  18968. * add 200 (or '-dot') and you get a dot in the middle
  18969. * add both and you get both
  18970. */
  18971. module.exports = {
  18972. circle: {
  18973. n: 0,
  18974. f: function(r) {
  18975. var rs = d3.round(r, 2);
  18976. return 'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs +
  18977. 'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z';
  18978. }
  18979. },
  18980. square: {
  18981. n: 1,
  18982. f: function(r) {
  18983. var rs = d3.round(r, 2);
  18984. return 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z';
  18985. }
  18986. },
  18987. diamond: {
  18988. n: 2,
  18989. f: function(r) {
  18990. var rd = d3.round(r * 1.3, 2);
  18991. return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z';
  18992. }
  18993. },
  18994. cross: {
  18995. n: 3,
  18996. f: function(r) {
  18997. var rc = d3.round(r * 0.4, 2);
  18998. var rc2 = d3.round(r * 1.2, 2);
  18999. return 'M' + rc2 + ',' + rc + 'H' + rc + 'V' + rc2 + 'H-' + rc +
  19000. 'V' + rc + 'H-' + rc2 + 'V-' + rc + 'H-' + rc + 'V-' + rc2 +
  19001. 'H' + rc + 'V-' + rc + 'H' + rc2 + 'Z';
  19002. }
  19003. },
  19004. x: {
  19005. n: 4,
  19006. f: function(r) {
  19007. var rx = d3.round(r * 0.8 / Math.sqrt(2), 2);
  19008. var ne = 'l' + rx + ',' + rx;
  19009. var se = 'l' + rx + ',-' + rx;
  19010. var sw = 'l-' + rx + ',-' + rx;
  19011. var nw = 'l-' + rx + ',' + rx;
  19012. return 'M0,' + rx + ne + se + sw + se + sw + nw + sw + nw + ne + nw + ne + 'Z';
  19013. }
  19014. },
  19015. 'triangle-up': {
  19016. n: 5,
  19017. f: function(r) {
  19018. var rt = d3.round(r * 2 / Math.sqrt(3), 2);
  19019. var r2 = d3.round(r / 2, 2);
  19020. var rs = d3.round(r, 2);
  19021. return 'M-' + rt + ',' + r2 + 'H' + rt + 'L0,-' + rs + 'Z';
  19022. }
  19023. },
  19024. 'triangle-down': {
  19025. n: 6,
  19026. f: function(r) {
  19027. var rt = d3.round(r * 2 / Math.sqrt(3), 2);
  19028. var r2 = d3.round(r / 2, 2);
  19029. var rs = d3.round(r, 2);
  19030. return 'M-' + rt + ',-' + r2 + 'H' + rt + 'L0,' + rs + 'Z';
  19031. }
  19032. },
  19033. 'triangle-left': {
  19034. n: 7,
  19035. f: function(r) {
  19036. var rt = d3.round(r * 2 / Math.sqrt(3), 2);
  19037. var r2 = d3.round(r / 2, 2);
  19038. var rs = d3.round(r, 2);
  19039. return 'M' + r2 + ',-' + rt + 'V' + rt + 'L-' + rs + ',0Z';
  19040. }
  19041. },
  19042. 'triangle-right': {
  19043. n: 8,
  19044. f: function(r) {
  19045. var rt = d3.round(r * 2 / Math.sqrt(3), 2);
  19046. var r2 = d3.round(r / 2, 2);
  19047. var rs = d3.round(r, 2);
  19048. return 'M-' + r2 + ',-' + rt + 'V' + rt + 'L' + rs + ',0Z';
  19049. }
  19050. },
  19051. 'triangle-ne': {
  19052. n: 9,
  19053. f: function(r) {
  19054. var r1 = d3.round(r * 0.6, 2);
  19055. var r2 = d3.round(r * 1.2, 2);
  19056. return 'M-' + r2 + ',-' + r1 + 'H' + r1 + 'V' + r2 + 'Z';
  19057. }
  19058. },
  19059. 'triangle-se': {
  19060. n: 10,
  19061. f: function(r) {
  19062. var r1 = d3.round(r * 0.6, 2);
  19063. var r2 = d3.round(r * 1.2, 2);
  19064. return 'M' + r1 + ',-' + r2 + 'V' + r1 + 'H-' + r2 + 'Z';
  19065. }
  19066. },
  19067. 'triangle-sw': {
  19068. n: 11,
  19069. f: function(r) {
  19070. var r1 = d3.round(r * 0.6, 2);
  19071. var r2 = d3.round(r * 1.2, 2);
  19072. return 'M' + r2 + ',' + r1 + 'H-' + r1 + 'V-' + r2 + 'Z';
  19073. }
  19074. },
  19075. 'triangle-nw': {
  19076. n: 12,
  19077. f: function(r) {
  19078. var r1 = d3.round(r * 0.6, 2);
  19079. var r2 = d3.round(r * 1.2, 2);
  19080. return 'M-' + r1 + ',' + r2 + 'V-' + r1 + 'H' + r2 + 'Z';
  19081. }
  19082. },
  19083. pentagon: {
  19084. n: 13,
  19085. f: function(r) {
  19086. var x1 = d3.round(r * 0.951, 2);
  19087. var x2 = d3.round(r * 0.588, 2);
  19088. var y0 = d3.round(-r, 2);
  19089. var y1 = d3.round(r * -0.309, 2);
  19090. var y2 = d3.round(r * 0.809, 2);
  19091. return 'M' + x1 + ',' + y1 + 'L' + x2 + ',' + y2 + 'H-' + x2 +
  19092. 'L-' + x1 + ',' + y1 + 'L0,' + y0 + 'Z';
  19093. }
  19094. },
  19095. hexagon: {
  19096. n: 14,
  19097. f: function(r) {
  19098. var y0 = d3.round(r, 2);
  19099. var y1 = d3.round(r / 2, 2);
  19100. var x = d3.round(r * Math.sqrt(3) / 2, 2);
  19101. return 'M' + x + ',-' + y1 + 'V' + y1 + 'L0,' + y0 +
  19102. 'L-' + x + ',' + y1 + 'V-' + y1 + 'L0,-' + y0 + 'Z';
  19103. }
  19104. },
  19105. hexagon2: {
  19106. n: 15,
  19107. f: function(r) {
  19108. var x0 = d3.round(r, 2);
  19109. var x1 = d3.round(r / 2, 2);
  19110. var y = d3.round(r * Math.sqrt(3) / 2, 2);
  19111. return 'M-' + x1 + ',' + y + 'H' + x1 + 'L' + x0 +
  19112. ',0L' + x1 + ',-' + y + 'H-' + x1 + 'L-' + x0 + ',0Z';
  19113. }
  19114. },
  19115. octagon: {
  19116. n: 16,
  19117. f: function(r) {
  19118. var a = d3.round(r * 0.924, 2);
  19119. var b = d3.round(r * 0.383, 2);
  19120. return 'M-' + b + ',-' + a + 'H' + b + 'L' + a + ',-' + b + 'V' + b +
  19121. 'L' + b + ',' + a + 'H-' + b + 'L-' + a + ',' + b + 'V-' + b + 'Z';
  19122. }
  19123. },
  19124. star: {
  19125. n: 17,
  19126. f: function(r) {
  19127. var rs = r * 1.4;
  19128. var x1 = d3.round(rs * 0.225, 2);
  19129. var x2 = d3.round(rs * 0.951, 2);
  19130. var x3 = d3.round(rs * 0.363, 2);
  19131. var x4 = d3.round(rs * 0.588, 2);
  19132. var y0 = d3.round(-rs, 2);
  19133. var y1 = d3.round(rs * -0.309, 2);
  19134. var y3 = d3.round(rs * 0.118, 2);
  19135. var y4 = d3.round(rs * 0.809, 2);
  19136. var y5 = d3.round(rs * 0.382, 2);
  19137. return 'M' + x1 + ',' + y1 + 'H' + x2 + 'L' + x3 + ',' + y3 +
  19138. 'L' + x4 + ',' + y4 + 'L0,' + y5 + 'L-' + x4 + ',' + y4 +
  19139. 'L-' + x3 + ',' + y3 + 'L-' + x2 + ',' + y1 + 'H-' + x1 +
  19140. 'L0,' + y0 + 'Z';
  19141. }
  19142. },
  19143. hexagram: {
  19144. n: 18,
  19145. f: function(r) {
  19146. var y = d3.round(r * 0.66, 2);
  19147. var x1 = d3.round(r * 0.38, 2);
  19148. var x2 = d3.round(r * 0.76, 2);
  19149. return 'M-' + x2 + ',0l-' + x1 + ',-' + y + 'h' + x2 +
  19150. 'l' + x1 + ',-' + y + 'l' + x1 + ',' + y + 'h' + x2 +
  19151. 'l-' + x1 + ',' + y + 'l' + x1 + ',' + y + 'h-' + x2 +
  19152. 'l-' + x1 + ',' + y + 'l-' + x1 + ',-' + y + 'h-' + x2 + 'Z';
  19153. }
  19154. },
  19155. 'star-triangle-up': {
  19156. n: 19,
  19157. f: function(r) {
  19158. var x = d3.round(r * Math.sqrt(3) * 0.8, 2);
  19159. var y1 = d3.round(r * 0.8, 2);
  19160. var y2 = d3.round(r * 1.6, 2);
  19161. var rc = d3.round(r * 4, 2);
  19162. var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
  19163. return 'M-' + x + ',' + y1 + aPart + x + ',' + y1 +
  19164. aPart + '0,-' + y2 + aPart + '-' + x + ',' + y1 + 'Z';
  19165. }
  19166. },
  19167. 'star-triangle-down': {
  19168. n: 20,
  19169. f: function(r) {
  19170. var x = d3.round(r * Math.sqrt(3) * 0.8, 2);
  19171. var y1 = d3.round(r * 0.8, 2);
  19172. var y2 = d3.round(r * 1.6, 2);
  19173. var rc = d3.round(r * 4, 2);
  19174. var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
  19175. return 'M' + x + ',-' + y1 + aPart + '-' + x + ',-' + y1 +
  19176. aPart + '0,' + y2 + aPart + x + ',-' + y1 + 'Z';
  19177. }
  19178. },
  19179. 'star-square': {
  19180. n: 21,
  19181. f: function(r) {
  19182. var rp = d3.round(r * 1.1, 2);
  19183. var rc = d3.round(r * 2, 2);
  19184. var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
  19185. return 'M-' + rp + ',-' + rp + aPart + '-' + rp + ',' + rp +
  19186. aPart + rp + ',' + rp + aPart + rp + ',-' + rp +
  19187. aPart + '-' + rp + ',-' + rp + 'Z';
  19188. }
  19189. },
  19190. 'star-diamond': {
  19191. n: 22,
  19192. f: function(r) {
  19193. var rp = d3.round(r * 1.4, 2);
  19194. var rc = d3.round(r * 1.9, 2);
  19195. var aPart = 'A ' + rc + ',' + rc + ' 0 0 1 ';
  19196. return 'M-' + rp + ',0' + aPart + '0,' + rp +
  19197. aPart + rp + ',0' + aPart + '0,-' + rp +
  19198. aPart + '-' + rp + ',0' + 'Z';
  19199. }
  19200. },
  19201. 'diamond-tall': {
  19202. n: 23,
  19203. f: function(r) {
  19204. var x = d3.round(r * 0.7, 2);
  19205. var y = d3.round(r * 1.4, 2);
  19206. return 'M0,' + y + 'L' + x + ',0L0,-' + y + 'L-' + x + ',0Z';
  19207. }
  19208. },
  19209. 'diamond-wide': {
  19210. n: 24,
  19211. f: function(r) {
  19212. var x = d3.round(r * 1.4, 2);
  19213. var y = d3.round(r * 0.7, 2);
  19214. return 'M0,' + y + 'L' + x + ',0L0,-' + y + 'L-' + x + ',0Z';
  19215. }
  19216. },
  19217. hourglass: {
  19218. n: 25,
  19219. f: function(r) {
  19220. var rs = d3.round(r, 2);
  19221. return 'M' + rs + ',' + rs + 'H-' + rs + 'L' + rs + ',-' + rs + 'H-' + rs + 'Z';
  19222. },
  19223. noDot: true
  19224. },
  19225. bowtie: {
  19226. n: 26,
  19227. f: function(r) {
  19228. var rs = d3.round(r, 2);
  19229. return 'M' + rs + ',' + rs + 'V-' + rs + 'L-' + rs + ',' + rs + 'V-' + rs + 'Z';
  19230. },
  19231. noDot: true
  19232. },
  19233. 'circle-cross': {
  19234. n: 27,
  19235. f: function(r) {
  19236. var rs = d3.round(r, 2);
  19237. return 'M0,' + rs + 'V-' + rs + 'M' + rs + ',0H-' + rs +
  19238. 'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs +
  19239. 'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z';
  19240. },
  19241. needLine: true,
  19242. noDot: true
  19243. },
  19244. 'circle-x': {
  19245. n: 28,
  19246. f: function(r) {
  19247. var rs = d3.round(r, 2);
  19248. var rc = d3.round(r / Math.sqrt(2), 2);
  19249. return 'M' + rc + ',' + rc + 'L-' + rc + ',-' + rc +
  19250. 'M' + rc + ',-' + rc + 'L-' + rc + ',' + rc +
  19251. 'M' + rs + ',0A' + rs + ',' + rs + ' 0 1,1 0,-' + rs +
  19252. 'A' + rs + ',' + rs + ' 0 0,1 ' + rs + ',0Z';
  19253. },
  19254. needLine: true,
  19255. noDot: true
  19256. },
  19257. 'square-cross': {
  19258. n: 29,
  19259. f: function(r) {
  19260. var rs = d3.round(r, 2);
  19261. return 'M0,' + rs + 'V-' + rs + 'M' + rs + ',0H-' + rs +
  19262. 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z';
  19263. },
  19264. needLine: true,
  19265. noDot: true
  19266. },
  19267. 'square-x': {
  19268. n: 30,
  19269. f: function(r) {
  19270. var rs = d3.round(r, 2);
  19271. return 'M' + rs + ',' + rs + 'L-' + rs + ',-' + rs +
  19272. 'M' + rs + ',-' + rs + 'L-' + rs + ',' + rs +
  19273. 'M' + rs + ',' + rs + 'H-' + rs + 'V-' + rs + 'H' + rs + 'Z';
  19274. },
  19275. needLine: true,
  19276. noDot: true
  19277. },
  19278. 'diamond-cross': {
  19279. n: 31,
  19280. f: function(r) {
  19281. var rd = d3.round(r * 1.3, 2);
  19282. return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z' +
  19283. 'M0,-' + rd + 'V' + rd + 'M-' + rd + ',0H' + rd;
  19284. },
  19285. needLine: true,
  19286. noDot: true
  19287. },
  19288. 'diamond-x': {
  19289. n: 32,
  19290. f: function(r) {
  19291. var rd = d3.round(r * 1.3, 2);
  19292. var r2 = d3.round(r * 0.65, 2);
  19293. return 'M' + rd + ',0L0,' + rd + 'L-' + rd + ',0L0,-' + rd + 'Z' +
  19294. 'M-' + r2 + ',-' + r2 + 'L' + r2 + ',' + r2 +
  19295. 'M-' + r2 + ',' + r2 + 'L' + r2 + ',-' + r2;
  19296. },
  19297. needLine: true,
  19298. noDot: true
  19299. },
  19300. 'cross-thin': {
  19301. n: 33,
  19302. f: function(r) {
  19303. var rc = d3.round(r * 1.4, 2);
  19304. return 'M0,' + rc + 'V-' + rc + 'M' + rc + ',0H-' + rc;
  19305. },
  19306. needLine: true,
  19307. noDot: true,
  19308. noFill: true
  19309. },
  19310. 'x-thin': {
  19311. n: 34,
  19312. f: function(r) {
  19313. var rx = d3.round(r, 2);
  19314. return 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx +
  19315. 'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx;
  19316. },
  19317. needLine: true,
  19318. noDot: true,
  19319. noFill: true
  19320. },
  19321. asterisk: {
  19322. n: 35,
  19323. f: function(r) {
  19324. var rc = d3.round(r * 1.2, 2);
  19325. var rs = d3.round(r * 0.85, 2);
  19326. return 'M0,' + rc + 'V-' + rc + 'M' + rc + ',0H-' + rc +
  19327. 'M' + rs + ',' + rs + 'L-' + rs + ',-' + rs +
  19328. 'M' + rs + ',-' + rs + 'L-' + rs + ',' + rs;
  19329. },
  19330. needLine: true,
  19331. noDot: true,
  19332. noFill: true
  19333. },
  19334. hash: {
  19335. n: 36,
  19336. f: function(r) {
  19337. var r1 = d3.round(r / 2, 2);
  19338. var r2 = d3.round(r, 2);
  19339. return 'M' + r1 + ',' + r2 + 'V-' + r2 +
  19340. 'm-' + r2 + ',0V' + r2 +
  19341. 'M' + r2 + ',' + r1 + 'H-' + r2 +
  19342. 'm0,-' + r2 + 'H' + r2;
  19343. },
  19344. needLine: true,
  19345. noFill: true
  19346. },
  19347. 'y-up': {
  19348. n: 37,
  19349. f: function(r) {
  19350. var x = d3.round(r * 1.2, 2);
  19351. var y0 = d3.round(r * 1.6, 2);
  19352. var y1 = d3.round(r * 0.8, 2);
  19353. return 'M-' + x + ',' + y1 + 'L0,0M' + x + ',' + y1 + 'L0,0M0,-' + y0 + 'L0,0';
  19354. },
  19355. needLine: true,
  19356. noDot: true,
  19357. noFill: true
  19358. },
  19359. 'y-down': {
  19360. n: 38,
  19361. f: function(r) {
  19362. var x = d3.round(r * 1.2, 2);
  19363. var y0 = d3.round(r * 1.6, 2);
  19364. var y1 = d3.round(r * 0.8, 2);
  19365. return 'M-' + x + ',-' + y1 + 'L0,0M' + x + ',-' + y1 + 'L0,0M0,' + y0 + 'L0,0';
  19366. },
  19367. needLine: true,
  19368. noDot: true,
  19369. noFill: true
  19370. },
  19371. 'y-left': {
  19372. n: 39,
  19373. f: function(r) {
  19374. var y = d3.round(r * 1.2, 2);
  19375. var x0 = d3.round(r * 1.6, 2);
  19376. var x1 = d3.round(r * 0.8, 2);
  19377. return 'M' + x1 + ',' + y + 'L0,0M' + x1 + ',-' + y + 'L0,0M-' + x0 + ',0L0,0';
  19378. },
  19379. needLine: true,
  19380. noDot: true,
  19381. noFill: true
  19382. },
  19383. 'y-right': {
  19384. n: 40,
  19385. f: function(r) {
  19386. var y = d3.round(r * 1.2, 2);
  19387. var x0 = d3.round(r * 1.6, 2);
  19388. var x1 = d3.round(r * 0.8, 2);
  19389. return 'M-' + x1 + ',' + y + 'L0,0M-' + x1 + ',-' + y + 'L0,0M' + x0 + ',0L0,0';
  19390. },
  19391. needLine: true,
  19392. noDot: true,
  19393. noFill: true
  19394. },
  19395. 'line-ew': {
  19396. n: 41,
  19397. f: function(r) {
  19398. var rc = d3.round(r * 1.4, 2);
  19399. return 'M' + rc + ',0H-' + rc;
  19400. },
  19401. needLine: true,
  19402. noDot: true,
  19403. noFill: true
  19404. },
  19405. 'line-ns': {
  19406. n: 42,
  19407. f: function(r) {
  19408. var rc = d3.round(r * 1.4, 2);
  19409. return 'M0,' + rc + 'V-' + rc;
  19410. },
  19411. needLine: true,
  19412. noDot: true,
  19413. noFill: true
  19414. },
  19415. 'line-ne': {
  19416. n: 43,
  19417. f: function(r) {
  19418. var rx = d3.round(r, 2);
  19419. return 'M' + rx + ',-' + rx + 'L-' + rx + ',' + rx;
  19420. },
  19421. needLine: true,
  19422. noDot: true,
  19423. noFill: true
  19424. },
  19425. 'line-nw': {
  19426. n: 44,
  19427. f: function(r) {
  19428. var rx = d3.round(r, 2);
  19429. return 'M' + rx + ',' + rx + 'L-' + rx + ',-' + rx;
  19430. },
  19431. needLine: true,
  19432. noDot: true,
  19433. noFill: true
  19434. }
  19435. };
  19436. },{"d3":16}],74:[function(_dereq_,module,exports){
  19437. /**
  19438. * Copyright 2012-2019, Plotly, Inc.
  19439. * All rights reserved.
  19440. *
  19441. * This source code is licensed under the MIT license found in the
  19442. * LICENSE file in the root directory of this source tree.
  19443. */
  19444. 'use strict';
  19445. module.exports = {
  19446. visible: {
  19447. valType: 'boolean',
  19448. editType: 'calc',
  19449. },
  19450. type: {
  19451. valType: 'enumerated',
  19452. values: ['percent', 'constant', 'sqrt', 'data'],
  19453. editType: 'calc',
  19454. },
  19455. symmetric: {
  19456. valType: 'boolean',
  19457. editType: 'calc',
  19458. },
  19459. array: {
  19460. valType: 'data_array',
  19461. editType: 'calc',
  19462. },
  19463. arrayminus: {
  19464. valType: 'data_array',
  19465. editType: 'calc',
  19466. },
  19467. value: {
  19468. valType: 'number',
  19469. min: 0,
  19470. dflt: 10,
  19471. editType: 'calc',
  19472. },
  19473. valueminus: {
  19474. valType: 'number',
  19475. min: 0,
  19476. dflt: 10,
  19477. editType: 'calc',
  19478. },
  19479. traceref: {
  19480. valType: 'integer',
  19481. min: 0,
  19482. dflt: 0,
  19483. editType: 'style'
  19484. },
  19485. tracerefminus: {
  19486. valType: 'integer',
  19487. min: 0,
  19488. dflt: 0,
  19489. editType: 'style'
  19490. },
  19491. copy_ystyle: {
  19492. valType: 'boolean',
  19493. editType: 'plot'
  19494. },
  19495. copy_zstyle: {
  19496. valType: 'boolean',
  19497. editType: 'style'
  19498. },
  19499. color: {
  19500. valType: 'color',
  19501. editType: 'style',
  19502. },
  19503. thickness: {
  19504. valType: 'number',
  19505. min: 0,
  19506. dflt: 2,
  19507. editType: 'style',
  19508. },
  19509. width: {
  19510. valType: 'number',
  19511. min: 0,
  19512. editType: 'plot',
  19513. },
  19514. editType: 'calc',
  19515. _deprecated: {
  19516. opacity: {
  19517. valType: 'number',
  19518. editType: 'style',
  19519. }
  19520. }
  19521. };
  19522. },{}],75:[function(_dereq_,module,exports){
  19523. /**
  19524. * Copyright 2012-2019, Plotly, Inc.
  19525. * All rights reserved.
  19526. *
  19527. * This source code is licensed under the MIT license found in the
  19528. * LICENSE file in the root directory of this source tree.
  19529. */
  19530. 'use strict';
  19531. var isNumeric = _dereq_('fast-isnumeric');
  19532. var Registry = _dereq_('../../registry');
  19533. var Axes = _dereq_('../../plots/cartesian/axes');
  19534. var Lib = _dereq_('../../lib');
  19535. var makeComputeError = _dereq_('./compute_error');
  19536. module.exports = function calc(gd) {
  19537. var calcdata = gd.calcdata;
  19538. for(var i = 0; i < calcdata.length; i++) {
  19539. var calcTrace = calcdata[i];
  19540. var trace = calcTrace[0].trace;
  19541. if(trace.visible === true && Registry.traceIs(trace, 'errorBarsOK')) {
  19542. var xa = Axes.getFromId(gd, trace.xaxis);
  19543. var ya = Axes.getFromId(gd, trace.yaxis);
  19544. calcOneAxis(calcTrace, trace, xa, 'x');
  19545. calcOneAxis(calcTrace, trace, ya, 'y');
  19546. }
  19547. }
  19548. };
  19549. function calcOneAxis(calcTrace, trace, axis, coord) {
  19550. var opts = trace['error_' + coord] || {};
  19551. var isVisible = (opts.visible && ['linear', 'log'].indexOf(axis.type) !== -1);
  19552. var vals = [];
  19553. if(!isVisible) return;
  19554. var computeError = makeComputeError(opts);
  19555. for(var i = 0; i < calcTrace.length; i++) {
  19556. var calcPt = calcTrace[i];
  19557. var iIn = calcPt.i;
  19558. // for types that don't include `i` in each calcdata point
  19559. if(iIn === undefined) iIn = i;
  19560. // for stacked area inserted points
  19561. // TODO: errorbars have been tested cursorily with stacked area,
  19562. // but not thoroughly. It's not even really clear what you want to do:
  19563. // Should it just be calculated based on that trace's size data?
  19564. // Should you add errors from below in quadrature?
  19565. // And what about normalization, where in principle the errors shrink
  19566. // again when you get up to the top end?
  19567. // One option would be to forbid errorbars with stacking until we
  19568. // decide how to handle these questions.
  19569. else if(iIn === null) continue;
  19570. var calcCoord = calcPt[coord];
  19571. if(!isNumeric(axis.c2l(calcCoord))) continue;
  19572. var errors = computeError(calcCoord, iIn);
  19573. if(isNumeric(errors[0]) && isNumeric(errors[1])) {
  19574. var shoe = calcPt[coord + 's'] = calcCoord - errors[0];
  19575. var hat = calcPt[coord + 'h'] = calcCoord + errors[1];
  19576. vals.push(shoe, hat);
  19577. }
  19578. }
  19579. var axId = axis._id;
  19580. var baseExtremes = trace._extremes[axId];
  19581. var extremes = Axes.findExtremes(
  19582. axis,
  19583. vals,
  19584. Lib.extendFlat({tozero: baseExtremes.opts.tozero}, {padded: true})
  19585. );
  19586. baseExtremes.min = baseExtremes.min.concat(extremes.min);
  19587. baseExtremes.max = baseExtremes.max.concat(extremes.max);
  19588. }
  19589. },{"../../lib":168,"../../plots/cartesian/axes":212,"../../registry":257,"./compute_error":76,"fast-isnumeric":18}],76:[function(_dereq_,module,exports){
  19590. /**
  19591. * Copyright 2012-2019, Plotly, Inc.
  19592. * All rights reserved.
  19593. *
  19594. * This source code is licensed under the MIT license found in the
  19595. * LICENSE file in the root directory of this source tree.
  19596. */
  19597. 'use strict';
  19598. /**
  19599. * Error bar computing function generator
  19600. *
  19601. * N.B. The generated function does not clean the dataPt entries. Non-numeric
  19602. * entries result in undefined error magnitudes.
  19603. *
  19604. * @param {object} opts error bar attributes
  19605. *
  19606. * @return {function} :
  19607. * @param {numeric} dataPt data point from where to compute the error magnitude
  19608. * @param {number} index index of dataPt in its corresponding data array
  19609. * @return {array}
  19610. * - error[0] : error magnitude in the negative direction
  19611. * - error[1] : " " " " positive "
  19612. */
  19613. module.exports = function makeComputeError(opts) {
  19614. var type = opts.type;
  19615. var symmetric = opts.symmetric;
  19616. if(type === 'data') {
  19617. var array = opts.array || [];
  19618. if(symmetric) {
  19619. return function computeError(dataPt, index) {
  19620. var val = +(array[index]);
  19621. return [val, val];
  19622. };
  19623. }
  19624. else {
  19625. var arrayminus = opts.arrayminus || [];
  19626. return function computeError(dataPt, index) {
  19627. var val = +array[index];
  19628. var valMinus = +arrayminus[index];
  19629. // in case one is present and the other is missing, fill in 0
  19630. // so we still see the present one. Mostly useful during manual
  19631. // data entry.
  19632. if(!isNaN(val) || !isNaN(valMinus)) {
  19633. return [valMinus || 0, val || 0];
  19634. }
  19635. return [NaN, NaN];
  19636. };
  19637. }
  19638. }
  19639. else {
  19640. var computeErrorValue = makeComputeErrorValue(type, opts.value);
  19641. var computeErrorValueMinus = makeComputeErrorValue(type, opts.valueminus);
  19642. if(symmetric || opts.valueminus === undefined) {
  19643. return function computeError(dataPt) {
  19644. var val = computeErrorValue(dataPt);
  19645. return [val, val];
  19646. };
  19647. }
  19648. else {
  19649. return function computeError(dataPt) {
  19650. return [
  19651. computeErrorValueMinus(dataPt),
  19652. computeErrorValue(dataPt)
  19653. ];
  19654. };
  19655. }
  19656. }
  19657. };
  19658. /**
  19659. * Compute error bar magnitude (for all types except data)
  19660. *
  19661. * @param {string} type error bar type
  19662. * @param {numeric} value error bar value
  19663. *
  19664. * @return {function} :
  19665. * @param {numeric} dataPt
  19666. */
  19667. function makeComputeErrorValue(type, value) {
  19668. if(type === 'percent') {
  19669. return function(dataPt) {
  19670. return Math.abs(dataPt * value / 100);
  19671. };
  19672. }
  19673. if(type === 'constant') {
  19674. return function() {
  19675. return Math.abs(value);
  19676. };
  19677. }
  19678. if(type === 'sqrt') {
  19679. return function(dataPt) {
  19680. return Math.sqrt(Math.abs(dataPt));
  19681. };
  19682. }
  19683. }
  19684. },{}],77:[function(_dereq_,module,exports){
  19685. /**
  19686. * Copyright 2012-2019, Plotly, Inc.
  19687. * All rights reserved.
  19688. *
  19689. * This source code is licensed under the MIT license found in the
  19690. * LICENSE file in the root directory of this source tree.
  19691. */
  19692. 'use strict';
  19693. var isNumeric = _dereq_('fast-isnumeric');
  19694. var Registry = _dereq_('../../registry');
  19695. var Lib = _dereq_('../../lib');
  19696. var Template = _dereq_('../../plot_api/plot_template');
  19697. var attributes = _dereq_('./attributes');
  19698. module.exports = function(traceIn, traceOut, defaultColor, opts) {
  19699. var objName = 'error_' + opts.axis;
  19700. var containerOut = Template.newContainer(traceOut, objName);
  19701. var containerIn = traceIn[objName] || {};
  19702. function coerce(attr, dflt) {
  19703. return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
  19704. }
  19705. var hasErrorBars = (
  19706. containerIn.array !== undefined ||
  19707. containerIn.value !== undefined ||
  19708. containerIn.type === 'sqrt'
  19709. );
  19710. var visible = coerce('visible', hasErrorBars);
  19711. if(visible === false) return;
  19712. var type = coerce('type', 'array' in containerIn ? 'data' : 'percent');
  19713. var symmetric = true;
  19714. if(type !== 'sqrt') {
  19715. symmetric = coerce('symmetric',
  19716. !((type === 'data' ? 'arrayminus' : 'valueminus') in containerIn));
  19717. }
  19718. if(type === 'data') {
  19719. coerce('array');
  19720. coerce('traceref');
  19721. if(!symmetric) {
  19722. coerce('arrayminus');
  19723. coerce('tracerefminus');
  19724. }
  19725. }
  19726. else if(type === 'percent' || type === 'constant') {
  19727. coerce('value');
  19728. if(!symmetric) coerce('valueminus');
  19729. }
  19730. var copyAttr = 'copy_' + opts.inherit + 'style';
  19731. if(opts.inherit) {
  19732. var inheritObj = traceOut['error_' + opts.inherit];
  19733. if((inheritObj || {}).visible) {
  19734. coerce(copyAttr, !(containerIn.color ||
  19735. isNumeric(containerIn.thickness) ||
  19736. isNumeric(containerIn.width)));
  19737. }
  19738. }
  19739. if(!opts.inherit || !containerOut[copyAttr]) {
  19740. coerce('color', defaultColor);
  19741. coerce('thickness');
  19742. coerce('width', Registry.traceIs(traceOut, 'gl3d') ? 0 : 4);
  19743. }
  19744. };
  19745. },{"../../lib":168,"../../plot_api/plot_template":202,"../../registry":257,"./attributes":74,"fast-isnumeric":18}],78:[function(_dereq_,module,exports){
  19746. /**
  19747. * Copyright 2012-2019, Plotly, Inc.
  19748. * All rights reserved.
  19749. *
  19750. * This source code is licensed under the MIT license found in the
  19751. * LICENSE file in the root directory of this source tree.
  19752. */
  19753. 'use strict';
  19754. var Lib = _dereq_('../../lib');
  19755. var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
  19756. var attributes = _dereq_('./attributes');
  19757. var xyAttrs = {
  19758. error_x: Lib.extendFlat({}, attributes),
  19759. error_y: Lib.extendFlat({}, attributes)
  19760. };
  19761. delete xyAttrs.error_x.copy_zstyle;
  19762. delete xyAttrs.error_y.copy_zstyle;
  19763. delete xyAttrs.error_y.copy_ystyle;
  19764. var xyzAttrs = {
  19765. error_x: Lib.extendFlat({}, attributes),
  19766. error_y: Lib.extendFlat({}, attributes),
  19767. error_z: Lib.extendFlat({}, attributes)
  19768. };
  19769. delete xyzAttrs.error_x.copy_ystyle;
  19770. delete xyzAttrs.error_y.copy_ystyle;
  19771. delete xyzAttrs.error_z.copy_ystyle;
  19772. delete xyzAttrs.error_z.copy_zstyle;
  19773. module.exports = {
  19774. moduleType: 'component',
  19775. name: 'errorbars',
  19776. schema: {
  19777. traces: {
  19778. scatter: xyAttrs,
  19779. bar: xyAttrs,
  19780. histogram: xyAttrs,
  19781. scatter3d: overrideAll(xyzAttrs, 'calc', 'nested'),
  19782. scattergl: overrideAll(xyAttrs, 'calc', 'nested')
  19783. }
  19784. },
  19785. supplyDefaults: _dereq_('./defaults'),
  19786. calc: _dereq_('./calc'),
  19787. makeComputeError: _dereq_('./compute_error'),
  19788. plot: _dereq_('./plot'),
  19789. style: _dereq_('./style'),
  19790. hoverInfo: hoverInfo
  19791. };
  19792. function hoverInfo(calcPoint, trace, hoverPoint) {
  19793. if((trace.error_y || {}).visible) {
  19794. hoverPoint.yerr = calcPoint.yh - calcPoint.y;
  19795. if(!trace.error_y.symmetric) hoverPoint.yerrneg = calcPoint.y - calcPoint.ys;
  19796. }
  19797. if((trace.error_x || {}).visible) {
  19798. hoverPoint.xerr = calcPoint.xh - calcPoint.x;
  19799. if(!trace.error_x.symmetric) hoverPoint.xerrneg = calcPoint.x - calcPoint.xs;
  19800. }
  19801. }
  19802. },{"../../lib":168,"../../plot_api/edit_types":195,"./attributes":74,"./calc":75,"./compute_error":76,"./defaults":77,"./plot":79,"./style":80}],79:[function(_dereq_,module,exports){
  19803. /**
  19804. * Copyright 2012-2019, Plotly, Inc.
  19805. * All rights reserved.
  19806. *
  19807. * This source code is licensed under the MIT license found in the
  19808. * LICENSE file in the root directory of this source tree.
  19809. */
  19810. 'use strict';
  19811. var d3 = _dereq_('d3');
  19812. var isNumeric = _dereq_('fast-isnumeric');
  19813. var Drawing = _dereq_('../drawing');
  19814. var subTypes = _dereq_('../../traces/scatter/subtypes');
  19815. module.exports = function plot(gd, traces, plotinfo, transitionOpts) {
  19816. var isNew;
  19817. var xa = plotinfo.xaxis;
  19818. var ya = plotinfo.yaxis;
  19819. var hasAnimation = transitionOpts && transitionOpts.duration > 0;
  19820. traces.each(function(d) {
  19821. var trace = d[0].trace;
  19822. // || {} is in case the trace (specifically scatterternary)
  19823. // doesn't support error bars at all, but does go through
  19824. // the scatter.plot mechanics, which calls ErrorBars.plot
  19825. // internally
  19826. var xObj = trace.error_x || {};
  19827. var yObj = trace.error_y || {};
  19828. var keyFunc;
  19829. if(trace.ids) {
  19830. keyFunc = function(d) {return d.id;};
  19831. }
  19832. var sparse = (
  19833. subTypes.hasMarkers(trace) &&
  19834. trace.marker.maxdisplayed > 0
  19835. );
  19836. if(!yObj.visible && !xObj.visible) d = [];
  19837. var errorbars = d3.select(this).selectAll('g.errorbar')
  19838. .data(d, keyFunc);
  19839. errorbars.exit().remove();
  19840. if(!d.length) return;
  19841. if(!xObj.visible) errorbars.selectAll('path.xerror').remove();
  19842. if(!yObj.visible) errorbars.selectAll('path.yerror').remove();
  19843. errorbars.style('opacity', 1);
  19844. var enter = errorbars.enter().append('g')
  19845. .classed('errorbar', true);
  19846. if(hasAnimation) {
  19847. enter.style('opacity', 0).transition()
  19848. .duration(transitionOpts.duration)
  19849. .style('opacity', 1);
  19850. }
  19851. Drawing.setClipUrl(errorbars, plotinfo.layerClipId, gd);
  19852. errorbars.each(function(d) {
  19853. var errorbar = d3.select(this);
  19854. var coords = errorCoords(d, xa, ya);
  19855. if(sparse && !d.vis) return;
  19856. var path;
  19857. var yerror = errorbar.select('path.yerror');
  19858. if(yObj.visible && isNumeric(coords.x) &&
  19859. isNumeric(coords.yh) &&
  19860. isNumeric(coords.ys)) {
  19861. var yw = yObj.width;
  19862. path = 'M' + (coords.x - yw) + ',' +
  19863. coords.yh + 'h' + (2 * yw) + // hat
  19864. 'm-' + yw + ',0V' + coords.ys; // bar
  19865. if(!coords.noYS) path += 'm-' + yw + ',0h' + (2 * yw); // shoe
  19866. isNew = !yerror.size();
  19867. if(isNew) {
  19868. yerror = errorbar.append('path')
  19869. .style('vector-effect', 'non-scaling-stroke')
  19870. .classed('yerror', true);
  19871. } else if(hasAnimation) {
  19872. yerror = yerror
  19873. .transition()
  19874. .duration(transitionOpts.duration)
  19875. .ease(transitionOpts.easing);
  19876. }
  19877. yerror.attr('d', path);
  19878. }
  19879. else yerror.remove();
  19880. var xerror = errorbar.select('path.xerror');
  19881. if(xObj.visible && isNumeric(coords.y) &&
  19882. isNumeric(coords.xh) &&
  19883. isNumeric(coords.xs)) {
  19884. var xw = (xObj.copy_ystyle ? yObj : xObj).width;
  19885. path = 'M' + coords.xh + ',' +
  19886. (coords.y - xw) + 'v' + (2 * xw) + // hat
  19887. 'm0,-' + xw + 'H' + coords.xs; // bar
  19888. if(!coords.noXS) path += 'm0,-' + xw + 'v' + (2 * xw); // shoe
  19889. isNew = !xerror.size();
  19890. if(isNew) {
  19891. xerror = errorbar.append('path')
  19892. .style('vector-effect', 'non-scaling-stroke')
  19893. .classed('xerror', true);
  19894. } else if(hasAnimation) {
  19895. xerror = xerror
  19896. .transition()
  19897. .duration(transitionOpts.duration)
  19898. .ease(transitionOpts.easing);
  19899. }
  19900. xerror.attr('d', path);
  19901. }
  19902. else xerror.remove();
  19903. });
  19904. });
  19905. };
  19906. // compute the coordinates of the error-bar objects
  19907. function errorCoords(d, xa, ya) {
  19908. var out = {
  19909. x: xa.c2p(d.x),
  19910. y: ya.c2p(d.y)
  19911. };
  19912. // calculate the error bar size and hat and shoe locations
  19913. if(d.yh !== undefined) {
  19914. out.yh = ya.c2p(d.yh);
  19915. out.ys = ya.c2p(d.ys);
  19916. // if the shoes go off-scale (ie log scale, error bars past zero)
  19917. // clip the bar and hide the shoes
  19918. if(!isNumeric(out.ys)) {
  19919. out.noYS = true;
  19920. out.ys = ya.c2p(d.ys, true);
  19921. }
  19922. }
  19923. if(d.xh !== undefined) {
  19924. out.xh = xa.c2p(d.xh);
  19925. out.xs = xa.c2p(d.xs);
  19926. if(!isNumeric(out.xs)) {
  19927. out.noXS = true;
  19928. out.xs = xa.c2p(d.xs, true);
  19929. }
  19930. }
  19931. return out;
  19932. }
  19933. },{"../../traces/scatter/subtypes":391,"../drawing":72,"d3":16,"fast-isnumeric":18}],80:[function(_dereq_,module,exports){
  19934. /**
  19935. * Copyright 2012-2019, Plotly, Inc.
  19936. * All rights reserved.
  19937. *
  19938. * This source code is licensed under the MIT license found in the
  19939. * LICENSE file in the root directory of this source tree.
  19940. */
  19941. 'use strict';
  19942. var d3 = _dereq_('d3');
  19943. var Color = _dereq_('../color');
  19944. module.exports = function style(traces) {
  19945. traces.each(function(d) {
  19946. var trace = d[0].trace;
  19947. var yObj = trace.error_y || {};
  19948. var xObj = trace.error_x || {};
  19949. var s = d3.select(this);
  19950. s.selectAll('path.yerror')
  19951. .style('stroke-width', yObj.thickness + 'px')
  19952. .call(Color.stroke, yObj.color);
  19953. if(xObj.copy_ystyle) xObj = yObj;
  19954. s.selectAll('path.xerror')
  19955. .style('stroke-width', xObj.thickness + 'px')
  19956. .call(Color.stroke, xObj.color);
  19957. });
  19958. };
  19959. },{"../color":51,"d3":16}],81:[function(_dereq_,module,exports){
  19960. /**
  19961. * Copyright 2012-2019, Plotly, Inc.
  19962. * All rights reserved.
  19963. *
  19964. * This source code is licensed under the MIT license found in the
  19965. * LICENSE file in the root directory of this source tree.
  19966. */
  19967. 'use strict';
  19968. var fontAttrs = _dereq_('../../plots/font_attributes');
  19969. module.exports = {
  19970. hoverlabel: {
  19971. bgcolor: {
  19972. valType: 'color',
  19973. arrayOk: true,
  19974. editType: 'none',
  19975. },
  19976. bordercolor: {
  19977. valType: 'color',
  19978. arrayOk: true,
  19979. editType: 'none',
  19980. },
  19981. font: fontAttrs({
  19982. arrayOk: true,
  19983. editType: 'none',
  19984. }),
  19985. namelength: {
  19986. valType: 'integer',
  19987. min: -1,
  19988. arrayOk: true,
  19989. editType: 'none',
  19990. },
  19991. editType: 'calc'
  19992. }
  19993. };
  19994. },{"../../plots/font_attributes":239}],82:[function(_dereq_,module,exports){
  19995. /**
  19996. * Copyright 2012-2019, Plotly, Inc.
  19997. * All rights reserved.
  19998. *
  19999. * This source code is licensed under the MIT license found in the
  20000. * LICENSE file in the root directory of this source tree.
  20001. */
  20002. 'use strict';
  20003. var Lib = _dereq_('../../lib');
  20004. var Registry = _dereq_('../../registry');
  20005. module.exports = function calc(gd) {
  20006. var calcdata = gd.calcdata;
  20007. var fullLayout = gd._fullLayout;
  20008. function makeCoerceHoverInfo(trace) {
  20009. return function(val) {
  20010. return Lib.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout);
  20011. };
  20012. }
  20013. for(var i = 0; i < calcdata.length; i++) {
  20014. var cd = calcdata[i];
  20015. var trace = cd[0].trace;
  20016. // don't include hover calc fields for pie traces
  20017. // as calcdata items might be sorted by value and
  20018. // won't match the data array order.
  20019. if(Registry.traceIs(trace, 'pie')) continue;
  20020. var fillFn = Registry.traceIs(trace, '2dMap') ? paste : Lib.fillArray;
  20021. fillFn(trace.hoverinfo, cd, 'hi', makeCoerceHoverInfo(trace));
  20022. if(trace.hovertemplate) fillFn(trace.hovertemplate, cd, 'ht');
  20023. if(!trace.hoverlabel) continue;
  20024. fillFn(trace.hoverlabel.bgcolor, cd, 'hbg');
  20025. fillFn(trace.hoverlabel.bordercolor, cd, 'hbc');
  20026. fillFn(trace.hoverlabel.font.size, cd, 'hts');
  20027. fillFn(trace.hoverlabel.font.color, cd, 'htc');
  20028. fillFn(trace.hoverlabel.font.family, cd, 'htf');
  20029. fillFn(trace.hoverlabel.namelength, cd, 'hnl');
  20030. }
  20031. };
  20032. function paste(traceAttr, cd, cdAttr, fn) {
  20033. fn = fn || Lib.identity;
  20034. if(Array.isArray(traceAttr)) {
  20035. cd[0][cdAttr] = fn(traceAttr);
  20036. }
  20037. }
  20038. },{"../../lib":168,"../../registry":257}],83:[function(_dereq_,module,exports){
  20039. /**
  20040. * Copyright 2012-2019, Plotly, Inc.
  20041. * All rights reserved.
  20042. *
  20043. * This source code is licensed under the MIT license found in the
  20044. * LICENSE file in the root directory of this source tree.
  20045. */
  20046. 'use strict';
  20047. var Registry = _dereq_('../../registry');
  20048. var hover = _dereq_('./hover').hover;
  20049. module.exports = function click(gd, evt, subplot) {
  20050. var annotationsDone = Registry.getComponentMethod('annotations', 'onClick')(gd, gd._hoverdata);
  20051. // fallback to fail-safe in case the plot type's hover method doesn't pass the subplot.
  20052. // Ternary, for example, didn't, but it was caught because tested.
  20053. if(subplot !== undefined) {
  20054. // The true flag at the end causes it to re-run the hover computation to figure out *which*
  20055. // point is being clicked. Without this, clicking is somewhat unreliable.
  20056. hover(gd, evt, subplot, true);
  20057. }
  20058. function emitClick() { gd.emit('plotly_click', {points: gd._hoverdata, event: evt}); }
  20059. if(gd._hoverdata && evt && evt.target) {
  20060. if(annotationsDone && annotationsDone.then) {
  20061. annotationsDone.then(emitClick);
  20062. }
  20063. else emitClick();
  20064. // why do we get a double event without this???
  20065. if(evt.stopImmediatePropagation) evt.stopImmediatePropagation();
  20066. }
  20067. };
  20068. },{"../../registry":257,"./hover":87}],84:[function(_dereq_,module,exports){
  20069. /**
  20070. * Copyright 2012-2019, Plotly, Inc.
  20071. * All rights reserved.
  20072. *
  20073. * This source code is licensed under the MIT license found in the
  20074. * LICENSE file in the root directory of this source tree.
  20075. */
  20076. 'use strict';
  20077. module.exports = {
  20078. // hover labels for multiple horizontal bars get tilted by this angle
  20079. YANGLE: 60,
  20080. // size and display constants for hover text
  20081. // pixel size of hover arrows
  20082. HOVERARROWSIZE: 6,
  20083. // pixels padding around text
  20084. HOVERTEXTPAD: 3,
  20085. // hover font
  20086. HOVERFONTSIZE: 13,
  20087. HOVERFONT: 'Arial, sans-serif',
  20088. // minimum time (msec) between hover calls
  20089. HOVERMINTIME: 50,
  20090. // ID suffix (with fullLayout._uid) for hover events in the throttle cache
  20091. HOVERID: '-hover'
  20092. };
  20093. },{}],85:[function(_dereq_,module,exports){
  20094. /**
  20095. * Copyright 2012-2019, Plotly, Inc.
  20096. * All rights reserved.
  20097. *
  20098. * This source code is licensed under the MIT license found in the
  20099. * LICENSE file in the root directory of this source tree.
  20100. */
  20101. 'use strict';
  20102. var Lib = _dereq_('../../lib');
  20103. var attributes = _dereq_('./attributes');
  20104. var handleHoverLabelDefaults = _dereq_('./hoverlabel_defaults');
  20105. module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
  20106. function coerce(attr, dflt) {
  20107. return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
  20108. }
  20109. handleHoverLabelDefaults(traceIn, traceOut, coerce, layout.hoverlabel);
  20110. };
  20111. },{"../../lib":168,"./attributes":81,"./hoverlabel_defaults":88}],86:[function(_dereq_,module,exports){
  20112. /**
  20113. * Copyright 2012-2019, Plotly, Inc.
  20114. * All rights reserved.
  20115. *
  20116. * This source code is licensed under the MIT license found in the
  20117. * LICENSE file in the root directory of this source tree.
  20118. */
  20119. 'use strict';
  20120. var Lib = _dereq_('../../lib');
  20121. // look for either subplot or xaxis and yaxis attributes
  20122. // does not handle splom case
  20123. exports.getSubplot = function getSubplot(trace) {
  20124. return trace.subplot || (trace.xaxis + trace.yaxis) || trace.geo;
  20125. };
  20126. // is trace in given list of subplots?
  20127. // does handle splom case
  20128. exports.isTraceInSubplots = function isTraceInSubplot(trace, subplots) {
  20129. if(trace.type === 'splom') {
  20130. var xaxes = trace.xaxes || [];
  20131. var yaxes = trace.yaxes || [];
  20132. for(var i = 0; i < xaxes.length; i++) {
  20133. for(var j = 0; j < yaxes.length; j++) {
  20134. if(subplots.indexOf(xaxes[i] + yaxes[j]) !== -1) {
  20135. return true;
  20136. }
  20137. }
  20138. }
  20139. return false;
  20140. }
  20141. return subplots.indexOf(exports.getSubplot(trace)) !== -1;
  20142. };
  20143. // convenience functions for mapping all relevant axes
  20144. exports.flat = function flat(subplots, v) {
  20145. var out = new Array(subplots.length);
  20146. for(var i = 0; i < subplots.length; i++) {
  20147. out[i] = v;
  20148. }
  20149. return out;
  20150. };
  20151. exports.p2c = function p2c(axArray, v) {
  20152. var out = new Array(axArray.length);
  20153. for(var i = 0; i < axArray.length; i++) {
  20154. out[i] = axArray[i].p2c(v);
  20155. }
  20156. return out;
  20157. };
  20158. exports.getDistanceFunction = function getDistanceFunction(mode, dx, dy, dxy) {
  20159. if(mode === 'closest') return dxy || exports.quadrature(dx, dy);
  20160. return mode === 'x' ? dx : dy;
  20161. };
  20162. exports.getClosest = function getClosest(cd, distfn, pointData) {
  20163. // do we already have a point number? (array mode only)
  20164. if(pointData.index !== false) {
  20165. if(pointData.index >= 0 && pointData.index < cd.length) {
  20166. pointData.distance = 0;
  20167. }
  20168. else pointData.index = false;
  20169. }
  20170. else {
  20171. // apply the distance function to each data point
  20172. // this is the longest loop... if this bogs down, we may need
  20173. // to create pre-sorted data (by x or y), not sure how to
  20174. // do this for 'closest'
  20175. for(var i = 0; i < cd.length; i++) {
  20176. var newDistance = distfn(cd[i]);
  20177. if(newDistance <= pointData.distance) {
  20178. pointData.index = i;
  20179. pointData.distance = newDistance;
  20180. }
  20181. }
  20182. }
  20183. return pointData;
  20184. };
  20185. /*
  20186. * pseudo-distance function for hover effects on areas: inside the region
  20187. * distance is finite (`passVal`), outside it's Infinity.
  20188. *
  20189. * @param {number} v0: signed difference between the current position and the left edge
  20190. * @param {number} v1: signed difference between the current position and the right edge
  20191. * @param {number} passVal: the value to return on success
  20192. */
  20193. exports.inbox = function inbox(v0, v1, passVal) {
  20194. return (v0 * v1 < 0 || v0 === 0) ? passVal : Infinity;
  20195. };
  20196. exports.quadrature = function quadrature(dx, dy) {
  20197. return function(di) {
  20198. var x = dx(di);
  20199. var y = dy(di);
  20200. return Math.sqrt(x * x + y * y);
  20201. };
  20202. };
  20203. /** Fill event data point object for hover and selection.
  20204. * Invokes _module.eventData if present.
  20205. *
  20206. * N.B. note that point 'index' corresponds to input data array index
  20207. * whereas 'number' is its post-transform version.
  20208. *
  20209. * If the hovered/selected pt corresponds to an multiple input points
  20210. * (e.g. for histogram and transformed traces), 'pointNumbers` and 'pointIndices'
  20211. * are include in the event data.
  20212. *
  20213. * @param {object} pt
  20214. * @param {object} trace
  20215. * @param {object} cd
  20216. * @return {object}
  20217. */
  20218. exports.makeEventData = function makeEventData(pt, trace, cd) {
  20219. // hover uses 'index', select uses 'pointNumber'
  20220. var pointNumber = 'index' in pt ? pt.index : pt.pointNumber;
  20221. var out = {
  20222. data: trace._input,
  20223. fullData: trace,
  20224. curveNumber: trace.index,
  20225. pointNumber: pointNumber
  20226. };
  20227. if(trace._indexToPoints) {
  20228. var pointIndices = trace._indexToPoints[pointNumber];
  20229. if(pointIndices.length === 1) {
  20230. out.pointIndex = pointIndices[0];
  20231. } else {
  20232. out.pointIndices = pointIndices;
  20233. }
  20234. } else {
  20235. out.pointIndex = pointNumber;
  20236. }
  20237. if(trace._module.eventData) {
  20238. out = trace._module.eventData(out, pt, trace, cd, pointNumber);
  20239. } else {
  20240. if('xVal' in pt) out.x = pt.xVal;
  20241. else if('x' in pt) out.x = pt.x;
  20242. if('yVal' in pt) out.y = pt.yVal;
  20243. else if('y' in pt) out.y = pt.y;
  20244. if(pt.xa) out.xaxis = pt.xa;
  20245. if(pt.ya) out.yaxis = pt.ya;
  20246. if(pt.zLabelVal !== undefined) out.z = pt.zLabelVal;
  20247. }
  20248. exports.appendArrayPointValue(out, trace, pointNumber);
  20249. return out;
  20250. };
  20251. /** Appends values inside array attributes corresponding to given point number
  20252. *
  20253. * @param {object} pointData : point data object (gets mutated here)
  20254. * @param {object} trace : full trace object
  20255. * @param {number|Array(number)} pointNumber : point number. May be a length-2 array
  20256. * [row, col] to dig into 2D arrays
  20257. */
  20258. exports.appendArrayPointValue = function(pointData, trace, pointNumber) {
  20259. var arrayAttrs = trace._arrayAttrs;
  20260. if(!arrayAttrs) {
  20261. return;
  20262. }
  20263. for(var i = 0; i < arrayAttrs.length; i++) {
  20264. var astr = arrayAttrs[i];
  20265. var key = getPointKey(astr);
  20266. if(pointData[key] === undefined) {
  20267. var val = Lib.nestedProperty(trace, astr).get();
  20268. var pointVal = getPointData(val, pointNumber);
  20269. if(pointVal !== undefined) pointData[key] = pointVal;
  20270. }
  20271. }
  20272. };
  20273. /**
  20274. * Appends values inside array attributes corresponding to given point number array
  20275. * For use when pointData references a plot entity that arose (or potentially arose)
  20276. * from multiple points in the input data
  20277. *
  20278. * @param {object} pointData : point data object (gets mutated here)
  20279. * @param {object} trace : full trace object
  20280. * @param {Array(number)|Array(Array(number))} pointNumbers : Array of point numbers.
  20281. * Each entry in the array may itself be a length-2 array [row, col] to dig into 2D arrays
  20282. */
  20283. exports.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) {
  20284. var arrayAttrs = trace._arrayAttrs;
  20285. if(!arrayAttrs) {
  20286. return;
  20287. }
  20288. for(var i = 0; i < arrayAttrs.length; i++) {
  20289. var astr = arrayAttrs[i];
  20290. var key = getPointKey(astr);
  20291. if(pointData[key] === undefined) {
  20292. var val = Lib.nestedProperty(trace, astr).get();
  20293. var keyVal = new Array(pointNumbers.length);
  20294. for(var j = 0; j < pointNumbers.length; j++) {
  20295. keyVal[j] = getPointData(val, pointNumbers[j]);
  20296. }
  20297. pointData[key] = keyVal;
  20298. }
  20299. }
  20300. };
  20301. var pointKeyMap = {
  20302. ids: 'id',
  20303. locations: 'location',
  20304. labels: 'label',
  20305. values: 'value',
  20306. 'marker.colors': 'color'
  20307. };
  20308. function getPointKey(astr) {
  20309. return pointKeyMap[astr] || astr;
  20310. }
  20311. function getPointData(val, pointNumber) {
  20312. if(Array.isArray(pointNumber)) {
  20313. if(Array.isArray(val) && Array.isArray(val[pointNumber[0]])) {
  20314. return val[pointNumber[0]][pointNumber[1]];
  20315. }
  20316. } else {
  20317. return val[pointNumber];
  20318. }
  20319. }
  20320. },{"../../lib":168}],87:[function(_dereq_,module,exports){
  20321. /**
  20322. * Copyright 2012-2019, Plotly, Inc.
  20323. * All rights reserved.
  20324. *
  20325. * This source code is licensed under the MIT license found in the
  20326. * LICENSE file in the root directory of this source tree.
  20327. */
  20328. 'use strict';
  20329. var d3 = _dereq_('d3');
  20330. var isNumeric = _dereq_('fast-isnumeric');
  20331. var tinycolor = _dereq_('tinycolor2');
  20332. var Lib = _dereq_('../../lib');
  20333. var Events = _dereq_('../../lib/events');
  20334. var svgTextUtils = _dereq_('../../lib/svg_text_utils');
  20335. var overrideCursor = _dereq_('../../lib/override_cursor');
  20336. var Drawing = _dereq_('../drawing');
  20337. var Color = _dereq_('../color');
  20338. var dragElement = _dereq_('../dragelement');
  20339. var Axes = _dereq_('../../plots/cartesian/axes');
  20340. var Registry = _dereq_('../../registry');
  20341. var helpers = _dereq_('./helpers');
  20342. var constants = _dereq_('./constants');
  20343. // hover labels for multiple horizontal bars get tilted by some angle,
  20344. // then need to be offset differently if they overlap
  20345. var YANGLE = constants.YANGLE;
  20346. var YA_RADIANS = Math.PI * YANGLE / 180;
  20347. // expansion of projected height
  20348. var YFACTOR = 1 / Math.sin(YA_RADIANS);
  20349. // to make the appropriate post-rotation x offset,
  20350. // you need both x and y offsets
  20351. var YSHIFTX = Math.cos(YA_RADIANS);
  20352. var YSHIFTY = Math.sin(YA_RADIANS);
  20353. // size and display constants for hover text
  20354. var HOVERARROWSIZE = constants.HOVERARROWSIZE;
  20355. var HOVERTEXTPAD = constants.HOVERTEXTPAD;
  20356. // fx.hover: highlight data on hover
  20357. // evt can be a mousemove event, or an object with data about what points
  20358. // to hover on
  20359. // {xpx,ypx[,hovermode]} - pixel locations from top left
  20360. // (with optional overriding hovermode)
  20361. // {xval,yval[,hovermode]} - data values
  20362. // [{curveNumber,(pointNumber|xval and/or yval)}] -
  20363. // array of specific points to highlight
  20364. // pointNumber is a single integer if gd.data[curveNumber] is 1D,
  20365. // or a two-element array if it's 2D
  20366. // xval and yval are data values,
  20367. // 1D data may specify either or both,
  20368. // 2D data must specify both
  20369. // subplot is an id string (default "xy")
  20370. // makes use of gl.hovermode, which can be:
  20371. // x (find the points with the closest x values, ie a column),
  20372. // closest (find the single closest point)
  20373. // internally there are two more that occasionally get used:
  20374. // y (pick out a row - only used for multiple horizontal bar charts)
  20375. // array (used when the user specifies an explicit
  20376. // array of points to hover on)
  20377. //
  20378. // We wrap the hovers in a timer, to limit their frequency.
  20379. // The actual rendering is done by private function _hover.
  20380. exports.hover = function hover(gd, evt, subplot, noHoverEvent) {
  20381. gd = Lib.getGraphDiv(gd);
  20382. Lib.throttle(
  20383. gd._fullLayout._uid + constants.HOVERID,
  20384. constants.HOVERMINTIME,
  20385. function() { _hover(gd, evt, subplot, noHoverEvent); }
  20386. );
  20387. };
  20388. /*
  20389. * Draw a single hover item in a pre-existing svg container somewhere
  20390. * hoverItem should have keys:
  20391. * - x and y (or x0, x1, y0, and y1):
  20392. * the pixel position to mark, relative to opts.container
  20393. * - xLabel, yLabel, zLabel, text, and name:
  20394. * info to go in the label
  20395. * - color:
  20396. * the background color for the label.
  20397. * - idealAlign (optional):
  20398. * 'left' or 'right' for which side of the x/y box to try to put this on first
  20399. * - borderColor (optional):
  20400. * color for the border, defaults to strongest contrast with color
  20401. * - fontFamily (optional):
  20402. * string, the font for this label, defaults to constants.HOVERFONT
  20403. * - fontSize (optional):
  20404. * the label font size, defaults to constants.HOVERFONTSIZE
  20405. * - fontColor (optional):
  20406. * defaults to borderColor
  20407. * opts should have keys:
  20408. * - bgColor:
  20409. * the background color this is against, used if the trace is
  20410. * non-opaque, and for the name, which goes outside the box
  20411. * - container:
  20412. * a <svg> or <g> element to add the hover label to
  20413. * - outerContainer:
  20414. * normally a parent of `container`, sets the bounding box to use to
  20415. * constrain the hover label and determine whether to show it on the left or right
  20416. */
  20417. exports.loneHover = function loneHover(hoverItem, opts) {
  20418. var pointData = {
  20419. color: hoverItem.color || Color.defaultLine,
  20420. x0: hoverItem.x0 || hoverItem.x || 0,
  20421. x1: hoverItem.x1 || hoverItem.x || 0,
  20422. y0: hoverItem.y0 || hoverItem.y || 0,
  20423. y1: hoverItem.y1 || hoverItem.y || 0,
  20424. xLabel: hoverItem.xLabel,
  20425. yLabel: hoverItem.yLabel,
  20426. zLabel: hoverItem.zLabel,
  20427. text: hoverItem.text,
  20428. name: hoverItem.name,
  20429. idealAlign: hoverItem.idealAlign,
  20430. // optional extra bits of styling
  20431. borderColor: hoverItem.borderColor,
  20432. fontFamily: hoverItem.fontFamily,
  20433. fontSize: hoverItem.fontSize,
  20434. fontColor: hoverItem.fontColor,
  20435. // filler to make createHoverText happy
  20436. trace: hoverItem.trace || {
  20437. index: 0,
  20438. hoverinfo: ''
  20439. },
  20440. xa: {_offset: 0},
  20441. ya: {_offset: 0},
  20442. index: 0,
  20443. hovertemplate: hoverItem.hovertemplate || false,
  20444. eventData: hoverItem.eventData || false,
  20445. hovertemplateLabels: hoverItem.hovertemplateLabels || false,
  20446. };
  20447. var container3 = d3.select(opts.container);
  20448. var outerContainer3 = opts.outerContainer ?
  20449. d3.select(opts.outerContainer) : container3;
  20450. var fullOpts = {
  20451. hovermode: 'closest',
  20452. rotateLabels: false,
  20453. bgColor: opts.bgColor || Color.background,
  20454. container: container3,
  20455. outerContainer: outerContainer3
  20456. };
  20457. var hoverLabel = createHoverText([pointData], fullOpts, opts.gd);
  20458. alignHoverText(hoverLabel, fullOpts.rotateLabels);
  20459. return hoverLabel.node();
  20460. };
  20461. exports.multiHovers = function multiHovers(hoverItems, opts) {
  20462. if(!Array.isArray(hoverItems)) {
  20463. hoverItems = [hoverItems];
  20464. }
  20465. var pointsData = hoverItems.map(function(hoverItem) {
  20466. return {
  20467. color: hoverItem.color || Color.defaultLine,
  20468. x0: hoverItem.x0 || hoverItem.x || 0,
  20469. x1: hoverItem.x1 || hoverItem.x || 0,
  20470. y0: hoverItem.y0 || hoverItem.y || 0,
  20471. y1: hoverItem.y1 || hoverItem.y || 0,
  20472. xLabel: hoverItem.xLabel,
  20473. yLabel: hoverItem.yLabel,
  20474. zLabel: hoverItem.zLabel,
  20475. text: hoverItem.text,
  20476. name: hoverItem.name,
  20477. idealAlign: hoverItem.idealAlign,
  20478. // optional extra bits of styling
  20479. borderColor: hoverItem.borderColor,
  20480. fontFamily: hoverItem.fontFamily,
  20481. fontSize: hoverItem.fontSize,
  20482. fontColor: hoverItem.fontColor,
  20483. // filler to make createHoverText happy
  20484. trace: hoverItem.trace || {
  20485. index: 0,
  20486. hoverinfo: ''
  20487. },
  20488. xa: {_offset: 0},
  20489. ya: {_offset: 0},
  20490. index: 0,
  20491. hovertemplate: hoverItem.hovertemplate || false,
  20492. eventData: hoverItem.eventData || false,
  20493. hovertemplateLabels: hoverItem.hovertemplateLabels || false,
  20494. };
  20495. });
  20496. var container3 = d3.select(opts.container);
  20497. var outerContainer3 = opts.outerContainer ? d3.select(opts.outerContainer) : container3;
  20498. var fullOpts = {
  20499. hovermode: 'closest',
  20500. rotateLabels: false,
  20501. bgColor: opts.bgColor || Color.background,
  20502. container: container3,
  20503. outerContainer: outerContainer3
  20504. };
  20505. var hoverLabel = createHoverText(pointsData, fullOpts, opts.gd);
  20506. // Fix vertical overlap
  20507. var tooltipSpacing = 5;
  20508. var lastBottomY = 0;
  20509. hoverLabel
  20510. .sort(function(a, b) {return a.y0 - b.y0;})
  20511. .each(function(d) {
  20512. var topY = d.y0 - d.by / 2;
  20513. if((topY - tooltipSpacing) < lastBottomY) {
  20514. d.offset = (lastBottomY - topY) + tooltipSpacing;
  20515. } else {
  20516. d.offset = 0;
  20517. }
  20518. lastBottomY = topY + d.by + d.offset;
  20519. });
  20520. alignHoverText(hoverLabel, fullOpts.rotateLabels);
  20521. return hoverLabel.node();
  20522. };
  20523. // The actual implementation is here:
  20524. function _hover(gd, evt, subplot, noHoverEvent) {
  20525. if(!subplot) subplot = 'xy';
  20526. // if the user passed in an array of subplots,
  20527. // use those instead of finding overlayed plots
  20528. var subplots = Array.isArray(subplot) ? subplot : [subplot];
  20529. var fullLayout = gd._fullLayout;
  20530. var plots = fullLayout._plots || [];
  20531. var plotinfo = plots[subplot];
  20532. var hasCartesian = fullLayout._has('cartesian');
  20533. // list of all overlaid subplots to look at
  20534. if(plotinfo) {
  20535. var overlayedSubplots = plotinfo.overlays.map(function(pi) {
  20536. return pi.id;
  20537. });
  20538. subplots = subplots.concat(overlayedSubplots);
  20539. }
  20540. var len = subplots.length;
  20541. var xaArray = new Array(len);
  20542. var yaArray = new Array(len);
  20543. var supportsCompare = false;
  20544. for(var i = 0; i < len; i++) {
  20545. var spId = subplots[i];
  20546. // 'cartesian' case
  20547. var plotObj = plots[spId];
  20548. if(plotObj) {
  20549. supportsCompare = true;
  20550. // TODO make sure that fullLayout_plots axis refs
  20551. // get updated properly so that we don't have
  20552. // to use Axes.getFromId in general.
  20553. xaArray[i] = Axes.getFromId(gd, plotObj.xaxis._id);
  20554. yaArray[i] = Axes.getFromId(gd, plotObj.yaxis._id);
  20555. continue;
  20556. }
  20557. // other subplot types
  20558. var _subplot = fullLayout[spId]._subplot;
  20559. xaArray[i] = _subplot.xaxis;
  20560. yaArray[i] = _subplot.yaxis;
  20561. }
  20562. var hovermode = evt.hovermode || fullLayout.hovermode;
  20563. if(hovermode && !supportsCompare) hovermode = 'closest';
  20564. if(['x', 'y', 'closest'].indexOf(hovermode) === -1 || !gd.calcdata ||
  20565. gd.querySelector('.zoombox') || gd._dragging) {
  20566. return dragElement.unhoverRaw(gd, evt);
  20567. }
  20568. var hoverdistance = fullLayout.hoverdistance === -1 ? Infinity : fullLayout.hoverdistance;
  20569. var spikedistance = fullLayout.spikedistance === -1 ? Infinity : fullLayout.spikedistance;
  20570. // hoverData: the set of candidate points we've found to highlight
  20571. var hoverData = [];
  20572. // searchData: the data to search in. Mostly this is just a copy of
  20573. // gd.calcdata, filtered to the subplot and overlays we're on
  20574. // but if a point array is supplied it will be a mapping
  20575. // of indicated curves
  20576. var searchData = [];
  20577. // [x|y]valArray: the axis values of the hover event
  20578. // mapped onto each of the currently selected overlaid subplots
  20579. var xvalArray, yvalArray;
  20580. var itemnum, curvenum, cd, trace, subplotId, subploti, mode,
  20581. xval, yval, pointData, closedataPreviousLength;
  20582. // spikePoints: the set of candidate points we've found to draw spikes to
  20583. var spikePoints = {
  20584. hLinePoint: null,
  20585. vLinePoint: null
  20586. };
  20587. // does subplot have one (or more) horizontal traces?
  20588. // This is used to determine whether we rotate the labels or not
  20589. var hasOneHorizontalTrace = false;
  20590. // Figure out what we're hovering on:
  20591. // mouse location or user-supplied data
  20592. if(Array.isArray(evt)) {
  20593. // user specified an array of points to highlight
  20594. hovermode = 'array';
  20595. for(itemnum = 0; itemnum < evt.length; itemnum++) {
  20596. cd = gd.calcdata[evt[itemnum].curveNumber || 0];
  20597. if(cd) {
  20598. trace = cd[0].trace;
  20599. if(cd[0].trace.hoverinfo !== 'skip') {
  20600. searchData.push(cd);
  20601. if(trace.orientation === 'h') {
  20602. hasOneHorizontalTrace = true;
  20603. }
  20604. }
  20605. }
  20606. }
  20607. }
  20608. else {
  20609. for(curvenum = 0; curvenum < gd.calcdata.length; curvenum++) {
  20610. cd = gd.calcdata[curvenum];
  20611. trace = cd[0].trace;
  20612. if(trace.hoverinfo !== 'skip' && helpers.isTraceInSubplots(trace, subplots)) {
  20613. searchData.push(cd);
  20614. if(trace.orientation === 'h') {
  20615. hasOneHorizontalTrace = true;
  20616. }
  20617. }
  20618. }
  20619. // [x|y]px: the pixels (from top left) of the mouse location
  20620. // on the currently selected plot area
  20621. // add pointerX|Y property for drawing the spikes in spikesnap 'cursor' situation
  20622. var hasUserCalledHover = !evt.target;
  20623. var xpx, ypx;
  20624. if(hasUserCalledHover) {
  20625. if('xpx' in evt) xpx = evt.xpx;
  20626. else xpx = xaArray[0]._length / 2;
  20627. if('ypx' in evt) ypx = evt.ypx;
  20628. else ypx = yaArray[0]._length / 2;
  20629. }
  20630. else {
  20631. // fire the beforehover event and quit if it returns false
  20632. // note that we're only calling this on real mouse events, so
  20633. // manual calls to fx.hover will always run.
  20634. if(Events.triggerHandler(gd, 'plotly_beforehover', evt) === false) {
  20635. return;
  20636. }
  20637. var dbb = evt.target.getBoundingClientRect();
  20638. xpx = evt.clientX - dbb.left;
  20639. ypx = evt.clientY - dbb.top;
  20640. // in case hover was called from mouseout into hovertext,
  20641. // it's possible you're not actually over the plot anymore
  20642. if(xpx < 0 || xpx > xaArray[0]._length || ypx < 0 || ypx > yaArray[0]._length) {
  20643. return dragElement.unhoverRaw(gd, evt);
  20644. }
  20645. }
  20646. evt.pointerX = xpx + xaArray[0]._offset;
  20647. evt.pointerY = ypx + yaArray[0]._offset;
  20648. if('xval' in evt) xvalArray = helpers.flat(subplots, evt.xval);
  20649. else xvalArray = helpers.p2c(xaArray, xpx);
  20650. if('yval' in evt) yvalArray = helpers.flat(subplots, evt.yval);
  20651. else yvalArray = helpers.p2c(yaArray, ypx);
  20652. if(!isNumeric(xvalArray[0]) || !isNumeric(yvalArray[0])) {
  20653. Lib.warn('Fx.hover failed', evt, gd);
  20654. return dragElement.unhoverRaw(gd, evt);
  20655. }
  20656. }
  20657. // the pixel distance to beat as a matching point
  20658. // in 'x' or 'y' mode this resets for each trace
  20659. var distance = Infinity;
  20660. // find the closest point in each trace
  20661. // this is minimum dx and/or dy, depending on mode
  20662. // and the pixel position for the label (labelXpx, labelYpx)
  20663. for(curvenum = 0; curvenum < searchData.length; curvenum++) {
  20664. cd = searchData[curvenum];
  20665. // filter out invisible or broken data
  20666. if(!cd || !cd[0] || !cd[0].trace || cd[0].trace.visible !== true) continue;
  20667. trace = cd[0].trace;
  20668. // Explicitly bail out for these two. I don't know how to otherwise prevent
  20669. // the rest of this function from running and failing
  20670. if(['carpet', 'contourcarpet'].indexOf(trace._module.name) !== -1) continue;
  20671. if(trace.type === 'splom') {
  20672. // splom traces do not generate overlay subplots,
  20673. // it is safe to assume here splom traces correspond to the 0th subplot
  20674. subploti = 0;
  20675. subplotId = subplots[subploti];
  20676. } else {
  20677. subplotId = helpers.getSubplot(trace);
  20678. subploti = subplots.indexOf(subplotId);
  20679. }
  20680. // within one trace mode can sometimes be overridden
  20681. mode = hovermode;
  20682. // container for new point, also used to pass info into module.hoverPoints
  20683. pointData = {
  20684. // trace properties
  20685. cd: cd,
  20686. trace: trace,
  20687. xa: xaArray[subploti],
  20688. ya: yaArray[subploti],
  20689. // max distances for hover and spikes - for points that want to show but do not
  20690. // want to override other points, set distance/spikeDistance equal to max*Distance
  20691. // and it will not get filtered out but it will be guaranteed to have a greater
  20692. // distance than any point that calculated a real distance.
  20693. maxHoverDistance: hoverdistance,
  20694. maxSpikeDistance: spikedistance,
  20695. // point properties - override all of these
  20696. index: false, // point index in trace - only used by plotly.js hoverdata consumers
  20697. distance: Math.min(distance, hoverdistance), // pixel distance or pseudo-distance
  20698. // distance/pseudo-distance for spikes. This distance should always be calculated
  20699. // as if in "closest" mode, and should only be set if this point should
  20700. // generate a spike.
  20701. spikeDistance: Infinity,
  20702. // in some cases the spikes have different positioning from the hover label
  20703. // they don't need x0/x1, just one position
  20704. xSpike: undefined,
  20705. ySpike: undefined,
  20706. // where and how to display the hover label
  20707. color: Color.defaultLine, // trace color
  20708. name: trace.name,
  20709. x0: undefined,
  20710. x1: undefined,
  20711. y0: undefined,
  20712. y1: undefined,
  20713. xLabelVal: undefined,
  20714. yLabelVal: undefined,
  20715. zLabelVal: undefined,
  20716. text: undefined
  20717. };
  20718. // add ref to subplot object (non-cartesian case)
  20719. if(fullLayout[subplotId]) {
  20720. pointData.subplot = fullLayout[subplotId]._subplot;
  20721. }
  20722. // add ref to splom scene
  20723. if(fullLayout._splomScenes && fullLayout._splomScenes[trace.uid]) {
  20724. pointData.scene = fullLayout._splomScenes[trace.uid];
  20725. }
  20726. closedataPreviousLength = hoverData.length;
  20727. // for a highlighting array, figure out what
  20728. // we're searching for with this element
  20729. if(mode === 'array') {
  20730. var selection = evt[curvenum];
  20731. if('pointNumber' in selection) {
  20732. pointData.index = selection.pointNumber;
  20733. mode = 'closest';
  20734. }
  20735. else {
  20736. mode = '';
  20737. if('xval' in selection) {
  20738. xval = selection.xval;
  20739. mode = 'x';
  20740. }
  20741. if('yval' in selection) {
  20742. yval = selection.yval;
  20743. mode = mode ? 'closest' : 'y';
  20744. }
  20745. }
  20746. }
  20747. else {
  20748. xval = xvalArray[subploti];
  20749. yval = yvalArray[subploti];
  20750. }
  20751. // Now if there is range to look in, find the points to hover.
  20752. if(hoverdistance !== 0) {
  20753. if(trace._module && trace._module.hoverPoints) {
  20754. var newPoints = trace._module.hoverPoints(pointData, xval, yval, mode, fullLayout._hoverlayer);
  20755. if(newPoints) {
  20756. var newPoint;
  20757. for(var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) {
  20758. newPoint = newPoints[newPointNum];
  20759. if(isNumeric(newPoint.x0) && isNumeric(newPoint.y0)) {
  20760. hoverData.push(cleanPoint(newPoint, hovermode));
  20761. }
  20762. }
  20763. }
  20764. }
  20765. else {
  20766. Lib.log('Unrecognized trace type in hover:', trace);
  20767. }
  20768. }
  20769. // in closest mode, remove any existing (farther) points
  20770. // and don't look any farther than this latest point (or points, some
  20771. // traces like box & violin make multiple hover labels at once)
  20772. if(hovermode === 'closest' && hoverData.length > closedataPreviousLength) {
  20773. hoverData.splice(0, closedataPreviousLength);
  20774. distance = hoverData[0].distance;
  20775. }
  20776. // Now if there is range to look in, find the points to draw the spikelines
  20777. // Do it only if there is no hoverData
  20778. if(hasCartesian && (spikedistance !== 0)) {
  20779. if(hoverData.length === 0) {
  20780. pointData.distance = spikedistance;
  20781. pointData.index = false;
  20782. var closestPoints = trace._module.hoverPoints(pointData, xval, yval, 'closest', fullLayout._hoverlayer);
  20783. if(closestPoints) {
  20784. closestPoints = closestPoints.filter(function(point) {
  20785. // some hover points, like scatter fills, do not allow spikes,
  20786. // so will generate a hover point but without a valid spikeDistance
  20787. return point.spikeDistance <= spikedistance;
  20788. });
  20789. }
  20790. if(closestPoints && closestPoints.length) {
  20791. var tmpPoint;
  20792. var closestVPoints = closestPoints.filter(function(point) {
  20793. return point.xa.showspikes;
  20794. });
  20795. if(closestVPoints.length) {
  20796. var closestVPt = closestVPoints[0];
  20797. if(isNumeric(closestVPt.x0) && isNumeric(closestVPt.y0)) {
  20798. tmpPoint = fillSpikePoint(closestVPt);
  20799. if(!spikePoints.vLinePoint || (spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance)) {
  20800. spikePoints.vLinePoint = tmpPoint;
  20801. }
  20802. }
  20803. }
  20804. var closestHPoints = closestPoints.filter(function(point) {
  20805. return point.ya.showspikes;
  20806. });
  20807. if(closestHPoints.length) {
  20808. var closestHPt = closestHPoints[0];
  20809. if(isNumeric(closestHPt.x0) && isNumeric(closestHPt.y0)) {
  20810. tmpPoint = fillSpikePoint(closestHPt);
  20811. if(!spikePoints.hLinePoint || (spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance)) {
  20812. spikePoints.hLinePoint = tmpPoint;
  20813. }
  20814. }
  20815. }
  20816. }
  20817. }
  20818. }
  20819. }
  20820. function selectClosestPoint(pointsData, spikedistance) {
  20821. var resultPoint = null;
  20822. var minDistance = Infinity;
  20823. var thisSpikeDistance;
  20824. for(var i = 0; i < pointsData.length; i++) {
  20825. thisSpikeDistance = pointsData[i].spikeDistance;
  20826. if(thisSpikeDistance < minDistance && thisSpikeDistance <= spikedistance) {
  20827. resultPoint = pointsData[i];
  20828. minDistance = thisSpikeDistance;
  20829. }
  20830. }
  20831. return resultPoint;
  20832. }
  20833. function fillSpikePoint(point) {
  20834. if(!point) return null;
  20835. return {
  20836. xa: point.xa,
  20837. ya: point.ya,
  20838. x: point.xSpike !== undefined ? point.xSpike : (point.x0 + point.x1) / 2,
  20839. y: point.ySpike !== undefined ? point.ySpike : (point.y0 + point.y1) / 2,
  20840. distance: point.distance,
  20841. spikeDistance: point.spikeDistance,
  20842. curveNumber: point.trace.index,
  20843. color: point.color,
  20844. pointNumber: point.index
  20845. };
  20846. }
  20847. var spikelineOpts = {
  20848. fullLayout: fullLayout,
  20849. container: fullLayout._hoverlayer,
  20850. outerContainer: fullLayout._paperdiv,
  20851. event: evt
  20852. };
  20853. var oldspikepoints = gd._spikepoints;
  20854. var newspikepoints = {
  20855. vLinePoint: spikePoints.vLinePoint,
  20856. hLinePoint: spikePoints.hLinePoint
  20857. };
  20858. gd._spikepoints = newspikepoints;
  20859. // Now if it is not restricted by spikedistance option, set the points to draw the spikelines
  20860. if(hasCartesian && (spikedistance !== 0)) {
  20861. if(hoverData.length !== 0) {
  20862. var tmpHPointData = hoverData.filter(function(point) {
  20863. return point.ya.showspikes;
  20864. });
  20865. var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance);
  20866. spikePoints.hLinePoint = fillSpikePoint(tmpHPoint);
  20867. var tmpVPointData = hoverData.filter(function(point) {
  20868. return point.xa.showspikes;
  20869. });
  20870. var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance);
  20871. spikePoints.vLinePoint = fillSpikePoint(tmpVPoint);
  20872. }
  20873. }
  20874. // if hoverData is empty check for the spikes to draw and quit if there are none
  20875. if(hoverData.length === 0) {
  20876. var result = dragElement.unhoverRaw(gd, evt);
  20877. if(hasCartesian && ((spikePoints.hLinePoint !== null) || (spikePoints.vLinePoint !== null))) {
  20878. if(spikesChanged(oldspikepoints)) {
  20879. createSpikelines(spikePoints, spikelineOpts);
  20880. }
  20881. }
  20882. return result;
  20883. }
  20884. if(hasCartesian) {
  20885. if(spikesChanged(oldspikepoints)) {
  20886. createSpikelines(spikePoints, spikelineOpts);
  20887. }
  20888. }
  20889. hoverData.sort(function(d1, d2) { return d1.distance - d2.distance; });
  20890. // lastly, emit custom hover/unhover events
  20891. var oldhoverdata = gd._hoverdata;
  20892. var newhoverdata = [];
  20893. // pull out just the data that's useful to
  20894. // other people and send it to the event
  20895. for(itemnum = 0; itemnum < hoverData.length; itemnum++) {
  20896. var pt = hoverData[itemnum];
  20897. var eventData = helpers.makeEventData(pt, pt.trace, pt.cd);
  20898. var ht = false;
  20899. if(pt.cd[pt.index] && pt.cd[pt.index].ht) ht = pt.cd[pt.index].ht;
  20900. hoverData[itemnum].hovertemplate = ht || pt.trace.hovertemplate || false;
  20901. hoverData[itemnum].eventData = [eventData];
  20902. newhoverdata.push(eventData);
  20903. }
  20904. gd._hoverdata = newhoverdata;
  20905. var rotateLabels = (
  20906. (hovermode === 'y' && (searchData.length > 1 || hoverData.length > 1)) ||
  20907. (hovermode === 'closest' && hasOneHorizontalTrace && hoverData.length > 1)
  20908. );
  20909. var bgColor = Color.combine(
  20910. fullLayout.plot_bgcolor || Color.background,
  20911. fullLayout.paper_bgcolor
  20912. );
  20913. var labelOpts = {
  20914. hovermode: hovermode,
  20915. rotateLabels: rotateLabels,
  20916. bgColor: bgColor,
  20917. container: fullLayout._hoverlayer,
  20918. outerContainer: fullLayout._paperdiv,
  20919. commonLabelOpts: fullLayout.hoverlabel,
  20920. hoverdistance: fullLayout.hoverdistance
  20921. };
  20922. var hoverLabels = createHoverText(hoverData, labelOpts, gd);
  20923. hoverAvoidOverlaps(hoverData, rotateLabels ? 'xa' : 'ya', fullLayout);
  20924. alignHoverText(hoverLabels, rotateLabels);
  20925. // TODO: tagName hack is needed to appease geo.js's hack of using evt.target=true
  20926. // we should improve the "fx" API so other plots can use it without these hack.
  20927. if(evt.target && evt.target.tagName) {
  20928. var hasClickToShow = Registry.getComponentMethod('annotations', 'hasClickToShow')(gd, newhoverdata);
  20929. overrideCursor(d3.select(evt.target), hasClickToShow ? 'pointer' : '');
  20930. }
  20931. // don't emit events if called manually
  20932. if(!evt.target || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return;
  20933. if(oldhoverdata) {
  20934. gd.emit('plotly_unhover', {
  20935. event: evt,
  20936. points: oldhoverdata
  20937. });
  20938. }
  20939. gd.emit('plotly_hover', {
  20940. event: evt,
  20941. points: gd._hoverdata,
  20942. xaxes: xaArray,
  20943. yaxes: yaArray,
  20944. xvals: xvalArray,
  20945. yvals: yvalArray
  20946. });
  20947. }
  20948. var EXTRA_STRING_REGEX = /<extra>([\s\S]*)<\/extra>/;
  20949. function createHoverText(hoverData, opts, gd) {
  20950. var hovermode = opts.hovermode;
  20951. var rotateLabels = opts.rotateLabels;
  20952. var bgColor = opts.bgColor;
  20953. var container = opts.container;
  20954. var outerContainer = opts.outerContainer;
  20955. var commonLabelOpts = opts.commonLabelOpts || {};
  20956. // opts.fontFamily/Size are used for the common label
  20957. // and as defaults for each hover label, though the individual labels
  20958. // can override this.
  20959. var fontFamily = opts.fontFamily || constants.HOVERFONT;
  20960. var fontSize = opts.fontSize || constants.HOVERFONTSIZE;
  20961. var c0 = hoverData[0];
  20962. var xa = c0.xa;
  20963. var ya = c0.ya;
  20964. var commonAttr = hovermode === 'y' ? 'yLabel' : 'xLabel';
  20965. var t0 = c0[commonAttr];
  20966. var t00 = (String(t0) || '').split(' ')[0];
  20967. var outerContainerBB = outerContainer.node().getBoundingClientRect();
  20968. var outerTop = outerContainerBB.top;
  20969. var outerWidth = outerContainerBB.width;
  20970. var outerHeight = outerContainerBB.height;
  20971. // show the common label, if any, on the axis
  20972. // never show a common label in array mode,
  20973. // even if sometimes there could be one
  20974. var showCommonLabel = (
  20975. (t0 !== undefined) &&
  20976. (c0.distance <= opts.hoverdistance) &&
  20977. (hovermode === 'x' || hovermode === 'y')
  20978. );
  20979. // all hover traces hoverinfo must contain the hovermode
  20980. // to have common labels
  20981. if(showCommonLabel) {
  20982. var allHaveZ = true;
  20983. var i, traceHoverinfo;
  20984. for(i = 0; i < hoverData.length; i++) {
  20985. if(allHaveZ && hoverData[i].zLabel === undefined) allHaveZ = false;
  20986. traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo;
  20987. if(traceHoverinfo) {
  20988. var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split('+');
  20989. if(parts.indexOf('all') === -1 &&
  20990. parts.indexOf(hovermode) === -1) {
  20991. showCommonLabel = false;
  20992. break;
  20993. }
  20994. }
  20995. }
  20996. // xyz labels put all info in their main label, so have no need of a common label
  20997. if(allHaveZ) showCommonLabel = false;
  20998. }
  20999. var commonLabel = container.selectAll('g.axistext')
  21000. .data(showCommonLabel ? [0] : []);
  21001. commonLabel.enter().append('g')
  21002. .classed('axistext', true);
  21003. commonLabel.exit().remove();
  21004. commonLabel.each(function() {
  21005. var label = d3.select(this);
  21006. var lpath = Lib.ensureSingle(label, 'path', '', function(s) {
  21007. s.style({'stroke-width': '1px'});
  21008. });
  21009. var ltext = Lib.ensureSingle(label, 'text', '', function(s) {
  21010. // prohibit tex interpretation until we can handle
  21011. // tex and regular text together
  21012. s.attr('data-notex', 1);
  21013. });
  21014. var commonBgColor = commonLabelOpts.bgcolor || Color.defaultLine;
  21015. var commonStroke = commonLabelOpts.bordercolor || Color.contrast(commonBgColor);
  21016. var contrastColor = Color.contrast(commonBgColor);
  21017. lpath.style({
  21018. fill: commonBgColor,
  21019. stroke: commonStroke
  21020. });
  21021. ltext.text(t0)
  21022. .call(Drawing.font,
  21023. commonLabelOpts.font.family || fontFamily,
  21024. commonLabelOpts.font.size || fontSize,
  21025. commonLabelOpts.font.color || contrastColor
  21026. )
  21027. .call(svgTextUtils.positionText, 0, 0)
  21028. .call(svgTextUtils.convertToTspans, gd);
  21029. label.attr('transform', '');
  21030. var tbb = ltext.node().getBoundingClientRect();
  21031. if(hovermode === 'x') {
  21032. ltext.attr('text-anchor', 'middle')
  21033. .call(svgTextUtils.positionText, 0, (xa.side === 'top' ?
  21034. (outerTop - tbb.bottom - HOVERARROWSIZE - HOVERTEXTPAD) :
  21035. (outerTop - tbb.top + HOVERARROWSIZE + HOVERTEXTPAD)));
  21036. var topsign = xa.side === 'top' ? '-' : '';
  21037. lpath.attr('d', 'M0,0' +
  21038. 'L' + HOVERARROWSIZE + ',' + topsign + HOVERARROWSIZE +
  21039. 'H' + (HOVERTEXTPAD + tbb.width / 2) +
  21040. 'v' + topsign + (HOVERTEXTPAD * 2 + tbb.height) +
  21041. 'H-' + (HOVERTEXTPAD + tbb.width / 2) +
  21042. 'V' + topsign + HOVERARROWSIZE + 'H-' + HOVERARROWSIZE + 'Z');
  21043. label.attr('transform', 'translate(' +
  21044. (xa._offset + (c0.x0 + c0.x1) / 2) + ',' +
  21045. (ya._offset + (xa.side === 'top' ? 0 : ya._length)) + ')');
  21046. }
  21047. else {
  21048. ltext.attr('text-anchor', ya.side === 'right' ? 'start' : 'end')
  21049. .call(svgTextUtils.positionText,
  21050. (ya.side === 'right' ? 1 : -1) * (HOVERTEXTPAD + HOVERARROWSIZE),
  21051. outerTop - tbb.top - tbb.height / 2);
  21052. var leftsign = ya.side === 'right' ? '' : '-';
  21053. lpath.attr('d', 'M0,0' +
  21054. 'L' + leftsign + HOVERARROWSIZE + ',' + HOVERARROWSIZE +
  21055. 'V' + (HOVERTEXTPAD + tbb.height / 2) +
  21056. 'h' + leftsign + (HOVERTEXTPAD * 2 + tbb.width) +
  21057. 'V-' + (HOVERTEXTPAD + tbb.height / 2) +
  21058. 'H' + leftsign + HOVERARROWSIZE + 'V-' + HOVERARROWSIZE + 'Z');
  21059. label.attr('transform', 'translate(' +
  21060. (xa._offset + (ya.side === 'right' ? xa._length : 0)) + ',' +
  21061. (ya._offset + (c0.y0 + c0.y1) / 2) + ')');
  21062. }
  21063. // remove the "close but not quite" points
  21064. // because of error bars, only take up to a space
  21065. hoverData = hoverData.filter(function(d) {
  21066. return (d.zLabelVal !== undefined) ||
  21067. (d[commonAttr] || '').split(' ')[0] === t00;
  21068. });
  21069. });
  21070. // show all the individual labels
  21071. // first create the objects
  21072. var hoverLabels = container.selectAll('g.hovertext')
  21073. .data(hoverData, function(d) {
  21074. return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa, d.ya || ''].join(',');
  21075. });
  21076. hoverLabels.enter().append('g')
  21077. .classed('hovertext', true)
  21078. .each(function() {
  21079. var g = d3.select(this);
  21080. // trace name label (rect and text.name)
  21081. g.append('rect')
  21082. .call(Color.fill, Color.addOpacity(bgColor, 0.8));
  21083. g.append('text').classed('name', true);
  21084. // trace data label (path and text.nums)
  21085. g.append('path')
  21086. .style('stroke-width', '1px');
  21087. g.append('text').classed('nums', true)
  21088. .call(Drawing.font, fontFamily, fontSize);
  21089. });
  21090. hoverLabels.exit().remove();
  21091. // then put the text in, position the pointer to the data,
  21092. // and figure out sizes
  21093. hoverLabels.each(function(d) {
  21094. var g = d3.select(this).attr('transform', '');
  21095. var name = '';
  21096. var text = '';
  21097. // combine possible non-opaque trace color with bgColor
  21098. var color0 = d.bgcolor || d.color;
  21099. // color for 'nums' part of the label
  21100. var numsColor = Color.combine(
  21101. Color.opacity(color0) ? color0 : Color.defaultLine,
  21102. bgColor
  21103. );
  21104. // color for 'name' part of the label
  21105. var nameColor = Color.combine(
  21106. Color.opacity(d.color) ? d.color : Color.defaultLine,
  21107. bgColor
  21108. );
  21109. // find a contrasting color for border and text
  21110. var contrastColor = d.borderColor || Color.contrast(numsColor);
  21111. // to get custom 'name' labels pass cleanPoint
  21112. if(d.nameOverride !== undefined) d.name = d.nameOverride;
  21113. if(d.name) {
  21114. name = svgTextUtils.plainText(d.name || '', {
  21115. len: d.nameLength,
  21116. allowedTags: ['br', 'sub', 'sup', 'b', 'i', 'em']
  21117. });
  21118. }
  21119. if(d.zLabel !== undefined) {
  21120. if(d.xLabel !== undefined) text += 'x: ' + d.xLabel + '<br>';
  21121. if(d.yLabel !== undefined) text += 'y: ' + d.yLabel + '<br>';
  21122. text += (text ? 'z: ' : '') + d.zLabel;
  21123. }
  21124. else if(showCommonLabel && d[hovermode + 'Label'] === t0) {
  21125. text = d[(hovermode === 'x' ? 'y' : 'x') + 'Label'] || '';
  21126. }
  21127. else if(d.xLabel === undefined) {
  21128. if(d.yLabel !== undefined) text = d.yLabel;
  21129. }
  21130. else if(d.yLabel === undefined) text = d.xLabel;
  21131. else text = '(' + d.xLabel + ', ' + d.yLabel + ')';
  21132. if((d.text || d.text === 0) && !Array.isArray(d.text)) {
  21133. text += (text ? '<br>' : '') + d.text;
  21134. }
  21135. // used by other modules (initially just ternary) that
  21136. // manage their own hoverinfo independent of cleanPoint
  21137. // the rest of this will still apply, so such modules
  21138. // can still put things in (x|y|z)Label, text, and name
  21139. // and hoverinfo will still determine their visibility
  21140. if(d.extraText !== undefined) text += (text ? '<br>' : '') + d.extraText;
  21141. // if 'text' is empty at this point,
  21142. // and hovertemplate is not defined,
  21143. // put 'name' in main label and don't show secondary label
  21144. if(text === '' && !d.hovertemplate) {
  21145. // if 'name' is also empty, remove entire label
  21146. if(name === '') g.remove();
  21147. text = name;
  21148. }
  21149. // hovertemplate
  21150. var hovertemplate = d.hovertemplate || false;
  21151. var hovertemplateLabels = d.hovertemplateLabels || d;
  21152. var eventData = d.eventData[0] || {};
  21153. if(hovertemplate) {
  21154. text = Lib.hovertemplateString(hovertemplate, hovertemplateLabels, eventData);
  21155. text = text.replace(EXTRA_STRING_REGEX, function(match, extra) {
  21156. name = extra; // Assign name for secondary text label
  21157. return ''; // Remove from main text label
  21158. });
  21159. }
  21160. // main label
  21161. var tx = g.select('text.nums')
  21162. .call(Drawing.font,
  21163. d.fontFamily || fontFamily,
  21164. d.fontSize || fontSize,
  21165. d.fontColor || contrastColor)
  21166. .text(text)
  21167. .attr('data-notex', 1)
  21168. .call(svgTextUtils.positionText, 0, 0)
  21169. .call(svgTextUtils.convertToTspans, gd);
  21170. var tx2 = g.select('text.name');
  21171. var tx2width = 0;
  21172. var tx2height = 0;
  21173. // secondary label for non-empty 'name'
  21174. if(name && name !== text) {
  21175. tx2.call(Drawing.font,
  21176. d.fontFamily || fontFamily,
  21177. d.fontSize || fontSize,
  21178. nameColor)
  21179. .text(name)
  21180. .attr('data-notex', 1)
  21181. .call(svgTextUtils.positionText, 0, 0)
  21182. .call(svgTextUtils.convertToTspans, gd);
  21183. var t2bb = tx2.node().getBoundingClientRect();
  21184. tx2width = t2bb.width + 2 * HOVERTEXTPAD;
  21185. tx2height = t2bb.height + 2 * HOVERTEXTPAD;
  21186. } else {
  21187. tx2.remove();
  21188. g.select('rect').remove();
  21189. }
  21190. g.select('path').style({
  21191. fill: numsColor,
  21192. stroke: contrastColor
  21193. });
  21194. var tbb = tx.node().getBoundingClientRect();
  21195. var htx = d.xa._offset + (d.x0 + d.x1) / 2;
  21196. var hty = d.ya._offset + (d.y0 + d.y1) / 2;
  21197. var dx = Math.abs(d.x1 - d.x0);
  21198. var dy = Math.abs(d.y1 - d.y0);
  21199. var txTotalWidth = tbb.width + HOVERARROWSIZE + HOVERTEXTPAD + tx2width;
  21200. var anchorStartOK, anchorEndOK;
  21201. d.ty0 = outerTop - tbb.top;
  21202. d.bx = tbb.width + 2 * HOVERTEXTPAD;
  21203. d.by = Math.max(tbb.height + 2 * HOVERTEXTPAD, tx2height);
  21204. d.anchor = 'start';
  21205. d.txwidth = tbb.width;
  21206. d.tx2width = tx2width;
  21207. d.offset = 0;
  21208. if(rotateLabels) {
  21209. d.pos = htx;
  21210. anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight;
  21211. anchorEndOK = hty - dy / 2 - txTotalWidth >= 0;
  21212. if((d.idealAlign === 'top' || !anchorStartOK) && anchorEndOK) {
  21213. hty -= dy / 2;
  21214. d.anchor = 'end';
  21215. } else if(anchorStartOK) {
  21216. hty += dy / 2;
  21217. d.anchor = 'start';
  21218. } else d.anchor = 'middle';
  21219. }
  21220. else {
  21221. d.pos = hty;
  21222. anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth;
  21223. anchorEndOK = htx - dx / 2 - txTotalWidth >= 0;
  21224. if((d.idealAlign === 'left' || !anchorStartOK) && anchorEndOK) {
  21225. htx -= dx / 2;
  21226. d.anchor = 'end';
  21227. } else if(anchorStartOK) {
  21228. htx += dx / 2;
  21229. d.anchor = 'start';
  21230. } else d.anchor = 'middle';
  21231. }
  21232. tx.attr('text-anchor', d.anchor);
  21233. if(tx2width) tx2.attr('text-anchor', d.anchor);
  21234. g.attr('transform', 'translate(' + htx + ',' + hty + ')' +
  21235. (rotateLabels ? 'rotate(' + YANGLE + ')' : ''));
  21236. });
  21237. return hoverLabels;
  21238. }
  21239. // Make groups of touching points, and within each group
  21240. // move each point so that no labels overlap, but the average
  21241. // label position is the same as it was before moving. Indicentally,
  21242. // this is equivalent to saying all the labels are on equal linear
  21243. // springs about their initial position. Initially, each point is
  21244. // its own group, but as we find overlaps we will clump the points.
  21245. //
  21246. // Also, there are hard constraints at the edges of the graphs,
  21247. // that push all groups to the middle so they are visible. I don't
  21248. // know what happens if the group spans all the way from one edge to
  21249. // the other, though it hardly matters - there's just too much
  21250. // information then.
  21251. function hoverAvoidOverlaps(hoverData, ax, fullLayout) {
  21252. var nummoves = 0;
  21253. var axSign = 1;
  21254. // make groups of touching points
  21255. var pointgroups = hoverData.map(function(d, i) {
  21256. var axis = d[ax];
  21257. var axIsX = axis._id.charAt(0) === 'x';
  21258. var rng = axis.range;
  21259. if(!i && rng && ((rng[0] > rng[1]) !== axIsX)) axSign = -1;
  21260. return [{
  21261. i: i,
  21262. traceIndex: d.trace.index,
  21263. dp: 0,
  21264. pos: d.pos,
  21265. posref: d.posref,
  21266. size: d.by * (axIsX ? YFACTOR : 1) / 2,
  21267. pmin: 0,
  21268. pmax: (axIsX ? fullLayout.width : fullLayout.height)
  21269. }];
  21270. })
  21271. .sort(function(a, b) {
  21272. return (a[0].posref - b[0].posref) ||
  21273. // for equal positions, sort trace indices increasing or decreasing
  21274. // depending on whether the axis is reversed or not... so stacked
  21275. // traces will generally keep their order even if one trace adds
  21276. // nothing to the stack.
  21277. (axSign * (b[0].traceIndex - a[0].traceIndex));
  21278. });
  21279. var donepositioning, topOverlap, bottomOverlap, i, j, pti, sumdp;
  21280. function constrainGroup(grp) {
  21281. var minPt = grp[0];
  21282. var maxPt = grp[grp.length - 1];
  21283. // overlap with the top - positive vals are overlaps
  21284. topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size;
  21285. // overlap with the bottom - positive vals are overlaps
  21286. bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax;
  21287. // check for min overlap first, so that we always
  21288. // see the largest labels
  21289. // allow for .01px overlap, so we don't get an
  21290. // infinite loop from rounding errors
  21291. if(topOverlap > 0.01) {
  21292. for(j = grp.length - 1; j >= 0; j--) grp[j].dp += topOverlap;
  21293. donepositioning = false;
  21294. }
  21295. if(bottomOverlap < 0.01) return;
  21296. if(topOverlap < -0.01) {
  21297. // make sure we're not pushing back and forth
  21298. for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap;
  21299. donepositioning = false;
  21300. }
  21301. if(!donepositioning) return;
  21302. // no room to fix positioning, delete off-screen points
  21303. // first see how many points we need to delete
  21304. var deleteCount = 0;
  21305. for(i = 0; i < grp.length; i++) {
  21306. pti = grp[i];
  21307. if(pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++;
  21308. }
  21309. // start by deleting points whose data is off screen
  21310. for(i = grp.length - 1; i >= 0; i--) {
  21311. if(deleteCount <= 0) break;
  21312. pti = grp[i];
  21313. // pos has already been constrained to [pmin,pmax]
  21314. // so look for points close to that to delete
  21315. if(pti.pos > minPt.pmax - 1) {
  21316. pti.del = true;
  21317. deleteCount--;
  21318. }
  21319. }
  21320. for(i = 0; i < grp.length; i++) {
  21321. if(deleteCount <= 0) break;
  21322. pti = grp[i];
  21323. // pos has already been constrained to [pmin,pmax]
  21324. // so look for points close to that to delete
  21325. if(pti.pos < minPt.pmin + 1) {
  21326. pti.del = true;
  21327. deleteCount--;
  21328. // shift the whole group minus into this new space
  21329. bottomOverlap = pti.size * 2;
  21330. for(j = grp.length - 1; j >= 0; j--) grp[j].dp -= bottomOverlap;
  21331. }
  21332. }
  21333. // then delete points that go off the bottom
  21334. for(i = grp.length - 1; i >= 0; i--) {
  21335. if(deleteCount <= 0) break;
  21336. pti = grp[i];
  21337. if(pti.pos + pti.dp + pti.size > minPt.pmax) {
  21338. pti.del = true;
  21339. deleteCount--;
  21340. }
  21341. }
  21342. }
  21343. // loop through groups, combining them if they overlap,
  21344. // until nothing moves
  21345. while(!donepositioning && nummoves <= hoverData.length) {
  21346. // to avoid infinite loops, don't move more times
  21347. // than there are traces
  21348. nummoves++;
  21349. // assume nothing will move in this iteration,
  21350. // reverse this if it does
  21351. donepositioning = true;
  21352. i = 0;
  21353. while(i < pointgroups.length - 1) {
  21354. // the higher (g0) and lower (g1) point group
  21355. var g0 = pointgroups[i];
  21356. var g1 = pointgroups[i + 1];
  21357. // the lowest point in the higher group (p0)
  21358. // the highest point in the lower group (p1)
  21359. var p0 = g0[g0.length - 1];
  21360. var p1 = g1[0];
  21361. topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size;
  21362. // Only group points that lie on the same axes
  21363. if(topOverlap > 0.01 && (p0.pmin === p1.pmin) && (p0.pmax === p1.pmax)) {
  21364. // push the new point(s) added to this group out of the way
  21365. for(j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap;
  21366. // add them to the group
  21367. g0.push.apply(g0, g1);
  21368. pointgroups.splice(i + 1, 1);
  21369. // adjust for minimum average movement
  21370. sumdp = 0;
  21371. for(j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp;
  21372. bottomOverlap = sumdp / g0.length;
  21373. for(j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap;
  21374. donepositioning = false;
  21375. }
  21376. else i++;
  21377. }
  21378. // check if we're going off the plot on either side and fix
  21379. pointgroups.forEach(constrainGroup);
  21380. }
  21381. // now put these offsets into hoverData
  21382. for(i = pointgroups.length - 1; i >= 0; i--) {
  21383. var grp = pointgroups[i];
  21384. for(j = grp.length - 1; j >= 0; j--) {
  21385. var pt = grp[j];
  21386. var hoverPt = hoverData[pt.i];
  21387. hoverPt.offset = pt.dp;
  21388. hoverPt.del = pt.del;
  21389. }
  21390. }
  21391. }
  21392. function alignHoverText(hoverLabels, rotateLabels) {
  21393. // finally set the text positioning relative to the data and draw the
  21394. // box around it
  21395. hoverLabels.each(function(d) {
  21396. var g = d3.select(this);
  21397. if(d.del) {
  21398. g.remove();
  21399. return;
  21400. }
  21401. var horzSign = d.anchor === 'end' ? -1 : 1;
  21402. var tx = g.select('text.nums');
  21403. var alignShift = {start: 1, end: -1, middle: 0}[d.anchor];
  21404. var txx = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD);
  21405. var tx2x = txx + alignShift * (d.txwidth + HOVERTEXTPAD);
  21406. var offsetX = 0;
  21407. var offsetY = d.offset;
  21408. if(d.anchor === 'middle') {
  21409. txx -= d.tx2width / 2;
  21410. tx2x += d.txwidth / 2 + HOVERTEXTPAD;
  21411. }
  21412. if(rotateLabels) {
  21413. offsetY *= -YSHIFTY;
  21414. offsetX = d.offset * YSHIFTX;
  21415. }
  21416. g.select('path').attr('d', d.anchor === 'middle' ?
  21417. // middle aligned: rect centered on data
  21418. ('M-' + (d.bx / 2 + d.tx2width / 2) + ',' + (offsetY - d.by / 2) +
  21419. 'h' + d.bx + 'v' + d.by + 'h-' + d.bx + 'Z') :
  21420. // left or right aligned: side rect with arrow to data
  21421. ('M0,0L' + (horzSign * HOVERARROWSIZE + offsetX) + ',' + (HOVERARROWSIZE + offsetY) +
  21422. 'v' + (d.by / 2 - HOVERARROWSIZE) +
  21423. 'h' + (horzSign * d.bx) +
  21424. 'v-' + d.by +
  21425. 'H' + (horzSign * HOVERARROWSIZE + offsetX) +
  21426. 'V' + (offsetY - HOVERARROWSIZE) +
  21427. 'Z'));
  21428. tx.call(svgTextUtils.positionText,
  21429. txx + offsetX, offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD);
  21430. if(d.tx2width) {
  21431. g.select('text.name')
  21432. .call(svgTextUtils.positionText,
  21433. tx2x + alignShift * HOVERTEXTPAD + offsetX,
  21434. offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD);
  21435. g.select('rect')
  21436. .call(Drawing.setRect,
  21437. tx2x + (alignShift - 1) * d.tx2width / 2 + offsetX,
  21438. offsetY - d.by / 2 - 1,
  21439. d.tx2width, d.by + 2);
  21440. }
  21441. });
  21442. }
  21443. function cleanPoint(d, hovermode) {
  21444. var index = d.index;
  21445. var trace = d.trace || {};
  21446. var cd0 = d.cd[0];
  21447. var cd = d.cd[index] || {};
  21448. var getVal = Array.isArray(index) ?
  21449. function(calcKey, traceKey) {
  21450. return Lib.castOption(cd0, index, calcKey) ||
  21451. Lib.extractOption({}, trace, '', traceKey);
  21452. } :
  21453. function(calcKey, traceKey) {
  21454. return Lib.extractOption(cd, trace, calcKey, traceKey);
  21455. };
  21456. function fill(key, calcKey, traceKey) {
  21457. var val = getVal(calcKey, traceKey);
  21458. if(val) d[key] = val;
  21459. }
  21460. fill('hoverinfo', 'hi', 'hoverinfo');
  21461. fill('bgcolor', 'hbg', 'hoverlabel.bgcolor');
  21462. fill('borderColor', 'hbc', 'hoverlabel.bordercolor');
  21463. fill('fontFamily', 'htf', 'hoverlabel.font.family');
  21464. fill('fontSize', 'hts', 'hoverlabel.font.size');
  21465. fill('fontColor', 'htc', 'hoverlabel.font.color');
  21466. fill('nameLength', 'hnl', 'hoverlabel.namelength');
  21467. d.posref = (hovermode === 'y' || (hovermode === 'closest' && trace.orientation === 'h')) ?
  21468. (d.xa._offset + (d.x0 + d.x1) / 2) :
  21469. (d.ya._offset + (d.y0 + d.y1) / 2);
  21470. // then constrain all the positions to be on the plot
  21471. d.x0 = Lib.constrain(d.x0, 0, d.xa._length);
  21472. d.x1 = Lib.constrain(d.x1, 0, d.xa._length);
  21473. d.y0 = Lib.constrain(d.y0, 0, d.ya._length);
  21474. d.y1 = Lib.constrain(d.y1, 0, d.ya._length);
  21475. // and convert the x and y label values into formatted text
  21476. if(d.xLabelVal !== undefined) {
  21477. d.xLabel = ('xLabel' in d) ? d.xLabel : Axes.hoverLabelText(d.xa, d.xLabelVal);
  21478. d.xVal = d.xa.c2d(d.xLabelVal);
  21479. }
  21480. if(d.yLabelVal !== undefined) {
  21481. d.yLabel = ('yLabel' in d) ? d.yLabel : Axes.hoverLabelText(d.ya, d.yLabelVal);
  21482. d.yVal = d.ya.c2d(d.yLabelVal);
  21483. }
  21484. // Traces like heatmaps generate the zLabel in their hoverPoints function
  21485. if(d.zLabelVal !== undefined && d.zLabel === undefined) {
  21486. d.zLabel = String(d.zLabelVal);
  21487. }
  21488. // for box means and error bars, add the range to the label
  21489. if(!isNaN(d.xerr) && !(d.xa.type === 'log' && d.xerr <= 0)) {
  21490. var xeText = Axes.tickText(d.xa, d.xa.c2l(d.xerr), 'hover').text;
  21491. if(d.xerrneg !== undefined) {
  21492. d.xLabel += ' +' + xeText + ' / -' +
  21493. Axes.tickText(d.xa, d.xa.c2l(d.xerrneg), 'hover').text;
  21494. }
  21495. else d.xLabel += ' ± ' + xeText;
  21496. // small distance penalty for error bars, so that if there are
  21497. // traces with errors and some without, the error bar label will
  21498. // hoist up to the point
  21499. if(hovermode === 'x') d.distance += 1;
  21500. }
  21501. if(!isNaN(d.yerr) && !(d.ya.type === 'log' && d.yerr <= 0)) {
  21502. var yeText = Axes.tickText(d.ya, d.ya.c2l(d.yerr), 'hover').text;
  21503. if(d.yerrneg !== undefined) {
  21504. d.yLabel += ' +' + yeText + ' / -' +
  21505. Axes.tickText(d.ya, d.ya.c2l(d.yerrneg), 'hover').text;
  21506. }
  21507. else d.yLabel += ' ± ' + yeText;
  21508. if(hovermode === 'y') d.distance += 1;
  21509. }
  21510. var infomode = d.hoverinfo || d.trace.hoverinfo;
  21511. if(infomode && infomode !== 'all') {
  21512. infomode = Array.isArray(infomode) ? infomode : infomode.split('+');
  21513. if(infomode.indexOf('x') === -1) d.xLabel = undefined;
  21514. if(infomode.indexOf('y') === -1) d.yLabel = undefined;
  21515. if(infomode.indexOf('z') === -1) d.zLabel = undefined;
  21516. if(infomode.indexOf('text') === -1) d.text = undefined;
  21517. if(infomode.indexOf('name') === -1) d.name = undefined;
  21518. }
  21519. return d;
  21520. }
  21521. function createSpikelines(closestPoints, opts) {
  21522. var container = opts.container;
  21523. var fullLayout = opts.fullLayout;
  21524. var evt = opts.event;
  21525. var showY = !!closestPoints.hLinePoint;
  21526. var showX = !!closestPoints.vLinePoint;
  21527. var xa, ya;
  21528. // Remove old spikeline items
  21529. container.selectAll('.spikeline').remove();
  21530. if(!(showX || showY)) return;
  21531. var contrastColor = Color.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor);
  21532. // Horizontal line (to y-axis)
  21533. if(showY) {
  21534. var hLinePoint = closestPoints.hLinePoint;
  21535. var hLinePointX, hLinePointY;
  21536. xa = hLinePoint && hLinePoint.xa;
  21537. ya = hLinePoint && hLinePoint.ya;
  21538. var ySnap = ya.spikesnap;
  21539. if(ySnap === 'cursor') {
  21540. hLinePointX = evt.pointerX;
  21541. hLinePointY = evt.pointerY;
  21542. } else {
  21543. hLinePointX = xa._offset + hLinePoint.x;
  21544. hLinePointY = ya._offset + hLinePoint.y;
  21545. }
  21546. var dfltHLineColor = tinycolor.readability(hLinePoint.color, contrastColor) < 1.5 ?
  21547. Color.contrast(contrastColor) : hLinePoint.color;
  21548. var yMode = ya.spikemode;
  21549. var yThickness = ya.spikethickness;
  21550. var yColor = ya.spikecolor || dfltHLineColor;
  21551. var yBB = ya._boundingBox;
  21552. var xEdge = ((yBB.left + yBB.right) / 2) < hLinePointX ? yBB.right : yBB.left;
  21553. var xBase, xEndSpike;
  21554. if(yMode.indexOf('toaxis') !== -1 || yMode.indexOf('across') !== -1) {
  21555. if(yMode.indexOf('toaxis') !== -1) {
  21556. xBase = xEdge;
  21557. xEndSpike = hLinePointX;
  21558. }
  21559. if(yMode.indexOf('across') !== -1) {
  21560. xBase = ya._counterSpan[0];
  21561. xEndSpike = ya._counterSpan[1];
  21562. }
  21563. // Foreground horizontal line (to y-axis)
  21564. container.insert('line', ':first-child')
  21565. .attr({
  21566. x1: xBase,
  21567. x2: xEndSpike,
  21568. y1: hLinePointY,
  21569. y2: hLinePointY,
  21570. 'stroke-width': yThickness,
  21571. stroke: yColor,
  21572. 'stroke-dasharray': Drawing.dashStyle(ya.spikedash, yThickness)
  21573. })
  21574. .classed('spikeline', true)
  21575. .classed('crisp', true);
  21576. // Background horizontal Line (to y-axis)
  21577. container.insert('line', ':first-child')
  21578. .attr({
  21579. x1: xBase,
  21580. x2: xEndSpike,
  21581. y1: hLinePointY,
  21582. y2: hLinePointY,
  21583. 'stroke-width': yThickness + 2,
  21584. stroke: contrastColor
  21585. })
  21586. .classed('spikeline', true)
  21587. .classed('crisp', true);
  21588. }
  21589. // Y axis marker
  21590. if(yMode.indexOf('marker') !== -1) {
  21591. container.insert('circle', ':first-child')
  21592. .attr({
  21593. cx: xEdge + (ya.side !== 'right' ? yThickness : -yThickness),
  21594. cy: hLinePointY,
  21595. r: yThickness,
  21596. fill: yColor
  21597. })
  21598. .classed('spikeline', true);
  21599. }
  21600. }
  21601. if(showX) {
  21602. var vLinePoint = closestPoints.vLinePoint;
  21603. var vLinePointX, vLinePointY;
  21604. xa = vLinePoint && vLinePoint.xa;
  21605. ya = vLinePoint && vLinePoint.ya;
  21606. var xSnap = xa.spikesnap;
  21607. if(xSnap === 'cursor') {
  21608. vLinePointX = evt.pointerX;
  21609. vLinePointY = evt.pointerY;
  21610. } else {
  21611. vLinePointX = xa._offset + vLinePoint.x;
  21612. vLinePointY = ya._offset + vLinePoint.y;
  21613. }
  21614. var dfltVLineColor = tinycolor.readability(vLinePoint.color, contrastColor) < 1.5 ?
  21615. Color.contrast(contrastColor) : vLinePoint.color;
  21616. var xMode = xa.spikemode;
  21617. var xThickness = xa.spikethickness;
  21618. var xColor = xa.spikecolor || dfltVLineColor;
  21619. var xBB = xa._boundingBox;
  21620. var yEdge = ((xBB.top + xBB.bottom) / 2) < vLinePointY ? xBB.bottom : xBB.top;
  21621. var yBase, yEndSpike;
  21622. if(xMode.indexOf('toaxis') !== -1 || xMode.indexOf('across') !== -1) {
  21623. if(xMode.indexOf('toaxis') !== -1) {
  21624. yBase = yEdge;
  21625. yEndSpike = vLinePointY;
  21626. }
  21627. if(xMode.indexOf('across') !== -1) {
  21628. yBase = xa._counterSpan[0];
  21629. yEndSpike = xa._counterSpan[1];
  21630. }
  21631. // Foreground vertical line (to x-axis)
  21632. container.insert('line', ':first-child')
  21633. .attr({
  21634. x1: vLinePointX,
  21635. x2: vLinePointX,
  21636. y1: yBase,
  21637. y2: yEndSpike,
  21638. 'stroke-width': xThickness,
  21639. stroke: xColor,
  21640. 'stroke-dasharray': Drawing.dashStyle(xa.spikedash, xThickness)
  21641. })
  21642. .classed('spikeline', true)
  21643. .classed('crisp', true);
  21644. // Background vertical line (to x-axis)
  21645. container.insert('line', ':first-child')
  21646. .attr({
  21647. x1: vLinePointX,
  21648. x2: vLinePointX,
  21649. y1: yBase,
  21650. y2: yEndSpike,
  21651. 'stroke-width': xThickness + 2,
  21652. stroke: contrastColor
  21653. })
  21654. .classed('spikeline', true)
  21655. .classed('crisp', true);
  21656. }
  21657. // X axis marker
  21658. if(xMode.indexOf('marker') !== -1) {
  21659. container.insert('circle', ':first-child')
  21660. .attr({
  21661. cx: vLinePointX,
  21662. cy: yEdge - (xa.side !== 'top' ? xThickness : -xThickness),
  21663. r: xThickness,
  21664. fill: xColor
  21665. })
  21666. .classed('spikeline', true);
  21667. }
  21668. }
  21669. }
  21670. function hoverChanged(gd, evt, oldhoverdata) {
  21671. // don't emit any events if nothing changed
  21672. if(!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true;
  21673. for(var i = oldhoverdata.length - 1; i >= 0; i--) {
  21674. var oldPt = oldhoverdata[i];
  21675. var newPt = gd._hoverdata[i];
  21676. if(oldPt.curveNumber !== newPt.curveNumber ||
  21677. String(oldPt.pointNumber) !== String(newPt.pointNumber) ||
  21678. String(oldPt.pointNumbers) !== String(newPt.pointNumbers)
  21679. ) {
  21680. return true;
  21681. }
  21682. }
  21683. return false;
  21684. }
  21685. function spikesChanged(gd, oldspikepoints) {
  21686. // don't relayout the plot because of new spikelines if spikelines points didn't change
  21687. if(!oldspikepoints) return true;
  21688. if(oldspikepoints.vLinePoint !== gd._spikepoints.vLinePoint ||
  21689. oldspikepoints.hLinePoint !== gd._spikepoints.hLinePoint
  21690. ) return true;
  21691. return false;
  21692. }
  21693. },{"../../lib":168,"../../lib/events":161,"../../lib/override_cursor":179,"../../lib/svg_text_utils":189,"../../plots/cartesian/axes":212,"../../registry":257,"../color":51,"../dragelement":69,"../drawing":72,"./constants":84,"./helpers":86,"d3":16,"fast-isnumeric":18,"tinycolor2":34}],88:[function(_dereq_,module,exports){
  21694. /**
  21695. * Copyright 2012-2019, Plotly, Inc.
  21696. * All rights reserved.
  21697. *
  21698. * This source code is licensed under the MIT license found in the
  21699. * LICENSE file in the root directory of this source tree.
  21700. */
  21701. 'use strict';
  21702. var Lib = _dereq_('../../lib');
  21703. module.exports = function handleHoverLabelDefaults(contIn, contOut, coerce, opts) {
  21704. opts = opts || {};
  21705. coerce('hoverlabel.bgcolor', opts.bgcolor);
  21706. coerce('hoverlabel.bordercolor', opts.bordercolor);
  21707. coerce('hoverlabel.namelength', opts.namelength);
  21708. Lib.coerceFont(coerce, 'hoverlabel.font', opts.font);
  21709. };
  21710. },{"../../lib":168}],89:[function(_dereq_,module,exports){
  21711. /**
  21712. * Copyright 2012-2019, Plotly, Inc.
  21713. * All rights reserved.
  21714. *
  21715. * This source code is licensed under the MIT license found in the
  21716. * LICENSE file in the root directory of this source tree.
  21717. */
  21718. 'use strict';
  21719. module.exports = function(opts, extra) {
  21720. opts = opts || {};
  21721. extra = extra || {};
  21722. var descPart = extra.description ? ' ' + extra.description : '';
  21723. var keys = extra.keys || [];
  21724. if(keys.length > 0) {
  21725. var quotedKeys = [];
  21726. for(var i = 0; i < keys.length; i++) {
  21727. quotedKeys[i] = '`' + keys[i] + '`';
  21728. }
  21729. descPart = descPart + 'Finally, the template string has access to ';
  21730. if(keys.length === 1) {
  21731. descPart = 'variable ' + quotedKeys[0];
  21732. } else {
  21733. descPart = 'variables ' + quotedKeys.slice(0, -1).join(', ') + ' and ' + quotedKeys.slice(-1) + '.';
  21734. }
  21735. }
  21736. var hovertemplate = {
  21737. valType: 'string',
  21738. dflt: '',
  21739. arrayOk: true,
  21740. editType: 'none',
  21741. };
  21742. return hovertemplate;
  21743. };
  21744. },{}],90:[function(_dereq_,module,exports){
  21745. /**
  21746. * Copyright 2012-2019, Plotly, Inc.
  21747. * All rights reserved.
  21748. *
  21749. * This source code is licensed under the MIT license found in the
  21750. * LICENSE file in the root directory of this source tree.
  21751. */
  21752. 'use strict';
  21753. var d3 = _dereq_('d3');
  21754. var Lib = _dereq_('../../lib');
  21755. var dragElement = _dereq_('../dragelement');
  21756. var helpers = _dereq_('./helpers');
  21757. var layoutAttributes = _dereq_('./layout_attributes');
  21758. var hoverModule = _dereq_('./hover');
  21759. module.exports = {
  21760. moduleType: 'component',
  21761. name: 'fx',
  21762. constants: _dereq_('./constants'),
  21763. schema: {
  21764. layout: layoutAttributes
  21765. },
  21766. attributes: _dereq_('./attributes'),
  21767. layoutAttributes: layoutAttributes,
  21768. supplyLayoutGlobalDefaults: _dereq_('./layout_global_defaults'),
  21769. supplyDefaults: _dereq_('./defaults'),
  21770. supplyLayoutDefaults: _dereq_('./layout_defaults'),
  21771. calc: _dereq_('./calc'),
  21772. getDistanceFunction: helpers.getDistanceFunction,
  21773. getClosest: helpers.getClosest,
  21774. inbox: helpers.inbox,
  21775. quadrature: helpers.quadrature,
  21776. appendArrayPointValue: helpers.appendArrayPointValue,
  21777. castHoverOption: castHoverOption,
  21778. castHoverinfo: castHoverinfo,
  21779. hover: hoverModule.hover,
  21780. unhover: dragElement.unhover,
  21781. loneHover: hoverModule.loneHover,
  21782. multiHovers: hoverModule.multiHovers,
  21783. loneUnhover: loneUnhover,
  21784. click: _dereq_('./click')
  21785. };
  21786. function loneUnhover(containerOrSelection) {
  21787. // duck type whether the arg is a d3 selection because ie9 doesn't
  21788. // handle instanceof like modern browsers do.
  21789. var selection = Lib.isD3Selection(containerOrSelection) ?
  21790. containerOrSelection :
  21791. d3.select(containerOrSelection);
  21792. selection.selectAll('g.hovertext').remove();
  21793. selection.selectAll('.spikeline').remove();
  21794. }
  21795. // helpers for traces that use Fx.loneHover
  21796. function castHoverOption(trace, ptNumber, attr) {
  21797. return Lib.castOption(trace, ptNumber, 'hoverlabel.' + attr);
  21798. }
  21799. function castHoverinfo(trace, fullLayout, ptNumber) {
  21800. function _coerce(val) {
  21801. return Lib.coerceHoverinfo({hoverinfo: val}, {_module: trace._module}, fullLayout);
  21802. }
  21803. return Lib.castOption(trace, ptNumber, 'hoverinfo', _coerce);
  21804. }
  21805. },{"../../lib":168,"../dragelement":69,"./attributes":81,"./calc":82,"./click":83,"./constants":84,"./defaults":85,"./helpers":86,"./hover":87,"./layout_attributes":91,"./layout_defaults":92,"./layout_global_defaults":93,"d3":16}],91:[function(_dereq_,module,exports){
  21806. /**
  21807. * Copyright 2012-2019, Plotly, Inc.
  21808. * All rights reserved.
  21809. *
  21810. * This source code is licensed under the MIT license found in the
  21811. * LICENSE file in the root directory of this source tree.
  21812. */
  21813. 'use strict';
  21814. var constants = _dereq_('./constants');
  21815. var fontAttrs = _dereq_('../../plots/font_attributes')({
  21816. editType: 'none',
  21817. });
  21818. fontAttrs.family.dflt = constants.HOVERFONT;
  21819. fontAttrs.size.dflt = constants.HOVERFONTSIZE;
  21820. module.exports = {
  21821. clickmode: {
  21822. valType: 'flaglist',
  21823. flags: ['event', 'select'],
  21824. dflt: 'event',
  21825. editType: 'plot',
  21826. extras: ['none'],
  21827. },
  21828. dragmode: {
  21829. valType: 'enumerated',
  21830. values: ['zoom', 'pan', 'select', 'lasso', 'orbit', 'turntable', false],
  21831. dflt: 'zoom',
  21832. editType: 'modebar',
  21833. },
  21834. hovermode: {
  21835. valType: 'enumerated',
  21836. values: ['x', 'y', 'closest', false],
  21837. editType: 'modebar',
  21838. },
  21839. hoverdistance: {
  21840. valType: 'integer',
  21841. min: -1,
  21842. dflt: 20,
  21843. editType: 'none',
  21844. },
  21845. spikedistance: {
  21846. valType: 'integer',
  21847. min: -1,
  21848. dflt: 20,
  21849. editType: 'none',
  21850. },
  21851. hoverlabel: {
  21852. bgcolor: {
  21853. valType: 'color',
  21854. editType: 'none',
  21855. },
  21856. bordercolor: {
  21857. valType: 'color',
  21858. editType: 'none',
  21859. },
  21860. font: fontAttrs,
  21861. namelength: {
  21862. valType: 'integer',
  21863. min: -1,
  21864. dflt: 15,
  21865. editType: 'none',
  21866. },
  21867. editType: 'none'
  21868. },
  21869. selectdirection: {
  21870. valType: 'enumerated',
  21871. values: ['h', 'v', 'd', 'any'],
  21872. dflt: 'any',
  21873. editType: 'none'
  21874. }
  21875. };
  21876. },{"../../plots/font_attributes":239,"./constants":84}],92:[function(_dereq_,module,exports){
  21877. /**
  21878. * Copyright 2012-2019, Plotly, Inc.
  21879. * All rights reserved.
  21880. *
  21881. * This source code is licensed under the MIT license found in the
  21882. * LICENSE file in the root directory of this source tree.
  21883. */
  21884. 'use strict';
  21885. var Lib = _dereq_('../../lib');
  21886. var layoutAttributes = _dereq_('./layout_attributes');
  21887. module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
  21888. function coerce(attr, dflt) {
  21889. return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
  21890. }
  21891. var clickmode = coerce('clickmode');
  21892. var dragMode = coerce('dragmode');
  21893. if(dragMode === 'select') coerce('selectdirection');
  21894. var hovermodeDflt;
  21895. if(layoutOut._has('cartesian')) {
  21896. if(clickmode.indexOf('select') > -1) {
  21897. hovermodeDflt = 'closest';
  21898. } else {
  21899. // flag for 'horizontal' plots:
  21900. // determines the state of the mode bar 'compare' hovermode button
  21901. layoutOut._isHoriz = isHoriz(fullData);
  21902. hovermodeDflt = layoutOut._isHoriz ? 'y' : 'x';
  21903. }
  21904. }
  21905. else hovermodeDflt = 'closest';
  21906. var hoverMode = coerce('hovermode', hovermodeDflt);
  21907. if(hoverMode) {
  21908. coerce('hoverdistance');
  21909. coerce('spikedistance');
  21910. }
  21911. // if only mapbox or geo subplots is present on graph,
  21912. // reset 'zoom' dragmode to 'pan' until 'zoom' is implemented,
  21913. // so that the correct modebar button is active
  21914. var hasMapbox = layoutOut._has('mapbox');
  21915. var hasGeo = layoutOut._has('geo');
  21916. var len = layoutOut._basePlotModules.length;
  21917. if(layoutOut.dragmode === 'zoom' && (
  21918. ((hasMapbox || hasGeo) && len === 1) ||
  21919. (hasMapbox && hasGeo && len === 2)
  21920. )) {
  21921. layoutOut.dragmode = 'pan';
  21922. }
  21923. };
  21924. function isHoriz(fullData) {
  21925. var out = true;
  21926. for(var i = 0; i < fullData.length; i++) {
  21927. var trace = fullData[i];
  21928. if(trace.orientation !== 'h') {
  21929. out = false;
  21930. break;
  21931. }
  21932. }
  21933. return out;
  21934. }
  21935. },{"../../lib":168,"./layout_attributes":91}],93:[function(_dereq_,module,exports){
  21936. /**
  21937. * Copyright 2012-2019, Plotly, Inc.
  21938. * All rights reserved.
  21939. *
  21940. * This source code is licensed under the MIT license found in the
  21941. * LICENSE file in the root directory of this source tree.
  21942. */
  21943. 'use strict';
  21944. var Lib = _dereq_('../../lib');
  21945. var handleHoverLabelDefaults = _dereq_('./hoverlabel_defaults');
  21946. var layoutAttributes = _dereq_('./layout_attributes');
  21947. module.exports = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) {
  21948. function coerce(attr, dflt) {
  21949. return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
  21950. }
  21951. handleHoverLabelDefaults(layoutIn, layoutOut, coerce);
  21952. };
  21953. },{"../../lib":168,"./hoverlabel_defaults":88,"./layout_attributes":91}],94:[function(_dereq_,module,exports){
  21954. /**
  21955. * Copyright 2012-2019, Plotly, Inc.
  21956. * All rights reserved.
  21957. *
  21958. * This source code is licensed under the MIT license found in the
  21959. * LICENSE file in the root directory of this source tree.
  21960. */
  21961. 'use strict';
  21962. var Lib = _dereq_('../../lib');
  21963. var counterRegex = _dereq_('../../lib/regex').counter;
  21964. var domainAttrs = _dereq_('../../plots/domain').attributes;
  21965. var cartesianIdRegex = _dereq_('../../plots/cartesian/constants').idRegex;
  21966. var Template = _dereq_('../../plot_api/plot_template');
  21967. var gridAttrs = {
  21968. rows: {
  21969. valType: 'integer',
  21970. min: 1,
  21971. editType: 'plot',
  21972. },
  21973. roworder: {
  21974. valType: 'enumerated',
  21975. values: ['top to bottom', 'bottom to top'],
  21976. dflt: 'top to bottom',
  21977. editType: 'plot',
  21978. },
  21979. columns: {
  21980. valType: 'integer',
  21981. min: 1,
  21982. editType: 'plot',
  21983. },
  21984. subplots: {
  21985. valType: 'info_array',
  21986. freeLength: true,
  21987. dimensions: 2,
  21988. items: {valType: 'enumerated', values: [counterRegex('xy').toString(), ''], editType: 'plot'},
  21989. editType: 'plot',
  21990. },
  21991. xaxes: {
  21992. valType: 'info_array',
  21993. freeLength: true,
  21994. items: {valType: 'enumerated', values: [cartesianIdRegex.x.toString(), ''], editType: 'plot'},
  21995. editType: 'plot',
  21996. },
  21997. yaxes: {
  21998. valType: 'info_array',
  21999. freeLength: true,
  22000. items: {valType: 'enumerated', values: [cartesianIdRegex.y.toString(), ''], editType: 'plot'},
  22001. editType: 'plot',
  22002. },
  22003. pattern: {
  22004. valType: 'enumerated',
  22005. values: ['independent', 'coupled'],
  22006. dflt: 'coupled',
  22007. editType: 'plot',
  22008. },
  22009. xgap: {
  22010. valType: 'number',
  22011. min: 0,
  22012. max: 1,
  22013. editType: 'plot',
  22014. },
  22015. ygap: {
  22016. valType: 'number',
  22017. min: 0,
  22018. max: 1,
  22019. editType: 'plot',
  22020. },
  22021. domain: domainAttrs({name: 'grid', editType: 'plot', noGridCell: true}, {
  22022. }),
  22023. xside: {
  22024. valType: 'enumerated',
  22025. values: ['bottom', 'bottom plot', 'top plot', 'top'],
  22026. dflt: 'bottom plot',
  22027. editType: 'plot',
  22028. },
  22029. yside: {
  22030. valType: 'enumerated',
  22031. values: ['left', 'left plot', 'right plot', 'right'],
  22032. dflt: 'left plot',
  22033. editType: 'plot',
  22034. },
  22035. editType: 'plot'
  22036. };
  22037. function getAxes(layout, grid, axLetter) {
  22038. var gridVal = grid[axLetter + 'axes'];
  22039. var splomVal = Object.keys((layout._splomAxes || {})[axLetter] || {});
  22040. if(Array.isArray(gridVal)) return gridVal;
  22041. if(splomVal.length) return splomVal;
  22042. }
  22043. // the shape of the grid - this needs to be done BEFORE supplyDataDefaults
  22044. // so that non-subplot traces can place themselves in the grid
  22045. function sizeDefaults(layoutIn, layoutOut) {
  22046. var gridIn = layoutIn.grid || {};
  22047. var xAxes = getAxes(layoutOut, gridIn, 'x');
  22048. var yAxes = getAxes(layoutOut, gridIn, 'y');
  22049. if(!layoutIn.grid && !xAxes && !yAxes) return;
  22050. var hasSubplotGrid = Array.isArray(gridIn.subplots) && Array.isArray(gridIn.subplots[0]);
  22051. var hasXaxes = Array.isArray(xAxes);
  22052. var hasYaxes = Array.isArray(yAxes);
  22053. var isSplomGenerated = (
  22054. hasXaxes && xAxes !== gridIn.xaxes &&
  22055. hasYaxes && yAxes !== gridIn.yaxes
  22056. );
  22057. var dfltRows, dfltColumns;
  22058. if(hasSubplotGrid) {
  22059. dfltRows = gridIn.subplots.length;
  22060. dfltColumns = gridIn.subplots[0].length;
  22061. }
  22062. else {
  22063. if(hasYaxes) dfltRows = yAxes.length;
  22064. if(hasXaxes) dfltColumns = xAxes.length;
  22065. }
  22066. var gridOut = Template.newContainer(layoutOut, 'grid');
  22067. function coerce(attr, dflt) {
  22068. return Lib.coerce(gridIn, gridOut, gridAttrs, attr, dflt);
  22069. }
  22070. var rows = coerce('rows', dfltRows);
  22071. var columns = coerce('columns', dfltColumns);
  22072. if(!(rows * columns > 1)) {
  22073. delete layoutOut.grid;
  22074. return;
  22075. }
  22076. if(!hasSubplotGrid && !hasXaxes && !hasYaxes) {
  22077. var useDefaultSubplots = coerce('pattern') === 'independent';
  22078. if(useDefaultSubplots) hasSubplotGrid = true;
  22079. }
  22080. gridOut._hasSubplotGrid = hasSubplotGrid;
  22081. var rowOrder = coerce('roworder');
  22082. var reversed = rowOrder === 'top to bottom';
  22083. var dfltGapX = hasSubplotGrid ? 0.2 : 0.1;
  22084. var dfltGapY = hasSubplotGrid ? 0.3 : 0.1;
  22085. var dfltSideX, dfltSideY;
  22086. if(isSplomGenerated && layoutOut._splomGridDflt) {
  22087. dfltSideX = layoutOut._splomGridDflt.xside;
  22088. dfltSideY = layoutOut._splomGridDflt.yside;
  22089. }
  22090. gridOut._domains = {
  22091. x: fillGridPositions('x', coerce, dfltGapX, dfltSideX, columns),
  22092. y: fillGridPositions('y', coerce, dfltGapY, dfltSideY, rows, reversed)
  22093. };
  22094. }
  22095. // coerce x or y sizing attributes and return an array of domains for this direction
  22096. function fillGridPositions(axLetter, coerce, dfltGap, dfltSide, len, reversed) {
  22097. var dirGap = coerce(axLetter + 'gap', dfltGap);
  22098. var domain = coerce('domain.' + axLetter);
  22099. coerce(axLetter + 'side', dfltSide);
  22100. var out = new Array(len);
  22101. var start = domain[0];
  22102. var step = (domain[1] - start) / (len - dirGap);
  22103. var cellDomain = step * (1 - dirGap);
  22104. for(var i = 0; i < len; i++) {
  22105. var cellStart = start + step * i;
  22106. out[reversed ? (len - 1 - i) : i] = [cellStart, cellStart + cellDomain];
  22107. }
  22108. return out;
  22109. }
  22110. // the (cartesian) contents of the grid - this needs to happen AFTER supplyDataDefaults
  22111. // so that we know what cartesian subplots are available
  22112. function contentDefaults(layoutIn, layoutOut) {
  22113. var gridOut = layoutOut.grid;
  22114. // make sure we got to the end of handleGridSizing
  22115. if(!gridOut || !gridOut._domains) return;
  22116. var gridIn = layoutIn.grid || {};
  22117. var subplots = layoutOut._subplots;
  22118. var hasSubplotGrid = gridOut._hasSubplotGrid;
  22119. var rows = gridOut.rows;
  22120. var columns = gridOut.columns;
  22121. var useDefaultSubplots = gridOut.pattern === 'independent';
  22122. var i, j, xId, yId, subplotId, subplotsOut, yPos;
  22123. var axisMap = gridOut._axisMap = {};
  22124. if(hasSubplotGrid) {
  22125. var subplotsIn = gridIn.subplots || [];
  22126. subplotsOut = gridOut.subplots = new Array(rows);
  22127. var index = 1;
  22128. for(i = 0; i < rows; i++) {
  22129. var rowOut = subplotsOut[i] = new Array(columns);
  22130. var rowIn = subplotsIn[i] || [];
  22131. for(j = 0; j < columns; j++) {
  22132. if(useDefaultSubplots) {
  22133. subplotId = (index === 1) ? 'xy' : ('x' + index + 'y' + index);
  22134. index++;
  22135. }
  22136. else subplotId = rowIn[j];
  22137. rowOut[j] = '';
  22138. if(subplots.cartesian.indexOf(subplotId) !== -1) {
  22139. yPos = subplotId.indexOf('y');
  22140. xId = subplotId.slice(0, yPos);
  22141. yId = subplotId.slice(yPos);
  22142. if((axisMap[xId] !== undefined && axisMap[xId] !== j) ||
  22143. (axisMap[yId] !== undefined && axisMap[yId] !== i)
  22144. ) {
  22145. continue;
  22146. }
  22147. rowOut[j] = subplotId;
  22148. axisMap[xId] = j;
  22149. axisMap[yId] = i;
  22150. }
  22151. }
  22152. }
  22153. }
  22154. else {
  22155. var xAxes = getAxes(layoutOut, gridIn, 'x');
  22156. var yAxes = getAxes(layoutOut, gridIn, 'y');
  22157. gridOut.xaxes = fillGridAxes(xAxes, subplots.xaxis, columns, axisMap, 'x');
  22158. gridOut.yaxes = fillGridAxes(yAxes, subplots.yaxis, rows, axisMap, 'y');
  22159. }
  22160. var anchors = gridOut._anchors = {};
  22161. var reversed = gridOut.roworder === 'top to bottom';
  22162. for(var axisId in axisMap) {
  22163. var axLetter = axisId.charAt(0);
  22164. var side = gridOut[axLetter + 'side'];
  22165. var i0, inc, iFinal;
  22166. if(side.length < 8) {
  22167. // grid edge - ie not "* plot" - make these as free axes
  22168. // since we're not guaranteed to have a subplot there at all
  22169. anchors[axisId] = 'free';
  22170. }
  22171. else if(axLetter === 'x') {
  22172. if((side.charAt(0) === 't') === reversed) {
  22173. i0 = 0;
  22174. inc = 1;
  22175. iFinal = rows;
  22176. }
  22177. else {
  22178. i0 = rows - 1;
  22179. inc = -1;
  22180. iFinal = -1;
  22181. }
  22182. if(hasSubplotGrid) {
  22183. var column = axisMap[axisId];
  22184. for(i = i0; i !== iFinal; i += inc) {
  22185. subplotId = subplotsOut[i][column];
  22186. if(!subplotId) continue;
  22187. yPos = subplotId.indexOf('y');
  22188. if(subplotId.slice(0, yPos) === axisId) {
  22189. anchors[axisId] = subplotId.slice(yPos);
  22190. break;
  22191. }
  22192. }
  22193. }
  22194. else {
  22195. for(i = i0; i !== iFinal; i += inc) {
  22196. yId = gridOut.yaxes[i];
  22197. if(subplots.cartesian.indexOf(axisId + yId) !== -1) {
  22198. anchors[axisId] = yId;
  22199. break;
  22200. }
  22201. }
  22202. }
  22203. }
  22204. else {
  22205. if((side.charAt(0) === 'l')) {
  22206. i0 = 0;
  22207. inc = 1;
  22208. iFinal = columns;
  22209. }
  22210. else {
  22211. i0 = columns - 1;
  22212. inc = -1;
  22213. iFinal = -1;
  22214. }
  22215. if(hasSubplotGrid) {
  22216. var row = axisMap[axisId];
  22217. for(i = i0; i !== iFinal; i += inc) {
  22218. subplotId = subplotsOut[row][i];
  22219. if(!subplotId) continue;
  22220. yPos = subplotId.indexOf('y');
  22221. if(subplotId.slice(yPos) === axisId) {
  22222. anchors[axisId] = subplotId.slice(0, yPos);
  22223. break;
  22224. }
  22225. }
  22226. }
  22227. else {
  22228. for(i = i0; i !== iFinal; i += inc) {
  22229. xId = gridOut.xaxes[i];
  22230. if(subplots.cartesian.indexOf(xId + axisId) !== -1) {
  22231. anchors[axisId] = xId;
  22232. break;
  22233. }
  22234. }
  22235. }
  22236. }
  22237. }
  22238. }
  22239. function fillGridAxes(axesIn, axesAllowed, len, axisMap, axLetter) {
  22240. var out = new Array(len);
  22241. var i;
  22242. function fillOneAxis(i, axisId) {
  22243. if(axesAllowed.indexOf(axisId) !== -1 && axisMap[axisId] === undefined) {
  22244. out[i] = axisId;
  22245. axisMap[axisId] = i;
  22246. }
  22247. else out[i] = '';
  22248. }
  22249. if(Array.isArray(axesIn)) {
  22250. for(i = 0; i < len; i++) {
  22251. fillOneAxis(i, axesIn[i]);
  22252. }
  22253. }
  22254. else {
  22255. // default axis list is the first `len` axis ids
  22256. fillOneAxis(0, axLetter);
  22257. for(i = 1; i < len; i++) {
  22258. fillOneAxis(i, axLetter + (i + 1));
  22259. }
  22260. }
  22261. return out;
  22262. }
  22263. module.exports = {
  22264. moduleType: 'component',
  22265. name: 'grid',
  22266. schema: {
  22267. layout: {grid: gridAttrs}
  22268. },
  22269. layoutAttributes: gridAttrs,
  22270. sizeDefaults: sizeDefaults,
  22271. contentDefaults: contentDefaults
  22272. };
  22273. },{"../../lib":168,"../../lib/regex":183,"../../plot_api/plot_template":202,"../../plots/cartesian/constants":218,"../../plots/domain":238}],95:[function(_dereq_,module,exports){
  22274. /**
  22275. * Copyright 2012-2019, Plotly, Inc.
  22276. * All rights reserved.
  22277. *
  22278. * This source code is licensed under the MIT license found in the
  22279. * LICENSE file in the root directory of this source tree.
  22280. */
  22281. 'use strict';
  22282. var cartesianConstants = _dereq_('../../plots/cartesian/constants');
  22283. var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;
  22284. module.exports = templatedArray('image', {
  22285. visible: {
  22286. valType: 'boolean',
  22287. dflt: true,
  22288. editType: 'arraydraw',
  22289. },
  22290. source: {
  22291. valType: 'string',
  22292. editType: 'arraydraw',
  22293. },
  22294. layer: {
  22295. valType: 'enumerated',
  22296. values: ['below', 'above'],
  22297. dflt: 'above',
  22298. editType: 'arraydraw',
  22299. },
  22300. sizex: {
  22301. valType: 'number',
  22302. dflt: 0,
  22303. editType: 'arraydraw',
  22304. },
  22305. sizey: {
  22306. valType: 'number',
  22307. dflt: 0,
  22308. editType: 'arraydraw',
  22309. },
  22310. sizing: {
  22311. valType: 'enumerated',
  22312. values: ['fill', 'contain', 'stretch'],
  22313. dflt: 'contain',
  22314. editType: 'arraydraw',
  22315. },
  22316. opacity: {
  22317. valType: 'number',
  22318. min: 0,
  22319. max: 1,
  22320. dflt: 1,
  22321. editType: 'arraydraw',
  22322. },
  22323. x: {
  22324. valType: 'any',
  22325. dflt: 0,
  22326. editType: 'arraydraw',
  22327. },
  22328. y: {
  22329. valType: 'any',
  22330. dflt: 0,
  22331. editType: 'arraydraw',
  22332. },
  22333. xanchor: {
  22334. valType: 'enumerated',
  22335. values: ['left', 'center', 'right'],
  22336. dflt: 'left',
  22337. editType: 'arraydraw',
  22338. },
  22339. yanchor: {
  22340. valType: 'enumerated',
  22341. values: ['top', 'middle', 'bottom'],
  22342. dflt: 'top',
  22343. editType: 'arraydraw',
  22344. },
  22345. xref: {
  22346. valType: 'enumerated',
  22347. values: [
  22348. 'paper',
  22349. cartesianConstants.idRegex.x.toString()
  22350. ],
  22351. dflt: 'paper',
  22352. editType: 'arraydraw',
  22353. },
  22354. yref: {
  22355. valType: 'enumerated',
  22356. values: [
  22357. 'paper',
  22358. cartesianConstants.idRegex.y.toString()
  22359. ],
  22360. dflt: 'paper',
  22361. editType: 'arraydraw',
  22362. },
  22363. editType: 'arraydraw'
  22364. });
  22365. },{"../../plot_api/plot_template":202,"../../plots/cartesian/constants":218}],96:[function(_dereq_,module,exports){
  22366. /**
  22367. * Copyright 2012-2019, Plotly, Inc.
  22368. * All rights reserved.
  22369. *
  22370. * This source code is licensed under the MIT license found in the
  22371. * LICENSE file in the root directory of this source tree.
  22372. */
  22373. 'use strict';
  22374. var isNumeric = _dereq_('fast-isnumeric');
  22375. var toLogRange = _dereq_('../../lib/to_log_range');
  22376. /*
  22377. * convertCoords: when converting an axis between log and linear
  22378. * you need to alter any images on that axis to keep them
  22379. * pointing at the same data point.
  22380. * In v2.0 this will become obsolete (or perhaps size will still need conversion?)
  22381. * we convert size by declaring that the maximum extent *in data units* should be
  22382. * the same, assuming the image is anchored by its center (could remove that restriction
  22383. * if we think it's important) even though the actual left and right values will not be
  22384. * quite the same since the scale becomes nonlinear (and central anchor means the pixel
  22385. * center of the image, not the data units center)
  22386. *
  22387. * gd: the plot div
  22388. * ax: the axis being changed
  22389. * newType: the type it's getting
  22390. * doExtra: function(attr, val) from inside relayout that sets the attribute.
  22391. * Use this to make the changes as it's aware if any other changes in the
  22392. * same relayout call should override this conversion.
  22393. */
  22394. module.exports = function convertCoords(gd, ax, newType, doExtra) {
  22395. ax = ax || {};
  22396. var toLog = (newType === 'log') && (ax.type === 'linear');
  22397. var fromLog = (newType === 'linear') && (ax.type === 'log');
  22398. if(!(toLog || fromLog)) return;
  22399. var images = gd._fullLayout.images;
  22400. var axLetter = ax._id.charAt(0);
  22401. var image;
  22402. var attrPrefix;
  22403. for(var i = 0; i < images.length; i++) {
  22404. image = images[i];
  22405. attrPrefix = 'images[' + i + '].';
  22406. if(image[axLetter + 'ref'] === ax._id) {
  22407. var currentPos = image[axLetter];
  22408. var currentSize = image['size' + axLetter];
  22409. var newPos = null;
  22410. var newSize = null;
  22411. if(toLog) {
  22412. newPos = toLogRange(currentPos, ax.range);
  22413. // this is the inverse of the conversion we do in fromLog below
  22414. // so that the conversion is reversible (notice the fromLog conversion
  22415. // is like sinh, and this one looks like arcsinh)
  22416. var dx = currentSize / Math.pow(10, newPos) / 2;
  22417. newSize = 2 * Math.log(dx + Math.sqrt(1 + dx * dx)) / Math.LN10;
  22418. }
  22419. else {
  22420. newPos = Math.pow(10, currentPos);
  22421. newSize = newPos * (Math.pow(10, currentSize / 2) - Math.pow(10, -currentSize / 2));
  22422. }
  22423. // if conversion failed, delete the value so it can get a default later on
  22424. if(!isNumeric(newPos)) {
  22425. newPos = null;
  22426. newSize = null;
  22427. }
  22428. else if(!isNumeric(newSize)) newSize = null;
  22429. doExtra(attrPrefix + axLetter, newPos);
  22430. doExtra(attrPrefix + 'size' + axLetter, newSize);
  22431. }
  22432. }
  22433. };
  22434. },{"../../lib/to_log_range":191,"fast-isnumeric":18}],97:[function(_dereq_,module,exports){
  22435. /**
  22436. * Copyright 2012-2019, Plotly, Inc.
  22437. * All rights reserved.
  22438. *
  22439. * This source code is licensed under the MIT license found in the
  22440. * LICENSE file in the root directory of this source tree.
  22441. */
  22442. 'use strict';
  22443. var Lib = _dereq_('../../lib');
  22444. var Axes = _dereq_('../../plots/cartesian/axes');
  22445. var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');
  22446. var attributes = _dereq_('./attributes');
  22447. var name = 'images';
  22448. module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
  22449. var opts = {
  22450. name: name,
  22451. handleItemDefaults: imageDefaults
  22452. };
  22453. handleArrayContainerDefaults(layoutIn, layoutOut, opts);
  22454. };
  22455. function imageDefaults(imageIn, imageOut, fullLayout) {
  22456. function coerce(attr, dflt) {
  22457. return Lib.coerce(imageIn, imageOut, attributes, attr, dflt);
  22458. }
  22459. var source = coerce('source');
  22460. var visible = coerce('visible', !!source);
  22461. if(!visible) return imageOut;
  22462. coerce('layer');
  22463. coerce('xanchor');
  22464. coerce('yanchor');
  22465. coerce('sizex');
  22466. coerce('sizey');
  22467. coerce('sizing');
  22468. coerce('opacity');
  22469. var gdMock = { _fullLayout: fullLayout };
  22470. var axLetters = ['x', 'y'];
  22471. for(var i = 0; i < 2; i++) {
  22472. // 'paper' is the fallback axref
  22473. var axLetter = axLetters[i];
  22474. var axRef = Axes.coerceRef(imageIn, imageOut, gdMock, axLetter, 'paper');
  22475. if(axRef !== 'paper') {
  22476. var ax = Axes.getFromId(gdMock, axRef);
  22477. ax._imgIndices.push(imageOut._index);
  22478. }
  22479. Axes.coercePosition(imageOut, gdMock, coerce, axRef, axLetter, 0);
  22480. }
  22481. return imageOut;
  22482. }
  22483. },{"../../lib":168,"../../plots/array_container_defaults":208,"../../plots/cartesian/axes":212,"./attributes":95}],98:[function(_dereq_,module,exports){
  22484. /**
  22485. * Copyright 2012-2019, Plotly, Inc.
  22486. * All rights reserved.
  22487. *
  22488. * This source code is licensed under the MIT license found in the
  22489. * LICENSE file in the root directory of this source tree.
  22490. */
  22491. 'use strict';
  22492. var d3 = _dereq_('d3');
  22493. var Drawing = _dereq_('../drawing');
  22494. var Axes = _dereq_('../../plots/cartesian/axes');
  22495. var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');
  22496. module.exports = function draw(gd) {
  22497. var fullLayout = gd._fullLayout;
  22498. var imageDataAbove = [];
  22499. var imageDataSubplot = {};
  22500. var imageDataBelow = [];
  22501. var subplot;
  22502. var i;
  22503. // Sort into top, subplot, and bottom layers
  22504. for(i = 0; i < fullLayout.images.length; i++) {
  22505. var img = fullLayout.images[i];
  22506. if(img.visible) {
  22507. if(img.layer === 'below' && img.xref !== 'paper' && img.yref !== 'paper') {
  22508. subplot = img.xref + img.yref;
  22509. var plotinfo = fullLayout._plots[subplot];
  22510. if(!plotinfo) {
  22511. // Fall back to _imageLowerLayer in case the requested subplot doesn't exist.
  22512. // This can happen if you reference the image to an x / y axis combination
  22513. // that doesn't have any data on it (and layer is below)
  22514. imageDataBelow.push(img);
  22515. continue;
  22516. }
  22517. if(plotinfo.mainplot) {
  22518. subplot = plotinfo.mainplot.id;
  22519. }
  22520. if(!imageDataSubplot[subplot]) {
  22521. imageDataSubplot[subplot] = [];
  22522. }
  22523. imageDataSubplot[subplot].push(img);
  22524. } else if(img.layer === 'above') {
  22525. imageDataAbove.push(img);
  22526. } else {
  22527. imageDataBelow.push(img);
  22528. }
  22529. }
  22530. }
  22531. var anchors = {
  22532. x: {
  22533. left: { sizing: 'xMin', offset: 0 },
  22534. center: { sizing: 'xMid', offset: -1 / 2 },
  22535. right: { sizing: 'xMax', offset: -1 }
  22536. },
  22537. y: {
  22538. top: { sizing: 'YMin', offset: 0 },
  22539. middle: { sizing: 'YMid', offset: -1 / 2 },
  22540. bottom: { sizing: 'YMax', offset: -1 }
  22541. }
  22542. };
  22543. // Images must be converted to dataURL's for exporting.
  22544. function setImage(d) {
  22545. var thisImage = d3.select(this);
  22546. if(this.img && this.img.src === d.source) {
  22547. return;
  22548. }
  22549. thisImage.attr('xmlns', xmlnsNamespaces.svg);
  22550. var imagePromise = new Promise(function(resolve) {
  22551. var img = new Image();
  22552. this.img = img;
  22553. // If not set, a `tainted canvas` error is thrown
  22554. img.setAttribute('crossOrigin', 'anonymous');
  22555. img.onerror = errorHandler;
  22556. img.onload = function() {
  22557. var canvas = document.createElement('canvas');
  22558. canvas.width = this.width;
  22559. canvas.height = this.height;
  22560. var ctx = canvas.getContext('2d');
  22561. ctx.drawImage(this, 0, 0);
  22562. var dataURL = canvas.toDataURL('image/png');
  22563. thisImage.attr('xlink:href', dataURL);
  22564. // resolve promise in onload handler instead of on 'load' to support IE11
  22565. // see https://github.com/plotly/plotly.js/issues/1685
  22566. // for more details
  22567. resolve();
  22568. };
  22569. thisImage.on('error', errorHandler);
  22570. img.src = d.source;
  22571. function errorHandler() {
  22572. thisImage.remove();
  22573. resolve();
  22574. }
  22575. }.bind(this));
  22576. gd._promises.push(imagePromise);
  22577. }
  22578. function applyAttributes(d) {
  22579. var thisImage = d3.select(this);
  22580. // Axes if specified
  22581. var xa = Axes.getFromId(gd, d.xref);
  22582. var ya = Axes.getFromId(gd, d.yref);
  22583. var size = fullLayout._size;
  22584. var width = xa ? Math.abs(xa.l2p(d.sizex) - xa.l2p(0)) : d.sizex * size.w;
  22585. var height = ya ? Math.abs(ya.l2p(d.sizey) - ya.l2p(0)) : d.sizey * size.h;
  22586. // Offsets for anchor positioning
  22587. var xOffset = width * anchors.x[d.xanchor].offset;
  22588. var yOffset = height * anchors.y[d.yanchor].offset;
  22589. var sizing = anchors.x[d.xanchor].sizing + anchors.y[d.yanchor].sizing;
  22590. // Final positions
  22591. var xPos = (xa ? xa.r2p(d.x) + xa._offset : d.x * size.w + size.l) + xOffset;
  22592. var yPos = (ya ? ya.r2p(d.y) + ya._offset : size.h - d.y * size.h + size.t) + yOffset;
  22593. // Construct the proper aspectRatio attribute
  22594. switch(d.sizing) {
  22595. case 'fill':
  22596. sizing += ' slice';
  22597. break;
  22598. case 'stretch':
  22599. sizing = 'none';
  22600. break;
  22601. }
  22602. thisImage.attr({
  22603. x: xPos,
  22604. y: yPos,
  22605. width: width,
  22606. height: height,
  22607. preserveAspectRatio: sizing,
  22608. opacity: d.opacity
  22609. });
  22610. // Set proper clipping on images
  22611. var xId = xa ? xa._id : '';
  22612. var yId = ya ? ya._id : '';
  22613. var clipAxes = xId + yId;
  22614. Drawing.setClipUrl(
  22615. thisImage,
  22616. clipAxes ? ('clip' + fullLayout._uid + clipAxes) : null,
  22617. gd
  22618. );
  22619. }
  22620. var imagesBelow = fullLayout._imageLowerLayer.selectAll('image')
  22621. .data(imageDataBelow);
  22622. var imagesAbove = fullLayout._imageUpperLayer.selectAll('image')
  22623. .data(imageDataAbove);
  22624. imagesBelow.enter().append('image');
  22625. imagesAbove.enter().append('image');
  22626. imagesBelow.exit().remove();
  22627. imagesAbove.exit().remove();
  22628. imagesBelow.each(function(d) {
  22629. setImage.bind(this)(d);
  22630. applyAttributes.bind(this)(d);
  22631. });
  22632. imagesAbove.each(function(d) {
  22633. setImage.bind(this)(d);
  22634. applyAttributes.bind(this)(d);
  22635. });
  22636. var allSubplots = Object.keys(fullLayout._plots);
  22637. for(i = 0; i < allSubplots.length; i++) {
  22638. subplot = allSubplots[i];
  22639. var subplotObj = fullLayout._plots[subplot];
  22640. // filter out overlaid plots (which havd their images on the main plot)
  22641. // and gl2d plots (which don't support below images, at least not yet)
  22642. if(!subplotObj.imagelayer) continue;
  22643. var imagesOnSubplot = subplotObj.imagelayer.selectAll('image')
  22644. // even if there are no images on this subplot, we need to run
  22645. // enter and exit in case there were previously
  22646. .data(imageDataSubplot[subplot] || []);
  22647. imagesOnSubplot.enter().append('image');
  22648. imagesOnSubplot.exit().remove();
  22649. imagesOnSubplot.each(function(d) {
  22650. setImage.bind(this)(d);
  22651. applyAttributes.bind(this)(d);
  22652. });
  22653. }
  22654. };
  22655. },{"../../constants/xmlns_namespaces":150,"../../plots/cartesian/axes":212,"../drawing":72,"d3":16}],99:[function(_dereq_,module,exports){
  22656. /**
  22657. * Copyright 2012-2019, Plotly, Inc.
  22658. * All rights reserved.
  22659. *
  22660. * This source code is licensed under the MIT license found in the
  22661. * LICENSE file in the root directory of this source tree.
  22662. */
  22663. 'use strict';
  22664. module.exports = {
  22665. moduleType: 'component',
  22666. name: 'images',
  22667. layoutAttributes: _dereq_('./attributes'),
  22668. supplyLayoutDefaults: _dereq_('./defaults'),
  22669. includeBasePlot: _dereq_('../../plots/cartesian/include_components')('images'),
  22670. draw: _dereq_('./draw'),
  22671. convertCoords: _dereq_('./convert_coords')
  22672. };
  22673. },{"../../plots/cartesian/include_components":223,"./attributes":95,"./convert_coords":96,"./defaults":97,"./draw":98}],100:[function(_dereq_,module,exports){
  22674. /**
  22675. * Copyright 2012-2019, Plotly, Inc.
  22676. * All rights reserved.
  22677. *
  22678. * This source code is licensed under the MIT license found in the
  22679. * LICENSE file in the root directory of this source tree.
  22680. */
  22681. 'use strict';
  22682. var fontAttrs = _dereq_('../../plots/font_attributes');
  22683. var colorAttrs = _dereq_('../color/attributes');
  22684. module.exports = {
  22685. bgcolor: {
  22686. valType: 'color',
  22687. editType: 'legend',
  22688. },
  22689. bordercolor: {
  22690. valType: 'color',
  22691. dflt: colorAttrs.defaultLine,
  22692. editType: 'legend',
  22693. },
  22694. borderwidth: {
  22695. valType: 'number',
  22696. min: 0,
  22697. dflt: 0,
  22698. editType: 'legend',
  22699. },
  22700. font: fontAttrs({
  22701. editType: 'legend',
  22702. }),
  22703. orientation: {
  22704. valType: 'enumerated',
  22705. values: ['v', 'h'],
  22706. dflt: 'v',
  22707. editType: 'legend',
  22708. },
  22709. traceorder: {
  22710. valType: 'flaglist',
  22711. flags: ['reversed', 'grouped'],
  22712. extras: ['normal'],
  22713. editType: 'legend',
  22714. },
  22715. tracegroupgap: {
  22716. valType: 'number',
  22717. min: 0,
  22718. dflt: 10,
  22719. editType: 'legend',
  22720. },
  22721. x: {
  22722. valType: 'number',
  22723. min: -2,
  22724. max: 3,
  22725. dflt: 1.02,
  22726. editType: 'legend',
  22727. },
  22728. xanchor: {
  22729. valType: 'enumerated',
  22730. values: ['auto', 'left', 'center', 'right'],
  22731. dflt: 'left',
  22732. editType: 'legend',
  22733. },
  22734. y: {
  22735. valType: 'number',
  22736. min: -2,
  22737. max: 3,
  22738. dflt: 1,
  22739. editType: 'legend',
  22740. },
  22741. yanchor: {
  22742. valType: 'enumerated',
  22743. values: ['auto', 'top', 'middle', 'bottom'],
  22744. dflt: 'auto',
  22745. editType: 'legend',
  22746. },
  22747. uirevision: {
  22748. valType: 'any',
  22749. editType: 'none',
  22750. },
  22751. valign: {
  22752. valType: 'enumerated',
  22753. values: ['top', 'middle', 'bottom'],
  22754. dflt: 'middle',
  22755. editType: 'legend',
  22756. },
  22757. editType: 'legend'
  22758. };
  22759. },{"../../plots/font_attributes":239,"../color/attributes":50}],101:[function(_dereq_,module,exports){
  22760. /**
  22761. * Copyright 2012-2019, Plotly, Inc.
  22762. * All rights reserved.
  22763. *
  22764. * This source code is licensed under the MIT license found in the
  22765. * LICENSE file in the root directory of this source tree.
  22766. */
  22767. 'use strict';
  22768. module.exports = {
  22769. scrollBarWidth: 6,
  22770. scrollBarMinHeight: 20,
  22771. scrollBarColor: '#808BA4',
  22772. scrollBarMargin: 4,
  22773. textOffsetX: 40
  22774. };
  22775. },{}],102:[function(_dereq_,module,exports){
  22776. /**
  22777. * Copyright 2012-2019, Plotly, Inc.
  22778. * All rights reserved.
  22779. *
  22780. * This source code is licensed under the MIT license found in the
  22781. * LICENSE file in the root directory of this source tree.
  22782. */
  22783. 'use strict';
  22784. var Registry = _dereq_('../../registry');
  22785. var Lib = _dereq_('../../lib');
  22786. var Template = _dereq_('../../plot_api/plot_template');
  22787. var attributes = _dereq_('./attributes');
  22788. var basePlotLayoutAttributes = _dereq_('../../plots/layout_attributes');
  22789. var helpers = _dereq_('./helpers');
  22790. module.exports = function legendDefaults(layoutIn, layoutOut, fullData) {
  22791. var containerIn = layoutIn.legend || {};
  22792. var legendTraceCount = 0;
  22793. var legendReallyHasATrace = false;
  22794. var defaultOrder = 'normal';
  22795. var defaultX, defaultY, defaultXAnchor, defaultYAnchor;
  22796. for(var i = 0; i < fullData.length; i++) {
  22797. var trace = fullData[i];
  22798. if(!trace.visible) continue;
  22799. // Note that we explicitly count any trace that is either shown or
  22800. // *would* be shown by default, toward the two traces you need to
  22801. // ensure the legend is shown by default, because this can still help
  22802. // disambiguate.
  22803. if(trace.showlegend || trace._dfltShowLegend) {
  22804. legendTraceCount++;
  22805. if(trace.showlegend) {
  22806. legendReallyHasATrace = true;
  22807. // Always show the legend by default if there's a pie,
  22808. // or if there's only one trace but it's explicitly shown
  22809. if(Registry.traceIs(trace, 'pie') ||
  22810. trace._input.showlegend === true
  22811. ) {
  22812. legendTraceCount++;
  22813. }
  22814. }
  22815. }
  22816. if((Registry.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') ||
  22817. ['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) {
  22818. defaultOrder = helpers.isGrouped({traceorder: defaultOrder}) ?
  22819. 'grouped+reversed' : 'reversed';
  22820. }
  22821. if(trace.legendgroup !== undefined && trace.legendgroup !== '') {
  22822. defaultOrder = helpers.isReversed({traceorder: defaultOrder}) ?
  22823. 'reversed+grouped' : 'grouped';
  22824. }
  22825. }
  22826. var showLegend = Lib.coerce(layoutIn, layoutOut,
  22827. basePlotLayoutAttributes, 'showlegend',
  22828. legendReallyHasATrace && legendTraceCount > 1);
  22829. if(showLegend === false && !containerIn.uirevision) return;
  22830. var containerOut = Template.newContainer(layoutOut, 'legend');
  22831. function coerce(attr, dflt) {
  22832. return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
  22833. }
  22834. coerce('uirevision', layoutOut.uirevision);
  22835. if(showLegend === false) return;
  22836. coerce('bgcolor', layoutOut.paper_bgcolor);
  22837. coerce('bordercolor');
  22838. coerce('borderwidth');
  22839. Lib.coerceFont(coerce, 'font', layoutOut.font);
  22840. coerce('orientation');
  22841. if(containerOut.orientation === 'h') {
  22842. var xaxis = layoutIn.xaxis;
  22843. if(Registry.getComponentMethod('rangeslider', 'isVisible')(xaxis)) {
  22844. defaultX = 0;
  22845. defaultXAnchor = 'left';
  22846. defaultY = 1.1;
  22847. defaultYAnchor = 'bottom';
  22848. }
  22849. else {
  22850. defaultX = 0;
  22851. defaultXAnchor = 'left';
  22852. defaultY = -0.1;
  22853. defaultYAnchor = 'top';
  22854. }
  22855. }
  22856. coerce('traceorder', defaultOrder);
  22857. if(helpers.isGrouped(layoutOut.legend)) coerce('tracegroupgap');
  22858. coerce('x', defaultX);
  22859. coerce('xanchor', defaultXAnchor);
  22860. coerce('y', defaultY);
  22861. coerce('yanchor', defaultYAnchor);
  22862. coerce('valign');
  22863. Lib.noneOrAll(containerIn, containerOut, ['x', 'y']);
  22864. };
  22865. },{"../../lib":168,"../../plot_api/plot_template":202,"../../plots/layout_attributes":243,"../../registry":257,"./attributes":100,"./helpers":106}],103:[function(_dereq_,module,exports){
  22866. /**
  22867. * Copyright 2012-2019, Plotly, Inc.
  22868. * All rights reserved.
  22869. *
  22870. * This source code is licensed under the MIT license found in the
  22871. * LICENSE file in the root directory of this source tree.
  22872. */
  22873. 'use strict';
  22874. var d3 = _dereq_('d3');
  22875. var Lib = _dereq_('../../lib');
  22876. var Plots = _dereq_('../../plots/plots');
  22877. var Registry = _dereq_('../../registry');
  22878. var Events = _dereq_('../../lib/events');
  22879. var dragElement = _dereq_('../dragelement');
  22880. var Drawing = _dereq_('../drawing');
  22881. var Color = _dereq_('../color');
  22882. var svgTextUtils = _dereq_('../../lib/svg_text_utils');
  22883. var handleClick = _dereq_('./handle_click');
  22884. var constants = _dereq_('./constants');
  22885. var interactConstants = _dereq_('../../constants/interactions');
  22886. var alignmentConstants = _dereq_('../../constants/alignment');
  22887. var LINE_SPACING = alignmentConstants.LINE_SPACING;
  22888. var FROM_TL = alignmentConstants.FROM_TL;
  22889. var FROM_BR = alignmentConstants.FROM_BR;
  22890. var getLegendData = _dereq_('./get_legend_data');
  22891. var style = _dereq_('./style');
  22892. var helpers = _dereq_('./helpers');
  22893. var DBLCLICKDELAY = interactConstants.DBLCLICKDELAY;
  22894. module.exports = function draw(gd) {
  22895. var fullLayout = gd._fullLayout;
  22896. var clipId = 'legend' + fullLayout._uid;
  22897. if(!fullLayout._infolayer || !gd.calcdata) return;
  22898. if(!gd._legendMouseDownTime) gd._legendMouseDownTime = 0;
  22899. var opts = fullLayout.legend;
  22900. var legendData = fullLayout.showlegend && getLegendData(gd.calcdata, opts);
  22901. var hiddenSlices = fullLayout.hiddenlabels || [];
  22902. if(!fullLayout.showlegend || !legendData.length) {
  22903. fullLayout._infolayer.selectAll('.legend').remove();
  22904. fullLayout._topdefs.select('#' + clipId).remove();
  22905. Plots.autoMargin(gd, 'legend');
  22906. return;
  22907. }
  22908. var maxLength = 0;
  22909. for(var i = 0; i < legendData.length; i++) {
  22910. for(var j = 0; j < legendData[i].length; j++) {
  22911. var item = legendData[i][j][0];
  22912. var trace = item.trace;
  22913. var isPie = Registry.traceIs(trace, 'pie');
  22914. var name = isPie ? item.label : trace.name;
  22915. maxLength = Math.max(maxLength, name && name.length || 0);
  22916. }
  22917. }
  22918. var firstRender = false;
  22919. var legend = Lib.ensureSingle(fullLayout._infolayer, 'g', 'legend', function(s) {
  22920. s.attr('pointer-events', 'all');
  22921. firstRender = true;
  22922. });
  22923. var clipPath = Lib.ensureSingleById(fullLayout._topdefs, 'clipPath', clipId, function(s) {
  22924. s.append('rect');
  22925. });
  22926. var bg = Lib.ensureSingle(legend, 'rect', 'bg', function(s) {
  22927. s.attr('shape-rendering', 'crispEdges');
  22928. });
  22929. bg.call(Color.stroke, opts.bordercolor)
  22930. .call(Color.fill, opts.bgcolor)
  22931. .style('stroke-width', opts.borderwidth + 'px');
  22932. var scrollBox = Lib.ensureSingle(legend, 'g', 'scrollbox');
  22933. var scrollBar = Lib.ensureSingle(legend, 'rect', 'scrollbar', function(s) {
  22934. s.attr({
  22935. rx: 20,
  22936. ry: 3,
  22937. width: 0,
  22938. height: 0
  22939. })
  22940. .call(Color.fill, '#808BA4');
  22941. });
  22942. var groups = scrollBox.selectAll('g.groups')
  22943. .data(legendData);
  22944. groups.enter().append('g')
  22945. .attr('class', 'groups');
  22946. groups.exit().remove();
  22947. var traces = groups.selectAll('g.traces')
  22948. .data(Lib.identity);
  22949. traces.enter().append('g').attr('class', 'traces');
  22950. traces.exit().remove();
  22951. traces.style('opacity', function(d) {
  22952. var trace = d[0].trace;
  22953. if(Registry.traceIs(trace, 'pie')) {
  22954. return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1;
  22955. } else {
  22956. return trace.visible === 'legendonly' ? 0.5 : 1;
  22957. }
  22958. })
  22959. .each(function() {
  22960. d3.select(this)
  22961. .call(drawTexts, gd, maxLength)
  22962. .call(setupTraceToggle, gd);
  22963. })
  22964. .call(style, gd);
  22965. Lib.syncOrAsync([Plots.previousPromises,
  22966. function() {
  22967. if(firstRender) {
  22968. computeLegendDimensions(gd, groups, traces);
  22969. expandMargin(gd);
  22970. }
  22971. // Position and size the legend
  22972. var lxMin = 0;
  22973. var lxMax = fullLayout.width;
  22974. var lyMin = 0;
  22975. var lyMax = fullLayout.height;
  22976. computeLegendDimensions(gd, groups, traces);
  22977. if(opts._height > lyMax) {
  22978. // If the legend doesn't fit in the plot area,
  22979. // do not expand the vertical margins.
  22980. expandHorizontalMargin(gd);
  22981. } else {
  22982. expandMargin(gd);
  22983. }
  22984. // Scroll section must be executed after repositionLegend.
  22985. // It requires the legend width, height, x and y to position the scrollbox
  22986. // and these values are mutated in repositionLegend.
  22987. var gs = fullLayout._size;
  22988. var lx = gs.l + gs.w * opts.x;
  22989. var ly = gs.t + gs.h * (1 - opts.y);
  22990. if(Lib.isRightAnchor(opts)) {
  22991. lx -= opts._width;
  22992. }
  22993. else if(Lib.isCenterAnchor(opts)) {
  22994. lx -= opts._width / 2;
  22995. }
  22996. if(Lib.isBottomAnchor(opts)) {
  22997. ly -= opts._height;
  22998. }
  22999. else if(Lib.isMiddleAnchor(opts)) {
  23000. ly -= opts._height / 2;
  23001. }
  23002. // Make sure the legend left and right sides are visible
  23003. var legendWidth = opts._width;
  23004. var legendWidthMax = gs.w;
  23005. if(legendWidth > legendWidthMax) {
  23006. lx = gs.l;
  23007. legendWidth = legendWidthMax;
  23008. }
  23009. else {
  23010. if(lx + legendWidth > lxMax) lx = lxMax - legendWidth;
  23011. if(lx < lxMin) lx = lxMin;
  23012. legendWidth = Math.min(lxMax - lx, opts._width);
  23013. }
  23014. // Make sure the legend top and bottom are visible
  23015. // (legends with a scroll bar are not allowed to stretch beyond the extended
  23016. // margins)
  23017. var legendHeight = opts._height;
  23018. var legendHeightMax = gs.h;
  23019. if(legendHeight > legendHeightMax) {
  23020. ly = gs.t;
  23021. legendHeight = legendHeightMax;
  23022. }
  23023. else {
  23024. if(ly + legendHeight > lyMax) ly = lyMax - legendHeight;
  23025. if(ly < lyMin) ly = lyMin;
  23026. legendHeight = Math.min(lyMax - ly, opts._height);
  23027. }
  23028. // Set size and position of all the elements that make up a legend:
  23029. // legend, background and border, scroll box and scroll bar
  23030. Drawing.setTranslate(legend, lx, ly);
  23031. // to be safe, remove previous listeners
  23032. scrollBar.on('.drag', null);
  23033. legend.on('wheel', null);
  23034. if(opts._height <= legendHeight || gd._context.staticPlot) {
  23035. // if scrollbar should not be shown.
  23036. bg.attr({
  23037. width: legendWidth - opts.borderwidth,
  23038. height: legendHeight - opts.borderwidth,
  23039. x: opts.borderwidth / 2,
  23040. y: opts.borderwidth / 2
  23041. });
  23042. Drawing.setTranslate(scrollBox, 0, 0);
  23043. clipPath.select('rect').attr({
  23044. width: legendWidth - 2 * opts.borderwidth,
  23045. height: legendHeight - 2 * opts.borderwidth,
  23046. x: opts.borderwidth,
  23047. y: opts.borderwidth
  23048. });
  23049. Drawing.setClipUrl(scrollBox, clipId, gd);
  23050. Drawing.setRect(scrollBar, 0, 0, 0, 0);
  23051. delete opts._scrollY;
  23052. }
  23053. else {
  23054. var scrollBarHeight = Math.max(constants.scrollBarMinHeight,
  23055. legendHeight * legendHeight / opts._height);
  23056. var scrollBarYMax = legendHeight -
  23057. scrollBarHeight -
  23058. 2 * constants.scrollBarMargin;
  23059. var scrollBoxYMax = opts._height - legendHeight;
  23060. var scrollRatio = scrollBarYMax / scrollBoxYMax;
  23061. var scrollBoxY = Math.min(opts._scrollY || 0, scrollBoxYMax);
  23062. // increase the background and clip-path width
  23063. // by the scrollbar width and margin
  23064. bg.attr({
  23065. width: legendWidth -
  23066. 2 * opts.borderwidth +
  23067. constants.scrollBarWidth +
  23068. constants.scrollBarMargin,
  23069. height: legendHeight - opts.borderwidth,
  23070. x: opts.borderwidth / 2,
  23071. y: opts.borderwidth / 2
  23072. });
  23073. clipPath.select('rect').attr({
  23074. width: legendWidth -
  23075. 2 * opts.borderwidth +
  23076. constants.scrollBarWidth +
  23077. constants.scrollBarMargin,
  23078. height: legendHeight - 2 * opts.borderwidth,
  23079. x: opts.borderwidth,
  23080. y: opts.borderwidth + scrollBoxY
  23081. });
  23082. Drawing.setClipUrl(scrollBox, clipId, gd);
  23083. scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);
  23084. legend.on('wheel', function() {
  23085. scrollBoxY = Lib.constrain(
  23086. opts._scrollY +
  23087. d3.event.deltaY / scrollBarYMax * scrollBoxYMax,
  23088. 0, scrollBoxYMax);
  23089. scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);
  23090. if(scrollBoxY !== 0 && scrollBoxY !== scrollBoxYMax) {
  23091. d3.event.preventDefault();
  23092. }
  23093. });
  23094. var eventY0, scrollBoxY0;
  23095. var drag = d3.behavior.drag()
  23096. .on('dragstart', function() {
  23097. eventY0 = d3.event.sourceEvent.clientY;
  23098. scrollBoxY0 = scrollBoxY;
  23099. })
  23100. .on('drag', function() {
  23101. var e = d3.event.sourceEvent;
  23102. if(e.buttons === 2 || e.ctrlKey) return;
  23103. scrollBoxY = Lib.constrain(
  23104. (e.clientY - eventY0) / scrollRatio + scrollBoxY0,
  23105. 0, scrollBoxYMax);
  23106. scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio);
  23107. });
  23108. scrollBar.call(drag);
  23109. }
  23110. function scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio) {
  23111. opts._scrollY = gd._fullLayout.legend._scrollY = scrollBoxY;
  23112. Drawing.setTranslate(scrollBox, 0, -scrollBoxY);
  23113. Drawing.setRect(
  23114. scrollBar,
  23115. legendWidth,
  23116. constants.scrollBarMargin + scrollBoxY * scrollRatio,
  23117. constants.scrollBarWidth,
  23118. scrollBarHeight
  23119. );
  23120. clipPath.select('rect').attr({
  23121. y: opts.borderwidth + scrollBoxY
  23122. });
  23123. }
  23124. if(gd._context.edits.legendPosition) {
  23125. var xf, yf, x0, y0;
  23126. legend.classed('cursor-move', true);
  23127. dragElement.init({
  23128. element: legend.node(),
  23129. gd: gd,
  23130. prepFn: function() {
  23131. var transform = Drawing.getTranslate(legend);
  23132. x0 = transform.x;
  23133. y0 = transform.y;
  23134. },
  23135. moveFn: function(dx, dy) {
  23136. var newX = x0 + dx;
  23137. var newY = y0 + dy;
  23138. Drawing.setTranslate(legend, newX, newY);
  23139. xf = dragElement.align(newX, 0, gs.l, gs.l + gs.w, opts.xanchor);
  23140. yf = dragElement.align(newY, 0, gs.t + gs.h, gs.t, opts.yanchor);
  23141. },
  23142. doneFn: function() {
  23143. if(xf !== undefined && yf !== undefined) {
  23144. Registry.call('_guiRelayout', gd, {'legend.x': xf, 'legend.y': yf});
  23145. }
  23146. },
  23147. clickFn: function(numClicks, e) {
  23148. var clickedTrace = fullLayout._infolayer.selectAll('g.traces').filter(function() {
  23149. var bbox = this.getBoundingClientRect();
  23150. return (
  23151. e.clientX >= bbox.left && e.clientX <= bbox.right &&
  23152. e.clientY >= bbox.top && e.clientY <= bbox.bottom
  23153. );
  23154. });
  23155. if(clickedTrace.size() > 0) {
  23156. clickOrDoubleClick(gd, legend, clickedTrace, numClicks, e);
  23157. }
  23158. }
  23159. });
  23160. }
  23161. }], gd);
  23162. };
  23163. function clickOrDoubleClick(gd, legend, legendItem, numClicks, evt) {
  23164. var trace = legendItem.data()[0][0].trace;
  23165. var evtData = {
  23166. event: evt,
  23167. node: legendItem.node(),
  23168. curveNumber: trace.index,
  23169. expandedIndex: trace._expandedIndex,
  23170. data: gd.data,
  23171. layout: gd.layout,
  23172. frames: gd._transitionData._frames,
  23173. config: gd._context,
  23174. fullData: gd._fullData,
  23175. fullLayout: gd._fullLayout
  23176. };
  23177. if(trace._group) {
  23178. evtData.group = trace._group;
  23179. }
  23180. if(trace.type === 'pie') {
  23181. evtData.label = legendItem.datum()[0].label;
  23182. }
  23183. var clickVal = Events.triggerHandler(gd, 'plotly_legendclick', evtData);
  23184. if(clickVal === false) return;
  23185. if(numClicks === 1) {
  23186. legend._clickTimeout = setTimeout(function() {
  23187. handleClick(legendItem, gd, numClicks);
  23188. }, DBLCLICKDELAY);
  23189. }
  23190. else if(numClicks === 2) {
  23191. if(legend._clickTimeout) clearTimeout(legend._clickTimeout);
  23192. gd._legendMouseDownTime = 0;
  23193. var dblClickVal = Events.triggerHandler(gd, 'plotly_legenddoubleclick', evtData);
  23194. if(dblClickVal !== false) handleClick(legendItem, gd, numClicks);
  23195. }
  23196. }
  23197. function drawTexts(g, gd, maxLength) {
  23198. var legendItem = g.data()[0][0];
  23199. var fullLayout = gd._fullLayout;
  23200. var trace = legendItem.trace;
  23201. var isPie = Registry.traceIs(trace, 'pie');
  23202. var traceIndex = trace.index;
  23203. var name = isPie ? legendItem.label : trace.name;
  23204. var isEditable = gd._context.edits.legendText && !isPie;
  23205. var textEl = Lib.ensureSingle(g, 'text', 'legendtext');
  23206. textEl.attr('text-anchor', 'start')
  23207. .classed('user-select-none', true)
  23208. .call(Drawing.font, fullLayout.legend.font)
  23209. .text(isEditable ? ensureLength(name, maxLength) : name);
  23210. svgTextUtils.positionText(textEl, constants.textOffsetX, 0);
  23211. function textLayout(s) {
  23212. svgTextUtils.convertToTspans(s, gd, function() {
  23213. computeTextDimensions(g, gd);
  23214. });
  23215. }
  23216. if(isEditable) {
  23217. textEl.call(svgTextUtils.makeEditable, {gd: gd, text: name})
  23218. .call(textLayout)
  23219. .on('edit', function(newName) {
  23220. this.text(ensureLength(newName, maxLength))
  23221. .call(textLayout);
  23222. var fullInput = legendItem.trace._fullInput || {};
  23223. var update = {};
  23224. if(Registry.hasTransform(fullInput, 'groupby')) {
  23225. var groupbyIndices = Registry.getTransformIndices(fullInput, 'groupby');
  23226. var index = groupbyIndices[groupbyIndices.length - 1];
  23227. var kcont = Lib.keyedContainer(fullInput, 'transforms[' + index + '].styles', 'target', 'value.name');
  23228. kcont.set(legendItem.trace._group, newName);
  23229. update = kcont.constructUpdate();
  23230. } else {
  23231. update.name = newName;
  23232. }
  23233. return Registry.call('_guiRestyle', gd, update, traceIndex);
  23234. });
  23235. } else {
  23236. textLayout(textEl);
  23237. }
  23238. }
  23239. /*
  23240. * Make sure we have a reasonably clickable region.
  23241. * If this string is missing or very short, pad it with spaces out to at least
  23242. * 4 characters, up to the max length of other labels, on the assumption that
  23243. * most characters are wider than spaces so a string of spaces will usually be
  23244. * no wider than the real labels.
  23245. */
  23246. function ensureLength(str, maxLength) {
  23247. var targetLength = Math.max(4, maxLength);
  23248. if(str && str.trim().length >= targetLength / 2) return str;
  23249. str = str || '';
  23250. for(var i = targetLength - str.length; i > 0; i--) str += ' ';
  23251. return str;
  23252. }
  23253. function setupTraceToggle(g, gd) {
  23254. var newMouseDownTime;
  23255. var numClicks = 1;
  23256. var traceToggle = Lib.ensureSingle(g, 'rect', 'legendtoggle', function(s) {
  23257. s.style('cursor', 'pointer')
  23258. .attr('pointer-events', 'all')
  23259. .call(Color.fill, 'rgba(0,0,0,0)');
  23260. });
  23261. traceToggle.on('mousedown', function() {
  23262. newMouseDownTime = (new Date()).getTime();
  23263. if(newMouseDownTime - gd._legendMouseDownTime < DBLCLICKDELAY) {
  23264. // in a click train
  23265. numClicks += 1;
  23266. }
  23267. else {
  23268. // new click train
  23269. numClicks = 1;
  23270. gd._legendMouseDownTime = newMouseDownTime;
  23271. }
  23272. });
  23273. traceToggle.on('mouseup', function() {
  23274. if(gd._dragged || gd._editing) return;
  23275. var legend = gd._fullLayout.legend;
  23276. if((new Date()).getTime() - gd._legendMouseDownTime > DBLCLICKDELAY) {
  23277. numClicks = Math.max(numClicks - 1, 1);
  23278. }
  23279. clickOrDoubleClick(gd, legend, g, numClicks, d3.event);
  23280. });
  23281. }
  23282. function computeTextDimensions(g, gd) {
  23283. var legendItem = g.data()[0][0];
  23284. if(!legendItem.trace.showlegend) {
  23285. g.remove();
  23286. return;
  23287. }
  23288. var mathjaxGroup = g.select('g[class*=math-group]');
  23289. var mathjaxNode = mathjaxGroup.node();
  23290. var opts = gd._fullLayout.legend;
  23291. var lineHeight = opts.font.size * LINE_SPACING;
  23292. var height, width;
  23293. if(mathjaxNode) {
  23294. var mathjaxBB = Drawing.bBox(mathjaxNode);
  23295. height = mathjaxBB.height;
  23296. width = mathjaxBB.width;
  23297. Drawing.setTranslate(mathjaxGroup, 0, (height / 4));
  23298. } else {
  23299. var text = g.select('.legendtext');
  23300. var textLines = svgTextUtils.lineCount(text);
  23301. var textNode = text.node();
  23302. height = lineHeight * textLines;
  23303. width = textNode ? Drawing.bBox(textNode).width : 0;
  23304. // approximation to height offset to center the font
  23305. // to avoid getBoundingClientRect
  23306. var textY = lineHeight * (0.3 + (1 - textLines) / 2);
  23307. svgTextUtils.positionText(text, constants.textOffsetX, textY);
  23308. }
  23309. legendItem.lineHeight = lineHeight;
  23310. legendItem.height = Math.max(height, 16) + 3;
  23311. legendItem.width = width;
  23312. }
  23313. function computeLegendDimensions(gd, groups, traces) {
  23314. var fullLayout = gd._fullLayout;
  23315. var opts = fullLayout.legend;
  23316. var borderwidth = opts.borderwidth;
  23317. var isGrouped = helpers.isGrouped(opts);
  23318. var extraWidth = 0;
  23319. opts._width = 0;
  23320. opts._height = 0;
  23321. if(helpers.isVertical(opts)) {
  23322. if(isGrouped) {
  23323. groups.each(function(d, i) {
  23324. Drawing.setTranslate(this, 0, i * opts.tracegroupgap);
  23325. });
  23326. }
  23327. traces.each(function(d) {
  23328. var legendItem = d[0];
  23329. var textHeight = legendItem.height;
  23330. var textWidth = legendItem.width;
  23331. Drawing.setTranslate(this,
  23332. borderwidth,
  23333. (5 + borderwidth + opts._height + textHeight / 2));
  23334. opts._height += textHeight;
  23335. opts._width = Math.max(opts._width, textWidth);
  23336. });
  23337. opts._width += 45 + borderwidth * 2;
  23338. opts._height += 10 + borderwidth * 2;
  23339. if(isGrouped) {
  23340. opts._height += (opts._lgroupsLength - 1) * opts.tracegroupgap;
  23341. }
  23342. extraWidth = 40;
  23343. }
  23344. else if(isGrouped) {
  23345. var groupXOffsets = [opts._width];
  23346. var groupData = groups.data();
  23347. for(var i = 0, n = groupData.length; i < n; i++) {
  23348. var textWidths = groupData[i].map(function(legendItemArray) {
  23349. return legendItemArray[0].width;
  23350. });
  23351. var groupWidth = 40 + Math.max.apply(null, textWidths);
  23352. opts._width += opts.tracegroupgap + groupWidth;
  23353. groupXOffsets.push(opts._width);
  23354. }
  23355. groups.each(function(d, i) {
  23356. Drawing.setTranslate(this, groupXOffsets[i], 0);
  23357. });
  23358. groups.each(function() {
  23359. var group = d3.select(this);
  23360. var groupTraces = group.selectAll('g.traces');
  23361. var groupHeight = 0;
  23362. groupTraces.each(function(d) {
  23363. var legendItem = d[0];
  23364. var textHeight = legendItem.height;
  23365. Drawing.setTranslate(this,
  23366. 0,
  23367. (5 + borderwidth + groupHeight + textHeight / 2));
  23368. groupHeight += textHeight;
  23369. });
  23370. opts._height = Math.max(opts._height, groupHeight);
  23371. });
  23372. opts._height += 10 + borderwidth * 2;
  23373. opts._width += borderwidth * 2;
  23374. }
  23375. else {
  23376. var rowHeight = 0;
  23377. var maxTraceHeight = 0;
  23378. var maxTraceWidth = 0;
  23379. var offsetX = 0;
  23380. var fullTracesWidth = 0;
  23381. var traceGap = opts.tracegroupgap || 5;
  23382. // calculate largest width for traces and use for width of all legend items
  23383. traces.each(function(d) {
  23384. maxTraceWidth = Math.max(40 + d[0].width, maxTraceWidth);
  23385. fullTracesWidth += 40 + d[0].width + traceGap;
  23386. });
  23387. // check if legend fits in one row
  23388. var oneRowLegend = fullLayout._size.w > borderwidth + fullTracesWidth - traceGap;
  23389. traces.each(function(d) {
  23390. var legendItem = d[0];
  23391. var traceWidth = oneRowLegend ? 40 + d[0].width : maxTraceWidth;
  23392. if((borderwidth + offsetX + traceGap + traceWidth) > fullLayout._size.w) {
  23393. offsetX = 0;
  23394. rowHeight += maxTraceHeight;
  23395. opts._height += maxTraceHeight;
  23396. // reset for next row
  23397. maxTraceHeight = 0;
  23398. }
  23399. Drawing.setTranslate(this,
  23400. (borderwidth + offsetX),
  23401. (5 + borderwidth + legendItem.height / 2) + rowHeight);
  23402. opts._width += traceGap + traceWidth;
  23403. // keep track of tallest trace in group
  23404. offsetX += traceGap + traceWidth;
  23405. maxTraceHeight = Math.max(legendItem.height, maxTraceHeight);
  23406. });
  23407. if(oneRowLegend) {
  23408. opts._height = maxTraceHeight;
  23409. } else {
  23410. opts._height += maxTraceHeight;
  23411. }
  23412. opts._width += borderwidth * 2;
  23413. opts._height += 10 + borderwidth * 2;
  23414. }
  23415. // make sure we're only getting full pixels
  23416. opts._width = Math.ceil(opts._width);
  23417. opts._height = Math.ceil(opts._height);
  23418. var isEditable = (
  23419. gd._context.edits.legendText ||
  23420. gd._context.edits.legendPosition
  23421. );
  23422. traces.each(function(d) {
  23423. var legendItem = d[0];
  23424. var bg = d3.select(this).select('.legendtoggle');
  23425. Drawing.setRect(bg,
  23426. 0,
  23427. -legendItem.height / 2,
  23428. (isEditable ? 0 : opts._width) + extraWidth,
  23429. legendItem.height
  23430. );
  23431. });
  23432. }
  23433. function expandMargin(gd) {
  23434. var fullLayout = gd._fullLayout;
  23435. var opts = fullLayout.legend;
  23436. var xanchor = 'left';
  23437. if(Lib.isRightAnchor(opts)) {
  23438. xanchor = 'right';
  23439. }
  23440. else if(Lib.isCenterAnchor(opts)) {
  23441. xanchor = 'center';
  23442. }
  23443. var yanchor = 'top';
  23444. if(Lib.isBottomAnchor(opts)) {
  23445. yanchor = 'bottom';
  23446. }
  23447. else if(Lib.isMiddleAnchor(opts)) {
  23448. yanchor = 'middle';
  23449. }
  23450. // lastly check if the margin auto-expand has changed
  23451. Plots.autoMargin(gd, 'legend', {
  23452. x: opts.x,
  23453. y: opts.y,
  23454. l: opts._width * (FROM_TL[xanchor]),
  23455. r: opts._width * (FROM_BR[xanchor]),
  23456. b: opts._height * (FROM_BR[yanchor]),
  23457. t: opts._height * (FROM_TL[yanchor])
  23458. });
  23459. }
  23460. function expandHorizontalMargin(gd) {
  23461. var fullLayout = gd._fullLayout;
  23462. var opts = fullLayout.legend;
  23463. var xanchor = 'left';
  23464. if(Lib.isRightAnchor(opts)) {
  23465. xanchor = 'right';
  23466. }
  23467. else if(Lib.isCenterAnchor(opts)) {
  23468. xanchor = 'center';
  23469. }
  23470. // lastly check if the margin auto-expand has changed
  23471. Plots.autoMargin(gd, 'legend', {
  23472. x: opts.x,
  23473. y: 0.5,
  23474. l: opts._width * (FROM_TL[xanchor]),
  23475. r: opts._width * (FROM_BR[xanchor]),
  23476. b: 0,
  23477. t: 0
  23478. });
  23479. }
  23480. },{"../../constants/alignment":146,"../../constants/interactions":148,"../../lib":168,"../../lib/events":161,"../../lib/svg_text_utils":189,"../../plots/plots":245,"../../registry":257,"../color":51,"../dragelement":69,"../drawing":72,"./constants":101,"./get_legend_data":104,"./handle_click":105,"./helpers":106,"./style":108,"d3":16}],104:[function(_dereq_,module,exports){
  23481. /**
  23482. * Copyright 2012-2019, Plotly, Inc.
  23483. * All rights reserved.
  23484. *
  23485. * This source code is licensed under the MIT license found in the
  23486. * LICENSE file in the root directory of this source tree.
  23487. */
  23488. 'use strict';
  23489. var Registry = _dereq_('../../registry');
  23490. var helpers = _dereq_('./helpers');
  23491. module.exports = function getLegendData(calcdata, opts) {
  23492. var lgroupToTraces = {};
  23493. var lgroups = [];
  23494. var hasOneNonBlankGroup = false;
  23495. var slicesShown = {};
  23496. var lgroupi = 0;
  23497. var i, j;
  23498. function addOneItem(legendGroup, legendItem) {
  23499. // each '' legend group is treated as a separate group
  23500. if(legendGroup === '' || !helpers.isGrouped(opts)) {
  23501. var uniqueGroup = '~~i' + lgroupi; // TODO: check this against fullData legendgroups?
  23502. lgroups.push(uniqueGroup);
  23503. lgroupToTraces[uniqueGroup] = [[legendItem]];
  23504. lgroupi++;
  23505. }
  23506. else if(lgroups.indexOf(legendGroup) === -1) {
  23507. lgroups.push(legendGroup);
  23508. hasOneNonBlankGroup = true;
  23509. lgroupToTraces[legendGroup] = [[legendItem]];
  23510. }
  23511. else lgroupToTraces[legendGroup].push([legendItem]);
  23512. }
  23513. // build an { legendgroup: [cd0, cd0], ... } object
  23514. for(i = 0; i < calcdata.length; i++) {
  23515. var cd = calcdata[i];
  23516. var cd0 = cd[0];
  23517. var trace = cd0.trace;
  23518. var lgroup = trace.legendgroup;
  23519. if(!trace.visible || !trace.showlegend) continue;
  23520. if(Registry.traceIs(trace, 'pie')) {
  23521. if(!slicesShown[lgroup]) slicesShown[lgroup] = {};
  23522. for(j = 0; j < cd.length; j++) {
  23523. var labelj = cd[j].label;
  23524. if(!slicesShown[lgroup][labelj]) {
  23525. addOneItem(lgroup, {
  23526. label: labelj,
  23527. color: cd[j].color,
  23528. i: cd[j].i,
  23529. trace: trace,
  23530. pts: cd[j].pts
  23531. });
  23532. slicesShown[lgroup][labelj] = true;
  23533. }
  23534. }
  23535. }
  23536. else addOneItem(lgroup, cd0);
  23537. }
  23538. // won't draw a legend in this case
  23539. if(!lgroups.length) return [];
  23540. // rearrange lgroupToTraces into a d3-friendly array of arrays
  23541. var lgroupsLength = lgroups.length;
  23542. var ltraces;
  23543. var legendData;
  23544. if(hasOneNonBlankGroup && helpers.isGrouped(opts)) {
  23545. legendData = new Array(lgroupsLength);
  23546. for(i = 0; i < lgroupsLength; i++) {
  23547. ltraces = lgroupToTraces[lgroups[i]];
  23548. legendData[i] = helpers.isReversed(opts) ? ltraces.reverse() : ltraces;
  23549. }
  23550. }
  23551. else {
  23552. // collapse all groups into one if all groups are blank
  23553. legendData = [new Array(lgroupsLength)];
  23554. for(i = 0; i < lgroupsLength; i++) {
  23555. ltraces = lgroupToTraces[lgroups[i]][0];
  23556. legendData[0][helpers.isReversed(opts) ? lgroupsLength - i - 1 : i] = ltraces;
  23557. }
  23558. lgroupsLength = 1;
  23559. }
  23560. // needed in repositionLegend
  23561. opts._lgroupsLength = lgroupsLength;
  23562. return legendData;
  23563. };
  23564. },{"../../registry":257,"./helpers":106}],105:[function(_dereq_,module,exports){
  23565. /**
  23566. * Copyright 2012-2019, Plotly, Inc.
  23567. * All rights reserved.
  23568. *
  23569. * This source code is licensed under the MIT license found in the
  23570. * LICENSE file in the root directory of this source tree.
  23571. */
  23572. 'use strict';
  23573. var Lib = _dereq_('../../lib');
  23574. var Registry = _dereq_('../../registry');
  23575. var SHOWISOLATETIP = true;
  23576. module.exports = function handleClick(g, gd, numClicks) {
  23577. if(gd._dragged || gd._editing) return;
  23578. var hiddenSlices = gd._fullLayout.hiddenlabels ?
  23579. gd._fullLayout.hiddenlabels.slice() :
  23580. [];
  23581. var legendItem = g.data()[0][0];
  23582. var fullData = gd._fullData;
  23583. var fullTrace = legendItem.trace;
  23584. var legendgroup = fullTrace.legendgroup;
  23585. var i, j, kcont, key, keys, val;
  23586. var attrUpdate = {};
  23587. var attrIndices = [];
  23588. var carrs = [];
  23589. var carrIdx = [];
  23590. function insertUpdate(traceIndex, key, value) {
  23591. var attrIndex = attrIndices.indexOf(traceIndex);
  23592. var valueArray = attrUpdate[key];
  23593. if(!valueArray) {
  23594. valueArray = attrUpdate[key] = [];
  23595. }
  23596. if(attrIndices.indexOf(traceIndex) === -1) {
  23597. attrIndices.push(traceIndex);
  23598. attrIndex = attrIndices.length - 1;
  23599. }
  23600. valueArray[attrIndex] = value;
  23601. return attrIndex;
  23602. }
  23603. function setVisibility(fullTrace, visibility) {
  23604. var fullInput = fullTrace._fullInput;
  23605. if(Registry.hasTransform(fullInput, 'groupby')) {
  23606. var kcont = carrs[fullInput.index];
  23607. if(!kcont) {
  23608. var groupbyIndices = Registry.getTransformIndices(fullInput, 'groupby');
  23609. var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1];
  23610. kcont = Lib.keyedContainer(fullInput, 'transforms[' + lastGroupbyIndex + '].styles', 'target', 'value.visible');
  23611. carrs[fullInput.index] = kcont;
  23612. }
  23613. var curState = kcont.get(fullTrace._group);
  23614. // If not specified, assume visible. This happens if there are other style
  23615. // properties set for a group but not the visibility. There are many similar
  23616. // ways to do this (e.g. why not just `curState = fullTrace.visible`??? The
  23617. // answer is: because it breaks other things like groupby trace names in
  23618. // subtle ways.)
  23619. if(curState === undefined) {
  23620. curState = true;
  23621. }
  23622. if(curState !== false) {
  23623. // true -> legendonly. All others toggle to true:
  23624. kcont.set(fullTrace._group, visibility);
  23625. }
  23626. carrIdx[fullInput.index] = insertUpdate(fullInput.index, 'visible', fullInput.visible === false ? false : true);
  23627. } else {
  23628. // false -> false (not possible since will not be visible in legend)
  23629. // true -> legendonly
  23630. // legendonly -> true
  23631. var nextVisibility = fullInput.visible === false ? false : visibility;
  23632. insertUpdate(fullInput.index, 'visible', nextVisibility);
  23633. }
  23634. }
  23635. if(numClicks === 1 && SHOWISOLATETIP && gd.data && gd._context.showTips) {
  23636. Lib.notifier(Lib._(gd, 'Double-click on legend to isolate one trace'), 'long');
  23637. SHOWISOLATETIP = false;
  23638. } else {
  23639. SHOWISOLATETIP = false;
  23640. }
  23641. if(Registry.traceIs(fullTrace, 'pie')) {
  23642. var thisLabel = legendItem.label;
  23643. var thisLabelIndex = hiddenSlices.indexOf(thisLabel);
  23644. if(numClicks === 1) {
  23645. if(thisLabelIndex === -1) hiddenSlices.push(thisLabel);
  23646. else hiddenSlices.splice(thisLabelIndex, 1);
  23647. } else if(numClicks === 2) {
  23648. hiddenSlices = [];
  23649. gd.calcdata[0].forEach(function(d) {
  23650. if(thisLabel !== d.label) {
  23651. hiddenSlices.push(d.label);
  23652. }
  23653. });
  23654. if(gd._fullLayout.hiddenlabels && gd._fullLayout.hiddenlabels.length === hiddenSlices.length && thisLabelIndex === -1) {
  23655. hiddenSlices = [];
  23656. }
  23657. }
  23658. Registry.call('_guiRelayout', gd, 'hiddenlabels', hiddenSlices);
  23659. } else {
  23660. var hasLegendgroup = legendgroup && legendgroup.length;
  23661. var traceIndicesInGroup = [];
  23662. var tracei;
  23663. if(hasLegendgroup) {
  23664. for(i = 0; i < fullData.length; i++) {
  23665. tracei = fullData[i];
  23666. if(!tracei.visible) continue;
  23667. if(tracei.legendgroup === legendgroup) {
  23668. traceIndicesInGroup.push(i);
  23669. }
  23670. }
  23671. }
  23672. if(numClicks === 1) {
  23673. var nextVisibility;
  23674. switch(fullTrace.visible) {
  23675. case true:
  23676. nextVisibility = 'legendonly';
  23677. break;
  23678. case false:
  23679. nextVisibility = false;
  23680. break;
  23681. case 'legendonly':
  23682. nextVisibility = true;
  23683. break;
  23684. }
  23685. if(hasLegendgroup) {
  23686. for(i = 0; i < fullData.length; i++) {
  23687. if(fullData[i].visible !== false && fullData[i].legendgroup === legendgroup) {
  23688. setVisibility(fullData[i], nextVisibility);
  23689. }
  23690. }
  23691. } else {
  23692. setVisibility(fullTrace, nextVisibility);
  23693. }
  23694. } else if(numClicks === 2) {
  23695. // Compute the clicked index. expandedIndex does what we want for expanded traces
  23696. // but also culls hidden traces. That means we have some work to do.
  23697. var isClicked, isInGroup, otherState;
  23698. var isIsolated = true;
  23699. for(i = 0; i < fullData.length; i++) {
  23700. isClicked = fullData[i] === fullTrace;
  23701. if(isClicked) continue;
  23702. isInGroup = (hasLegendgroup && fullData[i].legendgroup === legendgroup);
  23703. if(!isInGroup && fullData[i].visible === true && !Registry.traceIs(fullData[i], 'notLegendIsolatable')) {
  23704. isIsolated = false;
  23705. break;
  23706. }
  23707. }
  23708. for(i = 0; i < fullData.length; i++) {
  23709. // False is sticky; we don't change it.
  23710. if(fullData[i].visible === false) continue;
  23711. if(Registry.traceIs(fullData[i], 'notLegendIsolatable')) {
  23712. continue;
  23713. }
  23714. switch(fullTrace.visible) {
  23715. case 'legendonly':
  23716. setVisibility(fullData[i], true);
  23717. break;
  23718. case true:
  23719. otherState = isIsolated ? true : 'legendonly';
  23720. isClicked = fullData[i] === fullTrace;
  23721. isInGroup = isClicked || (hasLegendgroup && fullData[i].legendgroup === legendgroup);
  23722. setVisibility(fullData[i], isInGroup ? true : otherState);
  23723. break;
  23724. }
  23725. }
  23726. }
  23727. for(i = 0; i < carrs.length; i++) {
  23728. kcont = carrs[i];
  23729. if(!kcont) continue;
  23730. var update = kcont.constructUpdate();
  23731. var updateKeys = Object.keys(update);
  23732. for(j = 0; j < updateKeys.length; j++) {
  23733. key = updateKeys[j];
  23734. val = attrUpdate[key] = attrUpdate[key] || [];
  23735. val[carrIdx[i]] = update[key];
  23736. }
  23737. }
  23738. // The length of the value arrays should be equal and any unspecified
  23739. // values should be explicitly undefined for them to get properly culled
  23740. // as updates and not accidentally reset to the default value. This fills
  23741. // out sparse arrays with the required number of undefined values:
  23742. keys = Object.keys(attrUpdate);
  23743. for(i = 0; i < keys.length; i++) {
  23744. key = keys[i];
  23745. for(j = 0; j < attrIndices.length; j++) {
  23746. // Use hasOwnPropety to protect against falsey values:
  23747. if(!attrUpdate[key].hasOwnProperty(j)) {
  23748. attrUpdate[key][j] = undefined;
  23749. }
  23750. }
  23751. }
  23752. Registry.call('_guiRestyle', gd, attrUpdate, attrIndices);
  23753. }
  23754. };
  23755. },{"../../lib":168,"../../registry":257}],106:[function(_dereq_,module,exports){
  23756. /**
  23757. * Copyright 2012-2019, Plotly, Inc.
  23758. * All rights reserved.
  23759. *
  23760. * This source code is licensed under the MIT license found in the
  23761. * LICENSE file in the root directory of this source tree.
  23762. */
  23763. 'use strict';
  23764. exports.isGrouped = function isGrouped(legendLayout) {
  23765. return (legendLayout.traceorder || '').indexOf('grouped') !== -1;
  23766. };
  23767. exports.isVertical = function isVertical(legendLayout) {
  23768. return legendLayout.orientation !== 'h';
  23769. };
  23770. exports.isReversed = function isReversed(legendLayout) {
  23771. return (legendLayout.traceorder || '').indexOf('reversed') !== -1;
  23772. };
  23773. },{}],107:[function(_dereq_,module,exports){
  23774. /**
  23775. * Copyright 2012-2019, Plotly, Inc.
  23776. * All rights reserved.
  23777. *
  23778. * This source code is licensed under the MIT license found in the
  23779. * LICENSE file in the root directory of this source tree.
  23780. */
  23781. 'use strict';
  23782. module.exports = {
  23783. moduleType: 'component',
  23784. name: 'legend',
  23785. layoutAttributes: _dereq_('./attributes'),
  23786. supplyLayoutDefaults: _dereq_('./defaults'),
  23787. draw: _dereq_('./draw'),
  23788. style: _dereq_('./style')
  23789. };
  23790. },{"./attributes":100,"./defaults":102,"./draw":103,"./style":108}],108:[function(_dereq_,module,exports){
  23791. /**
  23792. * Copyright 2012-2019, Plotly, Inc.
  23793. * All rights reserved.
  23794. *
  23795. * This source code is licensed under the MIT license found in the
  23796. * LICENSE file in the root directory of this source tree.
  23797. */
  23798. 'use strict';
  23799. var d3 = _dereq_('d3');
  23800. var Registry = _dereq_('../../registry');
  23801. var Lib = _dereq_('../../lib');
  23802. var Drawing = _dereq_('../drawing');
  23803. var Color = _dereq_('../color');
  23804. var subTypes = _dereq_('../../traces/scatter/subtypes');
  23805. var stylePie = _dereq_('../../traces/pie/style_one');
  23806. module.exports = function style(s, gd) {
  23807. s.each(function(d) {
  23808. var traceGroup = d3.select(this);
  23809. var layers = Lib.ensureSingle(traceGroup, 'g', 'layers');
  23810. layers.style('opacity', d[0].trace.opacity);
  23811. // Marker vertical alignment
  23812. var valign = gd._fullLayout.legend.valign;
  23813. var lineHeight = d[0].lineHeight;
  23814. var height = d[0].height;
  23815. if(valign === 'middle' || !lineHeight || !height) {
  23816. layers.attr('transform', null);
  23817. } else {
  23818. var factor = {top: 1, bottom: -1}[valign];
  23819. var markerOffsetY = factor * (0.5 * (lineHeight - height + 3));
  23820. layers.attr('transform', 'translate(0,' + markerOffsetY + ')');
  23821. }
  23822. var fill = layers
  23823. .selectAll('g.legendfill')
  23824. .data([d]);
  23825. fill.enter().append('g')
  23826. .classed('legendfill', true);
  23827. var line = layers
  23828. .selectAll('g.legendlines')
  23829. .data([d]);
  23830. line.enter().append('g')
  23831. .classed('legendlines', true);
  23832. var symbol = layers
  23833. .selectAll('g.legendsymbols')
  23834. .data([d]);
  23835. symbol.enter().append('g')
  23836. .classed('legendsymbols', true);
  23837. symbol.selectAll('g.legendpoints')
  23838. .data([d])
  23839. .enter().append('g')
  23840. .classed('legendpoints', true);
  23841. })
  23842. .each(styleBars)
  23843. .each(styleBoxes)
  23844. .each(stylePies)
  23845. .each(styleLines)
  23846. .each(stylePoints)
  23847. .each(styleCandles)
  23848. .each(styleOHLC);
  23849. function styleLines(d) {
  23850. var trace = d[0].trace;
  23851. var showFill = trace.visible && trace.fill && trace.fill !== 'none';
  23852. var showLine = subTypes.hasLines(trace);
  23853. var contours = trace.contours;
  23854. var showGradientLine = false;
  23855. var showGradientFill = false;
  23856. if(contours) {
  23857. var coloring = contours.coloring;
  23858. if(coloring === 'lines') {
  23859. showGradientLine = true;
  23860. }
  23861. else {
  23862. showLine = coloring === 'none' || coloring === 'heatmap' ||
  23863. contours.showlines;
  23864. }
  23865. if(contours.type === 'constraint') {
  23866. showFill = contours._operation !== '=';
  23867. }
  23868. else if(coloring === 'fill' || coloring === 'heatmap') {
  23869. showGradientFill = true;
  23870. }
  23871. }
  23872. // with fill and no markers or text, move the line and fill up a bit
  23873. // so it's more centered
  23874. var markersOrText = subTypes.hasMarkers(trace) || subTypes.hasText(trace);
  23875. var anyFill = showFill || showGradientFill;
  23876. var anyLine = showLine || showGradientLine;
  23877. var pathStart = (markersOrText || !anyFill) ? 'M5,0' :
  23878. // with a line leave it slightly below center, to leave room for the
  23879. // line thickness and because the line is usually more prominent
  23880. anyLine ? 'M5,-2' : 'M5,-3';
  23881. var this3 = d3.select(this);
  23882. var fill = this3.select('.legendfill').selectAll('path')
  23883. .data(showFill || showGradientFill ? [d] : []);
  23884. fill.enter().append('path').classed('js-fill', true);
  23885. fill.exit().remove();
  23886. fill.attr('d', pathStart + 'h30v6h-30z')
  23887. .call(showFill ? Drawing.fillGroupStyle : fillGradient);
  23888. var line = this3.select('.legendlines').selectAll('path')
  23889. .data(showLine || showGradientLine ? [d] : []);
  23890. line.enter().append('path').classed('js-line', true);
  23891. line.exit().remove();
  23892. // this is ugly... but you can't apply a gradient to a perfectly
  23893. // horizontal or vertical line. Presumably because then
  23894. // the system doesn't know how to scale vertical variation, even
  23895. // though there *is* no vertical variation in this case.
  23896. // so add an invisibly small angle to the line
  23897. // This issue (and workaround) exist across (Mac) Chrome, FF, and Safari
  23898. line.attr('d', pathStart + (showGradientLine ? 'l30,0.0001' : 'h30'))
  23899. .call(showLine ? Drawing.lineGroupStyle : lineGradient);
  23900. function fillGradient(s) {
  23901. if(s.size()) {
  23902. var gradientID = 'legendfill-' + trace.uid;
  23903. Drawing.gradient(s, gd, gradientID, 'horizontalreversed',
  23904. trace.colorscale, 'fill');
  23905. }
  23906. }
  23907. function lineGradient(s) {
  23908. if(s.size()) {
  23909. var gradientID = 'legendline-' + trace.uid;
  23910. Drawing.lineGroupStyle(s);
  23911. Drawing.gradient(s, gd, gradientID, 'horizontalreversed',
  23912. trace.colorscale, 'stroke');
  23913. }
  23914. }
  23915. }
  23916. function stylePoints(d) {
  23917. var d0 = d[0];
  23918. var trace = d0.trace;
  23919. var showMarkers = subTypes.hasMarkers(trace);
  23920. var showText = subTypes.hasText(trace);
  23921. var showLines = subTypes.hasLines(trace);
  23922. var dMod, tMod;
  23923. // 'scatter3d' don't use gd.calcdata,
  23924. // use d0.trace to infer arrayOk attributes
  23925. function boundVal(attrIn, arrayToValFn, bounds) {
  23926. var valIn = Lib.nestedProperty(trace, attrIn).get();
  23927. var valToBound = (Lib.isArrayOrTypedArray(valIn) && arrayToValFn) ?
  23928. arrayToValFn(valIn) :
  23929. valIn;
  23930. if(bounds) {
  23931. if(valToBound < bounds[0]) return bounds[0];
  23932. else if(valToBound > bounds[1]) return bounds[1];
  23933. }
  23934. return valToBound;
  23935. }
  23936. function pickFirst(array) { return array[0]; }
  23937. // constrain text, markers, etc so they'll fit on the legend
  23938. if(showMarkers || showText || showLines) {
  23939. var dEdit = {};
  23940. var tEdit = {};
  23941. if(showMarkers) {
  23942. dEdit.mc = boundVal('marker.color', pickFirst);
  23943. dEdit.mx = boundVal('marker.symbol', pickFirst);
  23944. dEdit.mo = boundVal('marker.opacity', Lib.mean, [0.2, 1]);
  23945. dEdit.mlc = boundVal('marker.line.color', pickFirst);
  23946. dEdit.mlw = boundVal('marker.line.width', Lib.mean, [0, 5]);
  23947. tEdit.marker = {
  23948. sizeref: 1,
  23949. sizemin: 1,
  23950. sizemode: 'diameter'
  23951. };
  23952. var ms = boundVal('marker.size', Lib.mean, [2, 16]);
  23953. dEdit.ms = ms;
  23954. tEdit.marker.size = ms;
  23955. }
  23956. if(showLines) {
  23957. tEdit.line = {
  23958. width: boundVal('line.width', pickFirst, [0, 10])
  23959. };
  23960. }
  23961. if(showText) {
  23962. dEdit.tx = 'Aa';
  23963. dEdit.tp = boundVal('textposition', pickFirst);
  23964. dEdit.ts = 10;
  23965. dEdit.tc = boundVal('textfont.color', pickFirst);
  23966. dEdit.tf = boundVal('textfont.family', pickFirst);
  23967. }
  23968. dMod = [Lib.minExtend(d0, dEdit)];
  23969. tMod = Lib.minExtend(trace, tEdit);
  23970. // always show legend items in base state
  23971. tMod.selectedpoints = null;
  23972. }
  23973. var ptgroup = d3.select(this).select('g.legendpoints');
  23974. var pts = ptgroup.selectAll('path.scatterpts')
  23975. .data(showMarkers ? dMod : []);
  23976. // make sure marker is on the bottom, in case it enters after text
  23977. pts.enter().insert('path', ':first-child')
  23978. .classed('scatterpts', true)
  23979. .attr('transform', 'translate(20,0)');
  23980. pts.exit().remove();
  23981. pts.call(Drawing.pointStyle, tMod, gd);
  23982. // 'mrc' is set in pointStyle and used in textPointStyle:
  23983. // constrain it here
  23984. if(showMarkers) dMod[0].mrc = 3;
  23985. var txt = ptgroup.selectAll('g.pointtext')
  23986. .data(showText ? dMod : []);
  23987. txt.enter()
  23988. .append('g').classed('pointtext', true)
  23989. .append('text').attr('transform', 'translate(20,0)');
  23990. txt.exit().remove();
  23991. txt.selectAll('text').call(Drawing.textPointStyle, tMod, gd);
  23992. }
  23993. function styleBars(d) {
  23994. var trace = d[0].trace;
  23995. var marker = trace.marker || {};
  23996. var markerLine = marker.line || {};
  23997. var barpath = d3.select(this).select('g.legendpoints')
  23998. .selectAll('path.legendbar')
  23999. .data(Registry.traceIs(trace, 'bar') ? [d] : []);
  24000. barpath.enter().append('path').classed('legendbar', true)
  24001. .attr('d', 'M6,6H-6V-6H6Z')
  24002. .attr('transform', 'translate(20,0)');
  24003. barpath.exit().remove();
  24004. barpath.each(function(d) {
  24005. var p = d3.select(this);
  24006. var d0 = d[0];
  24007. var w = (d0.mlw + 1 || markerLine.width + 1) - 1;
  24008. p.style('stroke-width', w + 'px')
  24009. .call(Color.fill, d0.mc || marker.color);
  24010. if(w) {
  24011. p.call(Color.stroke, d0.mlc || markerLine.color);
  24012. }
  24013. });
  24014. }
  24015. function styleBoxes(d) {
  24016. var trace = d[0].trace;
  24017. var pts = d3.select(this).select('g.legendpoints')
  24018. .selectAll('path.legendbox')
  24019. .data(Registry.traceIs(trace, 'box-violin') && trace.visible ? [d] : []);
  24020. pts.enter().append('path').classed('legendbox', true)
  24021. // if we want the median bar, prepend M6,0H-6
  24022. .attr('d', 'M6,6H-6V-6H6Z')
  24023. .attr('transform', 'translate(20,0)');
  24024. pts.exit().remove();
  24025. pts.each(function() {
  24026. var w = trace.line.width;
  24027. var p = d3.select(this);
  24028. p.style('stroke-width', w + 'px')
  24029. .call(Color.fill, trace.fillcolor);
  24030. if(w) {
  24031. Color.stroke(p, trace.line.color);
  24032. }
  24033. });
  24034. }
  24035. function styleCandles(d) {
  24036. var trace = d[0].trace;
  24037. var pts = d3.select(this).select('g.legendpoints')
  24038. .selectAll('path.legendcandle')
  24039. .data(trace.type === 'candlestick' && trace.visible ? [d, d] : []);
  24040. pts.enter().append('path').classed('legendcandle', true)
  24041. .attr('d', function(_, i) {
  24042. if(i) return 'M-15,0H-8M-8,6V-6H8Z'; // increasing
  24043. return 'M15,0H8M8,-6V6H-8Z'; // decreasing
  24044. })
  24045. .attr('transform', 'translate(20,0)')
  24046. .style('stroke-miterlimit', 1);
  24047. pts.exit().remove();
  24048. pts.each(function(_, i) {
  24049. var container = trace[i ? 'increasing' : 'decreasing'];
  24050. var w = container.line.width;
  24051. var p = d3.select(this);
  24052. p.style('stroke-width', w + 'px')
  24053. .call(Color.fill, container.fillcolor);
  24054. if(w) {
  24055. Color.stroke(p, container.line.color);
  24056. }
  24057. });
  24058. }
  24059. function styleOHLC(d) {
  24060. var trace = d[0].trace;
  24061. var pts = d3.select(this).select('g.legendpoints')
  24062. .selectAll('path.legendohlc')
  24063. .data(trace.type === 'ohlc' && trace.visible ? [d, d] : []);
  24064. pts.enter().append('path').classed('legendohlc', true)
  24065. .attr('d', function(_, i) {
  24066. if(i) return 'M-15,0H0M-8,-6V0'; // increasing
  24067. return 'M15,0H0M8,6V0'; // decreasing
  24068. })
  24069. .attr('transform', 'translate(20,0)')
  24070. .style('stroke-miterlimit', 1);
  24071. pts.exit().remove();
  24072. pts.each(function(_, i) {
  24073. var container = trace[i ? 'increasing' : 'decreasing'];
  24074. var w = container.line.width;
  24075. var p = d3.select(this);
  24076. p.style('fill', 'none')
  24077. .call(Drawing.dashLine, container.line.dash, w);
  24078. if(w) {
  24079. Color.stroke(p, container.line.color);
  24080. }
  24081. });
  24082. }
  24083. function stylePies(d) {
  24084. var trace = d[0].trace;
  24085. var pts = d3.select(this).select('g.legendpoints')
  24086. .selectAll('path.legendpie')
  24087. .data(Registry.traceIs(trace, 'pie') && trace.visible ? [d] : []);
  24088. pts.enter().append('path').classed('legendpie', true)
  24089. .attr('d', 'M6,6H-6V-6H6Z')
  24090. .attr('transform', 'translate(20,0)');
  24091. pts.exit().remove();
  24092. if(pts.size()) pts.call(stylePie, d[0], trace);
  24093. }
  24094. };
  24095. },{"../../lib":168,"../../registry":257,"../../traces/pie/style_one":365,"../../traces/scatter/subtypes":391,"../color":51,"../drawing":72,"d3":16}],109:[function(_dereq_,module,exports){
  24096. /**
  24097. * Copyright 2012-2019, Plotly, Inc.
  24098. * All rights reserved.
  24099. *
  24100. * This source code is licensed under the MIT license found in the
  24101. * LICENSE file in the root directory of this source tree.
  24102. */
  24103. 'use strict';
  24104. var Registry = _dereq_('../../registry');
  24105. var Plots = _dereq_('../../plots/plots');
  24106. var axisIds = _dereq_('../../plots/cartesian/axis_ids');
  24107. var Lib = _dereq_('../../lib');
  24108. var Icons = _dereq_('../../../build/ploticon');
  24109. var _ = Lib._;
  24110. var modeBarButtons = module.exports = {};
  24111. /**
  24112. * ModeBar buttons configuration
  24113. *
  24114. * @param {string} name
  24115. * name / id of the buttons (for tracking)
  24116. * @param {string} title
  24117. * text that appears while hovering over the button,
  24118. * enter null, false or '' for no hover text
  24119. * @param {string} icon
  24120. * svg icon object associated with the button
  24121. * can be linked to Plotly.Icons to use the default plotly icons
  24122. * @param {string} [gravity]
  24123. * icon positioning
  24124. * @param {function} click
  24125. * click handler associated with the button, a function of
  24126. * 'gd' (the main graph object) and
  24127. * 'ev' (the event object)
  24128. * @param {string} [attr]
  24129. * attribute associated with button,
  24130. * use this with 'val' to keep track of the state
  24131. * @param {*} [val]
  24132. * initial 'attr' value, can be a function of gd
  24133. * @param {boolean} [toggle]
  24134. * is the button a toggle button?
  24135. */
  24136. modeBarButtons.toImage = {
  24137. name: 'toImage',
  24138. title: function(gd) {
  24139. var opts = gd._context.toImageButtonOptions || {};
  24140. var format = opts.format || 'png';
  24141. return format === 'png' ?
  24142. _(gd, 'Download plot as a png') : // legacy text
  24143. _(gd, 'Download plot'); // generic non-PNG text
  24144. },
  24145. icon: Icons.camera,
  24146. click: function(gd) {
  24147. var toImageButtonOptions = gd._context.toImageButtonOptions;
  24148. var opts = {format: toImageButtonOptions.format || 'png'};
  24149. Lib.notifier(_(gd, 'Taking snapshot - this may take a few seconds'), 'long');
  24150. if(opts.format !== 'svg' && Lib.isIE()) {
  24151. Lib.notifier(_(gd, 'IE only supports svg. Changing format to svg.'), 'long');
  24152. opts.format = 'svg';
  24153. }
  24154. ['filename', 'width', 'height', 'scale'].forEach(function(key) {
  24155. if(toImageButtonOptions[key]) {
  24156. opts[key] = toImageButtonOptions[key];
  24157. }
  24158. });
  24159. Registry.call('downloadImage', gd, opts)
  24160. .then(function(filename) {
  24161. Lib.notifier(_(gd, 'Snapshot succeeded') + ' - ' + filename, 'long');
  24162. })
  24163. .catch(function() {
  24164. Lib.notifier(_(gd, 'Sorry, there was a problem downloading your snapshot!'), 'long');
  24165. });
  24166. }
  24167. };
  24168. modeBarButtons.sendDataToCloud = {
  24169. name: 'sendDataToCloud',
  24170. title: function(gd) { return _(gd, 'Edit in Chart Studio'); },
  24171. icon: Icons.disk,
  24172. click: function(gd) {
  24173. Plots.sendDataToCloud(gd);
  24174. }
  24175. };
  24176. modeBarButtons.zoom2d = {
  24177. name: 'zoom2d',
  24178. title: function(gd) { return _(gd, 'Zoom'); },
  24179. attr: 'dragmode',
  24180. val: 'zoom',
  24181. icon: Icons.zoombox,
  24182. click: handleCartesian
  24183. };
  24184. modeBarButtons.pan2d = {
  24185. name: 'pan2d',
  24186. title: function(gd) { return _(gd, 'Pan'); },
  24187. attr: 'dragmode',
  24188. val: 'pan',
  24189. icon: Icons.pan,
  24190. click: handleCartesian
  24191. };
  24192. modeBarButtons.select2d = {
  24193. name: 'select2d',
  24194. title: function(gd) { return _(gd, 'Box Select'); },
  24195. attr: 'dragmode',
  24196. val: 'select',
  24197. icon: Icons.selectbox,
  24198. click: handleCartesian
  24199. };
  24200. modeBarButtons.lasso2d = {
  24201. name: 'lasso2d',
  24202. title: function(gd) { return _(gd, 'Lasso Select'); },
  24203. attr: 'dragmode',
  24204. val: 'lasso',
  24205. icon: Icons.lasso,
  24206. click: handleCartesian
  24207. };
  24208. modeBarButtons.zoomIn2d = {
  24209. name: 'zoomIn2d',
  24210. title: function(gd) { return _(gd, 'Zoom in'); },
  24211. attr: 'zoom',
  24212. val: 'in',
  24213. icon: Icons.zoom_plus,
  24214. click: handleCartesian
  24215. };
  24216. modeBarButtons.zoomOut2d = {
  24217. name: 'zoomOut2d',
  24218. title: function(gd) { return _(gd, 'Zoom out'); },
  24219. attr: 'zoom',
  24220. val: 'out',
  24221. icon: Icons.zoom_minus,
  24222. click: handleCartesian
  24223. };
  24224. modeBarButtons.autoScale2d = {
  24225. name: 'autoScale2d',
  24226. title: function(gd) { return _(gd, 'Autoscale'); },
  24227. attr: 'zoom',
  24228. val: 'auto',
  24229. icon: Icons.autoscale,
  24230. click: handleCartesian
  24231. };
  24232. modeBarButtons.resetScale2d = {
  24233. name: 'resetScale2d',
  24234. title: function(gd) { return _(gd, 'Reset axes'); },
  24235. attr: 'zoom',
  24236. val: 'reset',
  24237. icon: Icons.home,
  24238. click: handleCartesian
  24239. };
  24240. modeBarButtons.hoverClosestCartesian = {
  24241. name: 'hoverClosestCartesian',
  24242. title: function(gd) { return _(gd, 'Show closest data on hover'); },
  24243. attr: 'hovermode',
  24244. val: 'closest',
  24245. icon: Icons.tooltip_basic,
  24246. gravity: 'ne',
  24247. click: handleCartesian
  24248. };
  24249. modeBarButtons.hoverCompareCartesian = {
  24250. name: 'hoverCompareCartesian',
  24251. title: function(gd) { return _(gd, 'Compare data on hover'); },
  24252. attr: 'hovermode',
  24253. val: function(gd) {
  24254. return gd._fullLayout._isHoriz ? 'y' : 'x';
  24255. },
  24256. icon: Icons.tooltip_compare,
  24257. gravity: 'ne',
  24258. click: handleCartesian
  24259. };
  24260. function handleCartesian(gd, ev) {
  24261. var button = ev.currentTarget;
  24262. var astr = button.getAttribute('data-attr');
  24263. var val = button.getAttribute('data-val') || true;
  24264. var fullLayout = gd._fullLayout;
  24265. var aobj = {};
  24266. var axList = axisIds.list(gd, null, true);
  24267. var allSpikesEnabled = 'on';
  24268. var ax, i;
  24269. if(astr === 'zoom') {
  24270. var mag = (val === 'in') ? 0.5 : 2;
  24271. var r0 = (1 + mag) / 2;
  24272. var r1 = (1 - mag) / 2;
  24273. var axName;
  24274. for(i = 0; i < axList.length; i++) {
  24275. ax = axList[i];
  24276. if(!ax.fixedrange) {
  24277. axName = ax._name;
  24278. if(val === 'auto') aobj[axName + '.autorange'] = true;
  24279. else if(val === 'reset') {
  24280. if(ax._rangeInitial === undefined) {
  24281. aobj[axName + '.autorange'] = true;
  24282. }
  24283. else {
  24284. var rangeInitial = ax._rangeInitial.slice();
  24285. aobj[axName + '.range[0]'] = rangeInitial[0];
  24286. aobj[axName + '.range[1]'] = rangeInitial[1];
  24287. }
  24288. if(ax._showSpikeInitial !== undefined) {
  24289. aobj[axName + '.showspikes'] = ax._showSpikeInitial;
  24290. if(allSpikesEnabled === 'on' && !ax._showSpikeInitial) {
  24291. allSpikesEnabled = 'off';
  24292. }
  24293. }
  24294. }
  24295. else {
  24296. var rangeNow = [
  24297. ax.r2l(ax.range[0]),
  24298. ax.r2l(ax.range[1]),
  24299. ];
  24300. var rangeNew = [
  24301. r0 * rangeNow[0] + r1 * rangeNow[1],
  24302. r0 * rangeNow[1] + r1 * rangeNow[0]
  24303. ];
  24304. aobj[axName + '.range[0]'] = ax.l2r(rangeNew[0]);
  24305. aobj[axName + '.range[1]'] = ax.l2r(rangeNew[1]);
  24306. }
  24307. }
  24308. }
  24309. fullLayout._cartesianSpikesEnabled = allSpikesEnabled;
  24310. }
  24311. else {
  24312. // if ALL traces have orientation 'h', 'hovermode': 'x' otherwise: 'y'
  24313. if(astr === 'hovermode' && (val === 'x' || val === 'y')) {
  24314. val = fullLayout._isHoriz ? 'y' : 'x';
  24315. button.setAttribute('data-val', val);
  24316. } else if(astr === 'hovermode' && val === 'closest') {
  24317. for(i = 0; i < axList.length; i++) {
  24318. ax = axList[i];
  24319. if(allSpikesEnabled === 'on' && !ax.showspikes) {
  24320. allSpikesEnabled = 'off';
  24321. }
  24322. }
  24323. fullLayout._cartesianSpikesEnabled = allSpikesEnabled;
  24324. }
  24325. aobj[astr] = val;
  24326. }
  24327. Registry.call('_guiRelayout', gd, aobj);
  24328. }
  24329. modeBarButtons.zoom3d = {
  24330. name: 'zoom3d',
  24331. title: function(gd) { return _(gd, 'Zoom'); },
  24332. attr: 'scene.dragmode',
  24333. val: 'zoom',
  24334. icon: Icons.zoombox,
  24335. click: handleDrag3d
  24336. };
  24337. modeBarButtons.pan3d = {
  24338. name: 'pan3d',
  24339. title: function(gd) { return _(gd, 'Pan'); },
  24340. attr: 'scene.dragmode',
  24341. val: 'pan',
  24342. icon: Icons.pan,
  24343. click: handleDrag3d
  24344. };
  24345. modeBarButtons.orbitRotation = {
  24346. name: 'orbitRotation',
  24347. title: function(gd) { return _(gd, 'Orbital rotation'); },
  24348. attr: 'scene.dragmode',
  24349. val: 'orbit',
  24350. icon: Icons['3d_rotate'],
  24351. click: handleDrag3d
  24352. };
  24353. modeBarButtons.tableRotation = {
  24354. name: 'tableRotation',
  24355. title: function(gd) { return _(gd, 'Turntable rotation'); },
  24356. attr: 'scene.dragmode',
  24357. val: 'turntable',
  24358. icon: Icons['z-axis'],
  24359. click: handleDrag3d
  24360. };
  24361. function handleDrag3d(gd, ev) {
  24362. var button = ev.currentTarget;
  24363. var attr = button.getAttribute('data-attr');
  24364. var val = button.getAttribute('data-val') || true;
  24365. var sceneIds = gd._fullLayout._subplots.gl3d;
  24366. var layoutUpdate = {};
  24367. var parts = attr.split('.');
  24368. for(var i = 0; i < sceneIds.length; i++) {
  24369. layoutUpdate[sceneIds[i] + '.' + parts[1]] = val;
  24370. }
  24371. // for multi-type subplots
  24372. var val2d = (val === 'pan') ? val : 'zoom';
  24373. layoutUpdate.dragmode = val2d;
  24374. Registry.call('_guiRelayout', gd, layoutUpdate);
  24375. }
  24376. modeBarButtons.resetCameraDefault3d = {
  24377. name: 'resetCameraDefault3d',
  24378. title: function(gd) { return _(gd, 'Reset camera to default'); },
  24379. attr: 'resetDefault',
  24380. icon: Icons.home,
  24381. click: handleCamera3d
  24382. };
  24383. modeBarButtons.resetCameraLastSave3d = {
  24384. name: 'resetCameraLastSave3d',
  24385. title: function(gd) { return _(gd, 'Reset camera to last save'); },
  24386. attr: 'resetLastSave',
  24387. icon: Icons.movie,
  24388. click: handleCamera3d
  24389. };
  24390. function handleCamera3d(gd, ev) {
  24391. var button = ev.currentTarget;
  24392. var attr = button.getAttribute('data-attr');
  24393. var fullLayout = gd._fullLayout;
  24394. var sceneIds = fullLayout._subplots.gl3d;
  24395. var aobj = {};
  24396. for(var i = 0; i < sceneIds.length; i++) {
  24397. var sceneId = sceneIds[i];
  24398. var key = sceneId + '.camera';
  24399. var scene = fullLayout[sceneId]._scene;
  24400. if(attr === 'resetDefault') {
  24401. aobj[key] = null;
  24402. }
  24403. else if(attr === 'resetLastSave') {
  24404. aobj[key] = Lib.extendDeep({}, scene.cameraInitial);
  24405. }
  24406. }
  24407. Registry.call('_guiRelayout', gd, aobj);
  24408. }
  24409. modeBarButtons.hoverClosest3d = {
  24410. name: 'hoverClosest3d',
  24411. title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
  24412. attr: 'hovermode',
  24413. val: null,
  24414. toggle: true,
  24415. icon: Icons.tooltip_basic,
  24416. gravity: 'ne',
  24417. click: handleHover3d
  24418. };
  24419. function getNextHover3d(gd, ev) {
  24420. var button = ev.currentTarget;
  24421. var val = button._previousVal;
  24422. var fullLayout = gd._fullLayout;
  24423. var sceneIds = fullLayout._subplots.gl3d;
  24424. var axes = ['xaxis', 'yaxis', 'zaxis'];
  24425. // initialize 'current spike' object to be stored in the DOM
  24426. var currentSpikes = {};
  24427. var layoutUpdate = {};
  24428. if(val) {
  24429. layoutUpdate = val;
  24430. button._previousVal = null;
  24431. }
  24432. else {
  24433. for(var i = 0; i < sceneIds.length; i++) {
  24434. var sceneId = sceneIds[i];
  24435. var sceneLayout = fullLayout[sceneId];
  24436. var hovermodeAStr = sceneId + '.hovermode';
  24437. currentSpikes[hovermodeAStr] = sceneLayout.hovermode;
  24438. layoutUpdate[hovermodeAStr] = false;
  24439. // copy all the current spike attrs
  24440. for(var j = 0; j < 3; j++) {
  24441. var axis = axes[j];
  24442. var spikeAStr = sceneId + '.' + axis + '.showspikes';
  24443. layoutUpdate[spikeAStr] = false;
  24444. currentSpikes[spikeAStr] = sceneLayout[axis].showspikes;
  24445. }
  24446. }
  24447. button._previousVal = currentSpikes;
  24448. }
  24449. return layoutUpdate;
  24450. }
  24451. function handleHover3d(gd, ev) {
  24452. var layoutUpdate = getNextHover3d(gd, ev);
  24453. Registry.call('_guiRelayout', gd, layoutUpdate);
  24454. }
  24455. modeBarButtons.zoomInGeo = {
  24456. name: 'zoomInGeo',
  24457. title: function(gd) { return _(gd, 'Zoom in'); },
  24458. attr: 'zoom',
  24459. val: 'in',
  24460. icon: Icons.zoom_plus,
  24461. click: handleGeo
  24462. };
  24463. modeBarButtons.zoomOutGeo = {
  24464. name: 'zoomOutGeo',
  24465. title: function(gd) { return _(gd, 'Zoom out'); },
  24466. attr: 'zoom',
  24467. val: 'out',
  24468. icon: Icons.zoom_minus,
  24469. click: handleGeo
  24470. };
  24471. modeBarButtons.resetGeo = {
  24472. name: 'resetGeo',
  24473. title: function(gd) { return _(gd, 'Reset'); },
  24474. attr: 'reset',
  24475. val: null,
  24476. icon: Icons.autoscale,
  24477. click: handleGeo
  24478. };
  24479. modeBarButtons.hoverClosestGeo = {
  24480. name: 'hoverClosestGeo',
  24481. title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
  24482. attr: 'hovermode',
  24483. val: null,
  24484. toggle: true,
  24485. icon: Icons.tooltip_basic,
  24486. gravity: 'ne',
  24487. click: toggleHover
  24488. };
  24489. function handleGeo(gd, ev) {
  24490. var button = ev.currentTarget;
  24491. var attr = button.getAttribute('data-attr');
  24492. var val = button.getAttribute('data-val') || true;
  24493. var fullLayout = gd._fullLayout;
  24494. var geoIds = fullLayout._subplots.geo;
  24495. for(var i = 0; i < geoIds.length; i++) {
  24496. var id = geoIds[i];
  24497. var geoLayout = fullLayout[id];
  24498. if(attr === 'zoom') {
  24499. var scale = geoLayout.projection.scale;
  24500. var newScale = (val === 'in') ? 2 * scale : 0.5 * scale;
  24501. Registry.call('_guiRelayout', gd, id + '.projection.scale', newScale);
  24502. } else if(attr === 'reset') {
  24503. resetView(gd, 'geo');
  24504. }
  24505. }
  24506. }
  24507. modeBarButtons.hoverClosestGl2d = {
  24508. name: 'hoverClosestGl2d',
  24509. title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
  24510. attr: 'hovermode',
  24511. val: null,
  24512. toggle: true,
  24513. icon: Icons.tooltip_basic,
  24514. gravity: 'ne',
  24515. click: toggleHover
  24516. };
  24517. modeBarButtons.hoverClosestPie = {
  24518. name: 'hoverClosestPie',
  24519. title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
  24520. attr: 'hovermode',
  24521. val: 'closest',
  24522. icon: Icons.tooltip_basic,
  24523. gravity: 'ne',
  24524. click: toggleHover
  24525. };
  24526. function getNextHover(gd) {
  24527. var fullLayout = gd._fullLayout;
  24528. if(fullLayout.hovermode) return false;
  24529. if(fullLayout._has('cartesian')) {
  24530. return fullLayout._isHoriz ? 'y' : 'x';
  24531. }
  24532. return 'closest';
  24533. }
  24534. function toggleHover(gd) {
  24535. var newHover = getNextHover(gd);
  24536. Registry.call('_guiRelayout', gd, 'hovermode', newHover);
  24537. }
  24538. // buttons when more then one plot types are present
  24539. modeBarButtons.toggleHover = {
  24540. name: 'toggleHover',
  24541. title: function(gd) { return _(gd, 'Toggle show closest data on hover'); },
  24542. attr: 'hovermode',
  24543. val: null,
  24544. toggle: true,
  24545. icon: Icons.tooltip_basic,
  24546. gravity: 'ne',
  24547. click: function(gd, ev) {
  24548. var layoutUpdate = getNextHover3d(gd, ev);
  24549. layoutUpdate.hovermode = getNextHover(gd);
  24550. Registry.call('_guiRelayout', gd, layoutUpdate);
  24551. }
  24552. };
  24553. modeBarButtons.resetViews = {
  24554. name: 'resetViews',
  24555. title: function(gd) { return _(gd, 'Reset views'); },
  24556. icon: Icons.home,
  24557. click: function(gd, ev) {
  24558. var button = ev.currentTarget;
  24559. button.setAttribute('data-attr', 'zoom');
  24560. button.setAttribute('data-val', 'reset');
  24561. handleCartesian(gd, ev);
  24562. button.setAttribute('data-attr', 'resetLastSave');
  24563. handleCamera3d(gd, ev);
  24564. resetView(gd, 'geo');
  24565. resetView(gd, 'mapbox');
  24566. }
  24567. };
  24568. modeBarButtons.toggleSpikelines = {
  24569. name: 'toggleSpikelines',
  24570. title: function(gd) { return _(gd, 'Toggle Spike Lines'); },
  24571. icon: Icons.spikeline,
  24572. attr: '_cartesianSpikesEnabled',
  24573. val: 'on',
  24574. click: function(gd) {
  24575. var fullLayout = gd._fullLayout;
  24576. fullLayout._cartesianSpikesEnabled = fullLayout._cartesianSpikesEnabled === 'on' ? 'off' : 'on';
  24577. var aobj = setSpikelineVisibility(gd);
  24578. Registry.call('_guiRelayout', gd, aobj);
  24579. }
  24580. };
  24581. function setSpikelineVisibility(gd) {
  24582. var fullLayout = gd._fullLayout;
  24583. var axList = axisIds.list(gd, null, true);
  24584. var aobj = {};
  24585. var ax, axName;
  24586. for(var i = 0; i < axList.length; i++) {
  24587. ax = axList[i];
  24588. axName = ax._name;
  24589. aobj[axName + '.showspikes'] = fullLayout._cartesianSpikesEnabled === 'on' ? true : ax._showSpikeInitial;
  24590. }
  24591. return aobj;
  24592. }
  24593. modeBarButtons.resetViewMapbox = {
  24594. name: 'resetViewMapbox',
  24595. title: function(gd) { return _(gd, 'Reset view'); },
  24596. attr: 'reset',
  24597. icon: Icons.home,
  24598. click: function(gd) {
  24599. resetView(gd, 'mapbox');
  24600. }
  24601. };
  24602. function resetView(gd, subplotType) {
  24603. var fullLayout = gd._fullLayout;
  24604. var subplotIds = fullLayout._subplots[subplotType];
  24605. var aObj = {};
  24606. for(var i = 0; i < subplotIds.length; i++) {
  24607. var id = subplotIds[i];
  24608. var subplotObj = fullLayout[id]._subplot;
  24609. var viewInitial = subplotObj.viewInitial;
  24610. var viewKeys = Object.keys(viewInitial);
  24611. for(var j = 0; j < viewKeys.length; j++) {
  24612. var key = viewKeys[j];
  24613. aObj[id + '.' + key] = viewInitial[key];
  24614. }
  24615. }
  24616. Registry.call('_guiRelayout', gd, aObj);
  24617. }
  24618. },{"../../../build/ploticon":2,"../../lib":168,"../../plots/cartesian/axis_ids":215,"../../plots/plots":245,"../../registry":257}],110:[function(_dereq_,module,exports){
  24619. /**
  24620. * Copyright 2012-2019, Plotly, Inc.
  24621. * All rights reserved.
  24622. *
  24623. * This source code is licensed under the MIT license found in the
  24624. * LICENSE file in the root directory of this source tree.
  24625. */
  24626. 'use strict';
  24627. exports.manage = _dereq_('./manage');
  24628. },{"./manage":111}],111:[function(_dereq_,module,exports){
  24629. /**
  24630. * Copyright 2012-2019, Plotly, Inc.
  24631. * All rights reserved.
  24632. *
  24633. * This source code is licensed under the MIT license found in the
  24634. * LICENSE file in the root directory of this source tree.
  24635. */
  24636. 'use strict';
  24637. var axisIds = _dereq_('../../plots/cartesian/axis_ids');
  24638. var scatterSubTypes = _dereq_('../../traces/scatter/subtypes');
  24639. var Registry = _dereq_('../../registry');
  24640. var createModeBar = _dereq_('./modebar');
  24641. var modeBarButtons = _dereq_('./buttons');
  24642. /**
  24643. * ModeBar wrapper around 'create' and 'update',
  24644. * chooses buttons to pass to ModeBar constructor based on
  24645. * plot type and plot config.
  24646. *
  24647. * @param {object} gd main plot object
  24648. *
  24649. */
  24650. module.exports = function manageModeBar(gd) {
  24651. var fullLayout = gd._fullLayout;
  24652. var context = gd._context;
  24653. var modeBar = fullLayout._modeBar;
  24654. if(!context.displayModeBar && !context.watermark) {
  24655. if(modeBar) {
  24656. modeBar.destroy();
  24657. delete fullLayout._modeBar;
  24658. }
  24659. return;
  24660. }
  24661. if(!Array.isArray(context.modeBarButtonsToRemove)) {
  24662. throw new Error([
  24663. '*modeBarButtonsToRemove* configuration options',
  24664. 'must be an array.'
  24665. ].join(' '));
  24666. }
  24667. if(!Array.isArray(context.modeBarButtonsToAdd)) {
  24668. throw new Error([
  24669. '*modeBarButtonsToAdd* configuration options',
  24670. 'must be an array.'
  24671. ].join(' '));
  24672. }
  24673. var customButtons = context.modeBarButtons;
  24674. var buttonGroups;
  24675. if(Array.isArray(customButtons) && customButtons.length) {
  24676. buttonGroups = fillCustomButton(customButtons);
  24677. }
  24678. else if(!context.displayModeBar && context.watermark) {
  24679. buttonGroups = [];
  24680. }
  24681. else {
  24682. buttonGroups = getButtonGroups(
  24683. gd,
  24684. context.modeBarButtonsToRemove,
  24685. context.modeBarButtonsToAdd,
  24686. context.showSendToCloud
  24687. );
  24688. }
  24689. if(modeBar) modeBar.update(gd, buttonGroups);
  24690. else fullLayout._modeBar = createModeBar(gd, buttonGroups);
  24691. };
  24692. // logic behind which buttons are displayed by default
  24693. function getButtonGroups(gd, buttonsToRemove, buttonsToAdd, showSendToCloud) {
  24694. var fullLayout = gd._fullLayout;
  24695. var fullData = gd._fullData;
  24696. var hasCartesian = fullLayout._has('cartesian');
  24697. var hasGL3D = fullLayout._has('gl3d');
  24698. var hasGeo = fullLayout._has('geo');
  24699. var hasPie = fullLayout._has('pie');
  24700. var hasGL2D = fullLayout._has('gl2d');
  24701. var hasTernary = fullLayout._has('ternary');
  24702. var hasMapbox = fullLayout._has('mapbox');
  24703. var hasPolar = fullLayout._has('polar');
  24704. var allAxesFixed = areAllAxesFixed(fullLayout);
  24705. var groups = [];
  24706. function addGroup(newGroup) {
  24707. if(!newGroup.length) return;
  24708. var out = [];
  24709. for(var i = 0; i < newGroup.length; i++) {
  24710. var button = newGroup[i];
  24711. if(buttonsToRemove.indexOf(button) !== -1) continue;
  24712. out.push(modeBarButtons[button]);
  24713. }
  24714. groups.push(out);
  24715. }
  24716. // buttons common to all plot types
  24717. var commonGroup = ['toImage'];
  24718. if(showSendToCloud) commonGroup.push('sendDataToCloud');
  24719. addGroup(commonGroup);
  24720. var zoomGroup = [];
  24721. var hoverGroup = [];
  24722. var resetGroup = [];
  24723. var dragModeGroup = [];
  24724. if((hasCartesian || hasGL2D || hasPie || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasPolar > 1) {
  24725. // graphs with more than one plot types get 'union buttons'
  24726. // which reset the view or toggle hover labels across all subplots.
  24727. hoverGroup = ['toggleHover'];
  24728. resetGroup = ['resetViews'];
  24729. }
  24730. else if(hasGeo) {
  24731. zoomGroup = ['zoomInGeo', 'zoomOutGeo'];
  24732. hoverGroup = ['hoverClosestGeo'];
  24733. resetGroup = ['resetGeo'];
  24734. }
  24735. else if(hasGL3D) {
  24736. hoverGroup = ['hoverClosest3d'];
  24737. resetGroup = ['resetCameraDefault3d', 'resetCameraLastSave3d'];
  24738. }
  24739. else if(hasMapbox) {
  24740. hoverGroup = ['toggleHover'];
  24741. resetGroup = ['resetViewMapbox'];
  24742. }
  24743. else if(hasGL2D) {
  24744. hoverGroup = ['hoverClosestGl2d'];
  24745. }
  24746. else if(hasPie) {
  24747. hoverGroup = ['hoverClosestPie'];
  24748. }
  24749. else { // hasPolar, hasTernary
  24750. // always show at least one hover icon.
  24751. hoverGroup = ['toggleHover'];
  24752. }
  24753. // if we have cartesian, allow switching between closest and compare
  24754. // regardless of what other types are on the plot, since they'll all
  24755. // just treat any truthy hovermode as 'closest'
  24756. if(hasCartesian) {
  24757. hoverGroup = ['toggleSpikelines', 'hoverClosestCartesian', 'hoverCompareCartesian'];
  24758. }
  24759. if((hasCartesian || hasGL2D) && !allAxesFixed) {
  24760. zoomGroup = ['zoomIn2d', 'zoomOut2d', 'autoScale2d'];
  24761. if(resetGroup[0] !== 'resetViews') resetGroup = ['resetScale2d'];
  24762. }
  24763. if(hasGL3D) {
  24764. dragModeGroup = ['zoom3d', 'pan3d', 'orbitRotation', 'tableRotation'];
  24765. }
  24766. else if(((hasCartesian || hasGL2D) && !allAxesFixed) || hasTernary) {
  24767. dragModeGroup = ['zoom2d', 'pan2d'];
  24768. }
  24769. else if(hasMapbox || hasGeo) {
  24770. dragModeGroup = ['pan2d'];
  24771. }
  24772. else if(hasPolar) {
  24773. dragModeGroup = ['zoom2d'];
  24774. }
  24775. if(isSelectable(fullData)) {
  24776. dragModeGroup.push('select2d', 'lasso2d');
  24777. }
  24778. addGroup(dragModeGroup);
  24779. addGroup(zoomGroup.concat(resetGroup));
  24780. addGroup(hoverGroup);
  24781. return appendButtonsToGroups(groups, buttonsToAdd);
  24782. }
  24783. function areAllAxesFixed(fullLayout) {
  24784. var axList = axisIds.list({_fullLayout: fullLayout}, null, true);
  24785. for(var i = 0; i < axList.length; i++) {
  24786. if(!axList[i].fixedrange) {
  24787. return false;
  24788. }
  24789. }
  24790. return true;
  24791. }
  24792. // look for traces that support selection
  24793. // to be updated as we add more selectPoints handlers
  24794. function isSelectable(fullData) {
  24795. var selectable = false;
  24796. for(var i = 0; i < fullData.length; i++) {
  24797. if(selectable) break;
  24798. var trace = fullData[i];
  24799. if(!trace._module || !trace._module.selectPoints) continue;
  24800. if(Registry.traceIs(trace, 'scatter-like')) {
  24801. if(scatterSubTypes.hasMarkers(trace) || scatterSubTypes.hasText(trace)) {
  24802. selectable = true;
  24803. }
  24804. } else if(Registry.traceIs(trace, 'box-violin')) {
  24805. if(trace.boxpoints === 'all' || trace.points === 'all') {
  24806. selectable = true;
  24807. }
  24808. }
  24809. // assume that in general if the trace module has selectPoints,
  24810. // then it's selectable. Scatter is an exception to this because it must
  24811. // have markers or text, not just be a scatter type.
  24812. else selectable = true;
  24813. }
  24814. return selectable;
  24815. }
  24816. function appendButtonsToGroups(groups, buttons) {
  24817. if(buttons.length) {
  24818. if(Array.isArray(buttons[0])) {
  24819. for(var i = 0; i < buttons.length; i++) {
  24820. groups.push(buttons[i]);
  24821. }
  24822. }
  24823. else groups.push(buttons);
  24824. }
  24825. return groups;
  24826. }
  24827. // fill in custom buttons referring to default mode bar buttons
  24828. function fillCustomButton(customButtons) {
  24829. for(var i = 0; i < customButtons.length; i++) {
  24830. var buttonGroup = customButtons[i];
  24831. for(var j = 0; j < buttonGroup.length; j++) {
  24832. var button = buttonGroup[j];
  24833. if(typeof button === 'string') {
  24834. if(modeBarButtons[button] !== undefined) {
  24835. customButtons[i][j] = modeBarButtons[button];
  24836. }
  24837. else {
  24838. throw new Error([
  24839. '*modeBarButtons* configuration options',
  24840. 'invalid button name'
  24841. ].join(' '));
  24842. }
  24843. }
  24844. }
  24845. }
  24846. return customButtons;
  24847. }
  24848. },{"../../plots/cartesian/axis_ids":215,"../../registry":257,"../../traces/scatter/subtypes":391,"./buttons":109,"./modebar":112}],112:[function(_dereq_,module,exports){
  24849. /**
  24850. * Copyright 2012-2019, Plotly, Inc.
  24851. * All rights reserved.
  24852. *
  24853. * This source code is licensed under the MIT license found in the
  24854. * LICENSE file in the root directory of this source tree.
  24855. */
  24856. 'use strict';
  24857. var d3 = _dereq_('d3');
  24858. var isNumeric = _dereq_('fast-isnumeric');
  24859. var Lib = _dereq_('../../lib');
  24860. var Icons = _dereq_('../../../build/ploticon');
  24861. var Parser = new DOMParser();
  24862. /**
  24863. * UI controller for interactive plots
  24864. * @Class
  24865. * @Param {object} opts
  24866. * @Param {object} opts.buttons nested arrays of grouped buttons config objects
  24867. * @Param {object} opts.container container div to append modeBar
  24868. * @Param {object} opts.graphInfo primary plot object containing data and layout
  24869. */
  24870. function ModeBar(opts) {
  24871. this.container = opts.container;
  24872. this.element = document.createElement('div');
  24873. this.update(opts.graphInfo, opts.buttons);
  24874. this.container.appendChild(this.element);
  24875. }
  24876. var proto = ModeBar.prototype;
  24877. /**
  24878. * Update modeBar (buttons and logo)
  24879. *
  24880. * @param {object} graphInfo primary plot object containing data and layout
  24881. * @param {array of arrays} buttons nested arrays of grouped buttons to initialize
  24882. *
  24883. */
  24884. proto.update = function(graphInfo, buttons) {
  24885. this.graphInfo = graphInfo;
  24886. var context = this.graphInfo._context;
  24887. var fullLayout = this.graphInfo._fullLayout;
  24888. var modeBarId = 'modebar-' + fullLayout._uid;
  24889. this.element.setAttribute('id', modeBarId);
  24890. this._uid = modeBarId;
  24891. this.element.className = 'modebar';
  24892. if(context.displayModeBar === 'hover') this.element.className += ' modebar--hover ease-bg';
  24893. if(fullLayout.modebar.orientation === 'v') {
  24894. this.element.className += ' vertical';
  24895. buttons = buttons.reverse();
  24896. }
  24897. var style = fullLayout.modebar;
  24898. var bgSelector = context.displayModeBar === 'hover' ? '.js-plotly-plot .plotly:hover ' : '';
  24899. Lib.deleteRelatedStyleRule(modeBarId);
  24900. Lib.addRelatedStyleRule(modeBarId, bgSelector + '#' + modeBarId, 'background-color: ' + style.bgcolor);
  24901. Lib.addRelatedStyleRule(modeBarId, '#' + modeBarId + ' .modebar-btn .icon path', 'fill: ' + style.color);
  24902. Lib.addRelatedStyleRule(modeBarId, '#' + modeBarId + ' .modebar-btn:hover .icon path', 'fill: ' + style.activecolor);
  24903. Lib.addRelatedStyleRule(modeBarId, '#' + modeBarId + ' .modebar-btn.active .icon path', 'fill: ' + style.activecolor);
  24904. // if buttons or logo have changed, redraw modebar interior
  24905. var needsNewButtons = !this.hasButtons(buttons);
  24906. var needsNewLogo = (this.hasLogo !== context.displaylogo);
  24907. var needsNewLocale = (this.locale !== context.locale);
  24908. this.locale = context.locale;
  24909. if(needsNewButtons || needsNewLogo || needsNewLocale) {
  24910. this.removeAllButtons();
  24911. this.updateButtons(buttons);
  24912. if(context.watermark || context.displaylogo) {
  24913. var logoGroup = this.getLogo();
  24914. if(context.watermark) {
  24915. logoGroup.className = logoGroup.className + ' watermark';
  24916. }
  24917. if(fullLayout.modebar.orientation === 'v') {
  24918. this.element.insertBefore(logoGroup, this.element.childNodes[0]);
  24919. } else {
  24920. this.element.appendChild(logoGroup);
  24921. }
  24922. this.hasLogo = true;
  24923. }
  24924. }
  24925. this.updateActiveButton();
  24926. };
  24927. proto.updateButtons = function(buttons) {
  24928. var _this = this;
  24929. this.buttons = buttons;
  24930. this.buttonElements = [];
  24931. this.buttonsNames = [];
  24932. this.buttons.forEach(function(buttonGroup) {
  24933. var group = _this.createGroup();
  24934. buttonGroup.forEach(function(buttonConfig) {
  24935. var buttonName = buttonConfig.name;
  24936. if(!buttonName) {
  24937. throw new Error('must provide button \'name\' in button config');
  24938. }
  24939. if(_this.buttonsNames.indexOf(buttonName) !== -1) {
  24940. throw new Error('button name \'' + buttonName + '\' is taken');
  24941. }
  24942. _this.buttonsNames.push(buttonName);
  24943. var button = _this.createButton(buttonConfig);
  24944. _this.buttonElements.push(button);
  24945. group.appendChild(button);
  24946. });
  24947. _this.element.appendChild(group);
  24948. });
  24949. };
  24950. /**
  24951. * Empty div for containing a group of buttons
  24952. * @Return {HTMLelement}
  24953. */
  24954. proto.createGroup = function() {
  24955. var group = document.createElement('div');
  24956. group.className = 'modebar-group';
  24957. return group;
  24958. };
  24959. /**
  24960. * Create a new button div and set constant and configurable attributes
  24961. * @Param {object} config (see ./buttons.js for more info)
  24962. * @Return {HTMLelement}
  24963. */
  24964. proto.createButton = function(config) {
  24965. var _this = this;
  24966. var button = document.createElement('a');
  24967. button.setAttribute('rel', 'tooltip');
  24968. button.className = 'modebar-btn';
  24969. var title = config.title;
  24970. if(title === undefined) title = config.name;
  24971. // for localization: allow title to be a callable that takes gd as arg
  24972. else if(typeof title === 'function') title = title(this.graphInfo);
  24973. if(title || title === 0) button.setAttribute('data-title', title);
  24974. if(config.attr !== undefined) button.setAttribute('data-attr', config.attr);
  24975. var val = config.val;
  24976. if(val !== undefined) {
  24977. if(typeof val === 'function') val = val(this.graphInfo);
  24978. button.setAttribute('data-val', val);
  24979. }
  24980. var click = config.click;
  24981. if(typeof click !== 'function') {
  24982. throw new Error('must provide button \'click\' function in button config');
  24983. }
  24984. else {
  24985. button.addEventListener('click', function(ev) {
  24986. config.click(_this.graphInfo, ev);
  24987. // only needed for 'hoverClosestGeo' which does not call relayout
  24988. _this.updateActiveButton(ev.currentTarget);
  24989. });
  24990. }
  24991. button.setAttribute('data-toggle', config.toggle || false);
  24992. if(config.toggle) d3.select(button).classed('active', true);
  24993. var icon = config.icon;
  24994. if(typeof icon === 'function') {
  24995. button.appendChild(icon());
  24996. }
  24997. else {
  24998. button.appendChild(this.createIcon(icon || Icons.question));
  24999. }
  25000. button.setAttribute('data-gravity', config.gravity || 'n');
  25001. return button;
  25002. };
  25003. /**
  25004. * Add an icon to a button
  25005. * @Param {object} thisIcon
  25006. * @Param {number} thisIcon.width
  25007. * @Param {string} thisIcon.path
  25008. * @Param {string} thisIcon.color
  25009. * @Return {HTMLelement}
  25010. */
  25011. proto.createIcon = function(thisIcon) {
  25012. var iconHeight = isNumeric(thisIcon.height) ?
  25013. Number(thisIcon.height) :
  25014. thisIcon.ascent - thisIcon.descent;
  25015. var svgNS = 'http://www.w3.org/2000/svg';
  25016. var icon;
  25017. if(thisIcon.path) {
  25018. icon = document.createElementNS(svgNS, 'svg');
  25019. icon.setAttribute('viewBox', [0, 0, thisIcon.width, iconHeight].join(' '));
  25020. icon.setAttribute('class', 'icon');
  25021. var path = document.createElementNS(svgNS, 'path');
  25022. path.setAttribute('d', thisIcon.path);
  25023. if(thisIcon.transform) {
  25024. path.setAttribute('transform', thisIcon.transform);
  25025. }
  25026. else if(thisIcon.ascent !== undefined) {
  25027. // Legacy icon transform calculation
  25028. path.setAttribute('transform', 'matrix(1 0 0 -1 0 ' + thisIcon.ascent + ')');
  25029. }
  25030. icon.appendChild(path);
  25031. }
  25032. if(thisIcon.svg) {
  25033. var svgDoc = Parser.parseFromString(thisIcon.svg, 'application/xml');
  25034. icon = svgDoc.childNodes[0];
  25035. }
  25036. icon.setAttribute('height', '1em');
  25037. icon.setAttribute('width', '1em');
  25038. return icon;
  25039. };
  25040. /**
  25041. * Updates active button with attribute specified in layout
  25042. * @Param {object} graphInfo plot object containing data and layout
  25043. * @Return {HTMLelement}
  25044. */
  25045. proto.updateActiveButton = function(buttonClicked) {
  25046. var fullLayout = this.graphInfo._fullLayout;
  25047. var dataAttrClicked = (buttonClicked !== undefined) ?
  25048. buttonClicked.getAttribute('data-attr') :
  25049. null;
  25050. this.buttonElements.forEach(function(button) {
  25051. var thisval = button.getAttribute('data-val') || true;
  25052. var dataAttr = button.getAttribute('data-attr');
  25053. var isToggleButton = (button.getAttribute('data-toggle') === 'true');
  25054. var button3 = d3.select(button);
  25055. // Use 'data-toggle' and 'buttonClicked' to toggle buttons
  25056. // that have no one-to-one equivalent in fullLayout
  25057. if(isToggleButton) {
  25058. if(dataAttr === dataAttrClicked) {
  25059. button3.classed('active', !button3.classed('active'));
  25060. }
  25061. }
  25062. else {
  25063. var val = (dataAttr === null) ?
  25064. dataAttr :
  25065. Lib.nestedProperty(fullLayout, dataAttr).get();
  25066. button3.classed('active', val === thisval);
  25067. }
  25068. });
  25069. };
  25070. /**
  25071. * Check if modeBar is configured as button configuration argument
  25072. *
  25073. * @Param {object} buttons 2d array of grouped button config objects
  25074. * @Return {boolean}
  25075. */
  25076. proto.hasButtons = function(buttons) {
  25077. var currentButtons = this.buttons;
  25078. if(!currentButtons) return false;
  25079. if(buttons.length !== currentButtons.length) return false;
  25080. for(var i = 0; i < buttons.length; ++i) {
  25081. if(buttons[i].length !== currentButtons[i].length) return false;
  25082. for(var j = 0; j < buttons[i].length; j++) {
  25083. if(buttons[i][j].name !== currentButtons[i][j].name) return false;
  25084. }
  25085. }
  25086. return true;
  25087. };
  25088. /**
  25089. * @return {HTMLDivElement} The logo image wrapped in a group
  25090. */
  25091. proto.getLogo = function() {
  25092. var group = this.createGroup();
  25093. var a = document.createElement('a');
  25094. a.href = 'https://plot.ly/';
  25095. a.target = '_blank';
  25096. a.setAttribute('data-title', Lib._(this.graphInfo, 'Produced with Plotly'));
  25097. a.className = 'modebar-btn plotlyjsicon modebar-btn--logo';
  25098. a.appendChild(this.createIcon(Icons.newplotlylogo));
  25099. group.appendChild(a);
  25100. return group;
  25101. };
  25102. proto.removeAllButtons = function() {
  25103. while(this.element.firstChild) {
  25104. this.element.removeChild(this.element.firstChild);
  25105. }
  25106. this.hasLogo = false;
  25107. };
  25108. proto.destroy = function() {
  25109. Lib.removeElement(this.container.querySelector('.modebar'));
  25110. Lib.deleteRelatedStyleRule(this._uid);
  25111. };
  25112. function createModeBar(gd, buttons) {
  25113. var fullLayout = gd._fullLayout;
  25114. var modeBar = new ModeBar({
  25115. graphInfo: gd,
  25116. container: fullLayout._paperdiv.node(),
  25117. buttons: buttons
  25118. });
  25119. if(fullLayout._privateplot) {
  25120. d3.select(modeBar.element).append('span')
  25121. .classed('badge-private float--left', true)
  25122. .text('PRIVATE');
  25123. }
  25124. return modeBar;
  25125. }
  25126. module.exports = createModeBar;
  25127. },{"../../../build/ploticon":2,"../../lib":168,"d3":16,"fast-isnumeric":18}],113:[function(_dereq_,module,exports){
  25128. /**
  25129. * Copyright 2012-2019, Plotly, Inc.
  25130. * All rights reserved.
  25131. *
  25132. * This source code is licensed under the MIT license found in the
  25133. * LICENSE file in the root directory of this source tree.
  25134. */
  25135. 'use strict';
  25136. var fontAttrs = _dereq_('../../plots/font_attributes');
  25137. var colorAttrs = _dereq_('../color/attributes');
  25138. var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;
  25139. var buttonAttrs = templatedArray('button', {
  25140. visible: {
  25141. valType: 'boolean',
  25142. dflt: true,
  25143. editType: 'plot',
  25144. },
  25145. step: {
  25146. valType: 'enumerated',
  25147. values: ['month', 'year', 'day', 'hour', 'minute', 'second', 'all'],
  25148. dflt: 'month',
  25149. editType: 'plot',
  25150. },
  25151. stepmode: {
  25152. valType: 'enumerated',
  25153. values: ['backward', 'todate'],
  25154. dflt: 'backward',
  25155. editType: 'plot',
  25156. },
  25157. count: {
  25158. valType: 'number',
  25159. min: 0,
  25160. dflt: 1,
  25161. editType: 'plot',
  25162. },
  25163. label: {
  25164. valType: 'string',
  25165. editType: 'plot',
  25166. },
  25167. editType: 'plot',
  25168. });
  25169. module.exports = {
  25170. visible: {
  25171. valType: 'boolean',
  25172. editType: 'plot',
  25173. },
  25174. buttons: buttonAttrs,
  25175. x: {
  25176. valType: 'number',
  25177. min: -2,
  25178. max: 3,
  25179. editType: 'plot',
  25180. },
  25181. xanchor: {
  25182. valType: 'enumerated',
  25183. values: ['auto', 'left', 'center', 'right'],
  25184. dflt: 'left',
  25185. editType: 'plot',
  25186. },
  25187. y: {
  25188. valType: 'number',
  25189. min: -2,
  25190. max: 3,
  25191. editType: 'plot',
  25192. },
  25193. yanchor: {
  25194. valType: 'enumerated',
  25195. values: ['auto', 'top', 'middle', 'bottom'],
  25196. dflt: 'bottom',
  25197. editType: 'plot',
  25198. },
  25199. font: fontAttrs({
  25200. editType: 'plot',
  25201. }),
  25202. bgcolor: {
  25203. valType: 'color',
  25204. dflt: colorAttrs.lightLine,
  25205. editType: 'plot',
  25206. },
  25207. activecolor: {
  25208. valType: 'color',
  25209. editType: 'plot',
  25210. },
  25211. bordercolor: {
  25212. valType: 'color',
  25213. dflt: colorAttrs.defaultLine,
  25214. editType: 'plot',
  25215. },
  25216. borderwidth: {
  25217. valType: 'number',
  25218. min: 0,
  25219. dflt: 0,
  25220. editType: 'plot',
  25221. },
  25222. editType: 'plot'
  25223. };
  25224. },{"../../plot_api/plot_template":202,"../../plots/font_attributes":239,"../color/attributes":50}],114:[function(_dereq_,module,exports){
  25225. /**
  25226. * Copyright 2012-2019, Plotly, Inc.
  25227. * All rights reserved.
  25228. *
  25229. * This source code is licensed under the MIT license found in the
  25230. * LICENSE file in the root directory of this source tree.
  25231. */
  25232. 'use strict';
  25233. module.exports = {
  25234. // 'y' position pad above counter axis domain
  25235. yPad: 0.02,
  25236. // minimum button width (regardless of text size)
  25237. minButtonWidth: 30,
  25238. // buttons rect radii
  25239. rx: 3,
  25240. ry: 3,
  25241. // light fraction used to compute the 'activecolor' default
  25242. lightAmount: 25,
  25243. darkAmount: 10
  25244. };
  25245. },{}],115:[function(_dereq_,module,exports){
  25246. /**
  25247. * Copyright 2012-2019, Plotly, Inc.
  25248. * All rights reserved.
  25249. *
  25250. * This source code is licensed under the MIT license found in the
  25251. * LICENSE file in the root directory of this source tree.
  25252. */
  25253. 'use strict';
  25254. var Lib = _dereq_('../../lib');
  25255. var Color = _dereq_('../color');
  25256. var Template = _dereq_('../../plot_api/plot_template');
  25257. var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');
  25258. var attributes = _dereq_('./attributes');
  25259. var constants = _dereq_('./constants');
  25260. module.exports = function handleDefaults(containerIn, containerOut, layout, counterAxes, calendar) {
  25261. var selectorIn = containerIn.rangeselector || {};
  25262. var selectorOut = Template.newContainer(containerOut, 'rangeselector');
  25263. function coerce(attr, dflt) {
  25264. return Lib.coerce(selectorIn, selectorOut, attributes, attr, dflt);
  25265. }
  25266. var buttons = handleArrayContainerDefaults(selectorIn, selectorOut, {
  25267. name: 'buttons',
  25268. handleItemDefaults: buttonDefaults,
  25269. calendar: calendar
  25270. });
  25271. var visible = coerce('visible', buttons.length > 0);
  25272. if(visible) {
  25273. var posDflt = getPosDflt(containerOut, layout, counterAxes);
  25274. coerce('x', posDflt[0]);
  25275. coerce('y', posDflt[1]);
  25276. Lib.noneOrAll(containerIn, containerOut, ['x', 'y']);
  25277. coerce('xanchor');
  25278. coerce('yanchor');
  25279. Lib.coerceFont(coerce, 'font', layout.font);
  25280. var bgColor = coerce('bgcolor');
  25281. coerce('activecolor', Color.contrast(bgColor, constants.lightAmount, constants.darkAmount));
  25282. coerce('bordercolor');
  25283. coerce('borderwidth');
  25284. }
  25285. };
  25286. function buttonDefaults(buttonIn, buttonOut, selectorOut, opts) {
  25287. var calendar = opts.calendar;
  25288. function coerce(attr, dflt) {
  25289. return Lib.coerce(buttonIn, buttonOut, attributes.buttons, attr, dflt);
  25290. }
  25291. var visible = coerce('visible');
  25292. if(visible) {
  25293. var step = coerce('step');
  25294. if(step !== 'all') {
  25295. if(calendar && calendar !== 'gregorian' && (step === 'month' || step === 'year')) {
  25296. buttonOut.stepmode = 'backward';
  25297. }
  25298. else {
  25299. coerce('stepmode');
  25300. }
  25301. coerce('count');
  25302. }
  25303. coerce('label');
  25304. }
  25305. }
  25306. function getPosDflt(containerOut, layout, counterAxes) {
  25307. var anchoredList = counterAxes.filter(function(ax) {
  25308. return layout[ax].anchor === containerOut._id;
  25309. });
  25310. var posY = 0;
  25311. for(var i = 0; i < anchoredList.length; i++) {
  25312. var domain = layout[anchoredList[i]].domain;
  25313. if(domain) posY = Math.max(domain[1], posY);
  25314. }
  25315. return [containerOut.domain[0], posY + constants.yPad];
  25316. }
  25317. },{"../../lib":168,"../../plot_api/plot_template":202,"../../plots/array_container_defaults":208,"../color":51,"./attributes":113,"./constants":114}],116:[function(_dereq_,module,exports){
  25318. /**
  25319. * Copyright 2012-2019, Plotly, Inc.
  25320. * All rights reserved.
  25321. *
  25322. * This source code is licensed under the MIT license found in the
  25323. * LICENSE file in the root directory of this source tree.
  25324. */
  25325. 'use strict';
  25326. var d3 = _dereq_('d3');
  25327. var Registry = _dereq_('../../registry');
  25328. var Plots = _dereq_('../../plots/plots');
  25329. var Color = _dereq_('../color');
  25330. var Drawing = _dereq_('../drawing');
  25331. var Lib = _dereq_('../../lib');
  25332. var svgTextUtils = _dereq_('../../lib/svg_text_utils');
  25333. var axisIds = _dereq_('../../plots/cartesian/axis_ids');
  25334. var alignmentConstants = _dereq_('../../constants/alignment');
  25335. var LINE_SPACING = alignmentConstants.LINE_SPACING;
  25336. var FROM_TL = alignmentConstants.FROM_TL;
  25337. var FROM_BR = alignmentConstants.FROM_BR;
  25338. var constants = _dereq_('./constants');
  25339. var getUpdateObject = _dereq_('./get_update_object');
  25340. module.exports = function draw(gd) {
  25341. var fullLayout = gd._fullLayout;
  25342. var selectors = fullLayout._infolayer.selectAll('.rangeselector')
  25343. .data(makeSelectorData(gd), selectorKeyFunc);
  25344. selectors.enter().append('g')
  25345. .classed('rangeselector', true);
  25346. selectors.exit().remove();
  25347. selectors.style({
  25348. cursor: 'pointer',
  25349. 'pointer-events': 'all'
  25350. });
  25351. selectors.each(function(d) {
  25352. var selector = d3.select(this);
  25353. var axisLayout = d;
  25354. var selectorLayout = axisLayout.rangeselector;
  25355. var buttons = selector.selectAll('g.button')
  25356. .data(Lib.filterVisible(selectorLayout.buttons));
  25357. buttons.enter().append('g')
  25358. .classed('button', true);
  25359. buttons.exit().remove();
  25360. buttons.each(function(d) {
  25361. var button = d3.select(this);
  25362. var update = getUpdateObject(axisLayout, d);
  25363. d._isActive = isActive(axisLayout, d, update);
  25364. button.call(drawButtonRect, selectorLayout, d);
  25365. button.call(drawButtonText, selectorLayout, d, gd);
  25366. button.on('click', function() {
  25367. if(gd._dragged) return;
  25368. Registry.call('_guiRelayout', gd, update);
  25369. });
  25370. button.on('mouseover', function() {
  25371. d._isHovered = true;
  25372. button.call(drawButtonRect, selectorLayout, d);
  25373. });
  25374. button.on('mouseout', function() {
  25375. d._isHovered = false;
  25376. button.call(drawButtonRect, selectorLayout, d);
  25377. });
  25378. });
  25379. reposition(gd, buttons, selectorLayout, axisLayout._name, selector);
  25380. });
  25381. };
  25382. function makeSelectorData(gd) {
  25383. var axes = axisIds.list(gd, 'x', true);
  25384. var data = [];
  25385. for(var i = 0; i < axes.length; i++) {
  25386. var axis = axes[i];
  25387. if(axis.rangeselector && axis.rangeselector.visible) {
  25388. data.push(axis);
  25389. }
  25390. }
  25391. return data;
  25392. }
  25393. function selectorKeyFunc(d) {
  25394. return d._id;
  25395. }
  25396. function isActive(axisLayout, opts, update) {
  25397. if(opts.step === 'all') {
  25398. return axisLayout.autorange === true;
  25399. }
  25400. else {
  25401. var keys = Object.keys(update);
  25402. return (
  25403. axisLayout.range[0] === update[keys[0]] &&
  25404. axisLayout.range[1] === update[keys[1]]
  25405. );
  25406. }
  25407. }
  25408. function drawButtonRect(button, selectorLayout, d) {
  25409. var rect = Lib.ensureSingle(button, 'rect', 'selector-rect', function(s) {
  25410. s.attr('shape-rendering', 'crispEdges');
  25411. });
  25412. rect.attr({
  25413. 'rx': constants.rx,
  25414. 'ry': constants.ry
  25415. });
  25416. rect.call(Color.stroke, selectorLayout.bordercolor)
  25417. .call(Color.fill, getFillColor(selectorLayout, d))
  25418. .style('stroke-width', selectorLayout.borderwidth + 'px');
  25419. }
  25420. function getFillColor(selectorLayout, d) {
  25421. return (d._isActive || d._isHovered) ?
  25422. selectorLayout.activecolor :
  25423. selectorLayout.bgcolor;
  25424. }
  25425. function drawButtonText(button, selectorLayout, d, gd) {
  25426. function textLayout(s) {
  25427. svgTextUtils.convertToTspans(s, gd);
  25428. }
  25429. var text = Lib.ensureSingle(button, 'text', 'selector-text', function(s) {
  25430. s.classed('user-select-none', true)
  25431. .attr('text-anchor', 'middle');
  25432. });
  25433. text.call(Drawing.font, selectorLayout.font)
  25434. .text(getLabel(d))
  25435. .call(textLayout);
  25436. }
  25437. function getLabel(opts) {
  25438. if(opts.label) return opts.label;
  25439. if(opts.step === 'all') return 'all';
  25440. return opts.count + opts.step.charAt(0);
  25441. }
  25442. function reposition(gd, buttons, opts, axName, selector) {
  25443. var width = 0;
  25444. var height = 0;
  25445. var borderWidth = opts.borderwidth;
  25446. buttons.each(function() {
  25447. var button = d3.select(this);
  25448. var text = button.select('.selector-text');
  25449. var tHeight = opts.font.size * LINE_SPACING;
  25450. var hEff = Math.max(tHeight * svgTextUtils.lineCount(text), 16) + 3;
  25451. height = Math.max(height, hEff);
  25452. });
  25453. buttons.each(function() {
  25454. var button = d3.select(this);
  25455. var rect = button.select('.selector-rect');
  25456. var text = button.select('.selector-text');
  25457. var tWidth = text.node() && Drawing.bBox(text.node()).width;
  25458. var tHeight = opts.font.size * LINE_SPACING;
  25459. var tLines = svgTextUtils.lineCount(text);
  25460. var wEff = Math.max(tWidth + 10, constants.minButtonWidth);
  25461. // TODO add MathJax support
  25462. // TODO add buttongap attribute
  25463. button.attr('transform', 'translate(' +
  25464. (borderWidth + width) + ',' + borderWidth +
  25465. ')');
  25466. rect.attr({
  25467. x: 0,
  25468. y: 0,
  25469. width: wEff,
  25470. height: height
  25471. });
  25472. svgTextUtils.positionText(text, wEff / 2,
  25473. height / 2 - ((tLines - 1) * tHeight / 2) + 3);
  25474. width += wEff + 5;
  25475. });
  25476. var graphSize = gd._fullLayout._size;
  25477. var lx = graphSize.l + graphSize.w * opts.x;
  25478. var ly = graphSize.t + graphSize.h * (1 - opts.y);
  25479. var xanchor = 'left';
  25480. if(Lib.isRightAnchor(opts)) {
  25481. lx -= width;
  25482. xanchor = 'right';
  25483. }
  25484. if(Lib.isCenterAnchor(opts)) {
  25485. lx -= width / 2;
  25486. xanchor = 'center';
  25487. }
  25488. var yanchor = 'top';
  25489. if(Lib.isBottomAnchor(opts)) {
  25490. ly -= height;
  25491. yanchor = 'bottom';
  25492. }
  25493. if(Lib.isMiddleAnchor(opts)) {
  25494. ly -= height / 2;
  25495. yanchor = 'middle';
  25496. }
  25497. width = Math.ceil(width);
  25498. height = Math.ceil(height);
  25499. lx = Math.round(lx);
  25500. ly = Math.round(ly);
  25501. Plots.autoMargin(gd, axName + '-range-selector', {
  25502. x: opts.x,
  25503. y: opts.y,
  25504. l: width * FROM_TL[xanchor],
  25505. r: width * FROM_BR[xanchor],
  25506. b: height * FROM_BR[yanchor],
  25507. t: height * FROM_TL[yanchor]
  25508. });
  25509. selector.attr('transform', 'translate(' + lx + ',' + ly + ')');
  25510. }
  25511. },{"../../constants/alignment":146,"../../lib":168,"../../lib/svg_text_utils":189,"../../plots/cartesian/axis_ids":215,"../../plots/plots":245,"../../registry":257,"../color":51,"../drawing":72,"./constants":114,"./get_update_object":117,"d3":16}],117:[function(_dereq_,module,exports){
  25512. /**
  25513. * Copyright 2012-2019, Plotly, Inc.
  25514. * All rights reserved.
  25515. *
  25516. * This source code is licensed under the MIT license found in the
  25517. * LICENSE file in the root directory of this source tree.
  25518. */
  25519. 'use strict';
  25520. var d3 = _dereq_('d3');
  25521. module.exports = function getUpdateObject(axisLayout, buttonLayout) {
  25522. var axName = axisLayout._name;
  25523. var update = {};
  25524. if(buttonLayout.step === 'all') {
  25525. update[axName + '.autorange'] = true;
  25526. }
  25527. else {
  25528. var xrange = getXRange(axisLayout, buttonLayout);
  25529. update[axName + '.range[0]'] = xrange[0];
  25530. update[axName + '.range[1]'] = xrange[1];
  25531. }
  25532. return update;
  25533. };
  25534. function getXRange(axisLayout, buttonLayout) {
  25535. var currentRange = axisLayout.range;
  25536. var base = new Date(axisLayout.r2l(currentRange[1]));
  25537. var step = buttonLayout.step;
  25538. var count = buttonLayout.count;
  25539. var range0;
  25540. switch(buttonLayout.stepmode) {
  25541. case 'backward':
  25542. range0 = axisLayout.l2r(+d3.time[step].utc.offset(base, -count));
  25543. break;
  25544. case 'todate':
  25545. var base2 = d3.time[step].utc.offset(base, -count);
  25546. range0 = axisLayout.l2r(+d3.time[step].utc.ceil(base2));
  25547. break;
  25548. }
  25549. var range1 = currentRange[1];
  25550. return [range0, range1];
  25551. }
  25552. },{"d3":16}],118:[function(_dereq_,module,exports){
  25553. /**
  25554. * Copyright 2012-2019, Plotly, Inc.
  25555. * All rights reserved.
  25556. *
  25557. * This source code is licensed under the MIT license found in the
  25558. * LICENSE file in the root directory of this source tree.
  25559. */
  25560. 'use strict';
  25561. module.exports = {
  25562. moduleType: 'component',
  25563. name: 'rangeselector',
  25564. schema: {
  25565. subplots: {
  25566. xaxis: {rangeselector: _dereq_('./attributes')}
  25567. }
  25568. },
  25569. layoutAttributes: _dereq_('./attributes'),
  25570. handleDefaults: _dereq_('./defaults'),
  25571. draw: _dereq_('./draw')
  25572. };
  25573. },{"./attributes":113,"./defaults":115,"./draw":116}],119:[function(_dereq_,module,exports){
  25574. /**
  25575. * Copyright 2012-2019, Plotly, Inc.
  25576. * All rights reserved.
  25577. *
  25578. * This source code is licensed under the MIT license found in the
  25579. * LICENSE file in the root directory of this source tree.
  25580. */
  25581. 'use strict';
  25582. var colorAttributes = _dereq_('../color/attributes');
  25583. module.exports = {
  25584. bgcolor: {
  25585. valType: 'color',
  25586. dflt: colorAttributes.background,
  25587. editType: 'plot',
  25588. },
  25589. bordercolor: {
  25590. valType: 'color',
  25591. dflt: colorAttributes.defaultLine,
  25592. editType: 'plot',
  25593. },
  25594. borderwidth: {
  25595. valType: 'integer',
  25596. dflt: 0,
  25597. min: 0,
  25598. editType: 'plot',
  25599. },
  25600. autorange: {
  25601. valType: 'boolean',
  25602. dflt: true,
  25603. editType: 'calc',
  25604. impliedEdits: {'range[0]': undefined, 'range[1]': undefined},
  25605. },
  25606. range: {
  25607. valType: 'info_array',
  25608. items: [
  25609. {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}},
  25610. {valType: 'any', editType: 'calc', impliedEdits: {'^autorange': false}}
  25611. ],
  25612. editType: 'calc',
  25613. impliedEdits: {'autorange': false},
  25614. },
  25615. thickness: {
  25616. valType: 'number',
  25617. dflt: 0.15,
  25618. min: 0,
  25619. max: 1,
  25620. editType: 'plot',
  25621. },
  25622. visible: {
  25623. valType: 'boolean',
  25624. dflt: true,
  25625. editType: 'calc',
  25626. },
  25627. editType: 'calc'
  25628. };
  25629. },{"../color/attributes":50}],120:[function(_dereq_,module,exports){
  25630. /**
  25631. * Copyright 2012-2019, Plotly, Inc.
  25632. * All rights reserved.
  25633. *
  25634. * This source code is licensed under the MIT license found in the
  25635. * LICENSE file in the root directory of this source tree.
  25636. */
  25637. 'use strict';
  25638. var listAxes = _dereq_('../../plots/cartesian/axis_ids').list;
  25639. var getAutoRange = _dereq_('../../plots/cartesian/autorange').getAutoRange;
  25640. var constants = _dereq_('./constants');
  25641. module.exports = function calcAutorange(gd) {
  25642. var axes = listAxes(gd, 'x', true);
  25643. // Compute new slider range using axis autorange if necessary.
  25644. //
  25645. // Copy back range to input range slider container to skip
  25646. // this step in subsequent draw calls.
  25647. for(var i = 0; i < axes.length; i++) {
  25648. var ax = axes[i];
  25649. var opts = ax[constants.name];
  25650. if(opts && opts.visible && opts.autorange) {
  25651. opts._input.autorange = true;
  25652. opts._input.range = opts.range = getAutoRange(gd, ax);
  25653. }
  25654. }
  25655. };
  25656. },{"../../plots/cartesian/autorange":211,"../../plots/cartesian/axis_ids":215,"./constants":121}],121:[function(_dereq_,module,exports){
  25657. /**
  25658. * Copyright 2012-2019, Plotly, Inc.
  25659. * All rights reserved.
  25660. *
  25661. * This source code is licensed under the MIT license found in the
  25662. * LICENSE file in the root directory of this source tree.
  25663. */
  25664. 'use strict';
  25665. module.exports = {
  25666. // attribute container name
  25667. name: 'rangeslider',
  25668. // class names
  25669. containerClassName: 'rangeslider-container',
  25670. bgClassName: 'rangeslider-bg',
  25671. rangePlotClassName: 'rangeslider-rangeplot',
  25672. maskMinClassName: 'rangeslider-mask-min',
  25673. maskMaxClassName: 'rangeslider-mask-max',
  25674. slideBoxClassName: 'rangeslider-slidebox',
  25675. grabberMinClassName: 'rangeslider-grabber-min',
  25676. grabAreaMinClassName: 'rangeslider-grabarea-min',
  25677. handleMinClassName: 'rangeslider-handle-min',
  25678. grabberMaxClassName: 'rangeslider-grabber-max',
  25679. grabAreaMaxClassName: 'rangeslider-grabarea-max',
  25680. handleMaxClassName: 'rangeslider-handle-max',
  25681. maskMinOppAxisClassName: 'rangeslider-mask-min-opp-axis',
  25682. maskMaxOppAxisClassName: 'rangeslider-mask-max-opp-axis',
  25683. // style constants
  25684. maskColor: 'rgba(0,0,0,0.4)',
  25685. maskOppAxisColor: 'rgba(0,0,0,0.2)',
  25686. slideBoxFill: 'transparent',
  25687. slideBoxCursor: 'ew-resize',
  25688. grabAreaFill: 'transparent',
  25689. grabAreaCursor: 'col-resize',
  25690. grabAreaWidth: 10,
  25691. handleWidth: 4,
  25692. handleRadius: 1,
  25693. handleStrokeWidth: 1,
  25694. extraPad: 15
  25695. };
  25696. },{}],122:[function(_dereq_,module,exports){
  25697. /**
  25698. * Copyright 2012-2019, Plotly, Inc.
  25699. * All rights reserved.
  25700. *
  25701. * This source code is licensed under the MIT license found in the
  25702. * LICENSE file in the root directory of this source tree.
  25703. */
  25704. 'use strict';
  25705. var Lib = _dereq_('../../lib');
  25706. var Template = _dereq_('../../plot_api/plot_template');
  25707. var axisIds = _dereq_('../../plots/cartesian/axis_ids');
  25708. var attributes = _dereq_('./attributes');
  25709. var oppAxisAttrs = _dereq_('./oppaxis_attributes');
  25710. module.exports = function handleDefaults(layoutIn, layoutOut, axName) {
  25711. var axIn = layoutIn[axName];
  25712. var axOut = layoutOut[axName];
  25713. if(!(axIn.rangeslider || layoutOut._requestRangeslider[axOut._id])) return;
  25714. // not super proud of this (maybe store _ in axis object instead
  25715. if(!Lib.isPlainObject(axIn.rangeslider)) {
  25716. axIn.rangeslider = {};
  25717. }
  25718. var containerIn = axIn.rangeslider;
  25719. var containerOut = Template.newContainer(axOut, 'rangeslider');
  25720. function coerce(attr, dflt) {
  25721. return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
  25722. }
  25723. var rangeContainerIn, rangeContainerOut;
  25724. function coerceRange(attr, dflt) {
  25725. return Lib.coerce(rangeContainerIn, rangeContainerOut, oppAxisAttrs, attr, dflt);
  25726. }
  25727. var visible = coerce('visible');
  25728. if(!visible) return;
  25729. coerce('bgcolor', layoutOut.plot_bgcolor);
  25730. coerce('bordercolor');
  25731. coerce('borderwidth');
  25732. coerce('thickness');
  25733. coerce('autorange', !axOut.isValidRange(containerIn.range));
  25734. coerce('range');
  25735. var subplots = layoutOut._subplots;
  25736. if(subplots) {
  25737. var yIds = subplots.cartesian
  25738. .filter(function(subplotId) {
  25739. return subplotId.substr(0, subplotId.indexOf('y')) === axisIds.name2id(axName);
  25740. })
  25741. .map(function(subplotId) {
  25742. return subplotId.substr(subplotId.indexOf('y'), subplotId.length);
  25743. });
  25744. var yNames = Lib.simpleMap(yIds, axisIds.id2name);
  25745. for(var i = 0; i < yNames.length; i++) {
  25746. var yName = yNames[i];
  25747. rangeContainerIn = containerIn[yName] || {};
  25748. rangeContainerOut = Template.newContainer(containerOut, yName, 'yaxis');
  25749. var yAxOut = layoutOut[yName];
  25750. var rangemodeDflt;
  25751. if(rangeContainerIn.range && yAxOut.isValidRange(rangeContainerIn.range)) {
  25752. rangemodeDflt = 'fixed';
  25753. }
  25754. var rangeMode = coerceRange('rangemode', rangemodeDflt);
  25755. if(rangeMode !== 'match') {
  25756. coerceRange('range', yAxOut.range.slice());
  25757. }
  25758. }
  25759. }
  25760. // to map back range slider (auto) range
  25761. containerOut._input = containerIn;
  25762. };
  25763. },{"../../lib":168,"../../plot_api/plot_template":202,"../../plots/cartesian/axis_ids":215,"./attributes":119,"./oppaxis_attributes":126}],123:[function(_dereq_,module,exports){
  25764. /**
  25765. * Copyright 2012-2019, Plotly, Inc.
  25766. * All rights reserved.
  25767. *
  25768. * This source code is licensed under the MIT license found in the
  25769. * LICENSE file in the root directory of this source tree.
  25770. */
  25771. 'use strict';
  25772. var d3 = _dereq_('d3');
  25773. var Registry = _dereq_('../../registry');
  25774. var Plots = _dereq_('../../plots/plots');
  25775. var Lib = _dereq_('../../lib');
  25776. var Drawing = _dereq_('../drawing');
  25777. var Color = _dereq_('../color');
  25778. var Titles = _dereq_('../titles');
  25779. var Cartesian = _dereq_('../../plots/cartesian');
  25780. var axisIDs = _dereq_('../../plots/cartesian/axis_ids');
  25781. var dragElement = _dereq_('../dragelement');
  25782. var setCursor = _dereq_('../../lib/setcursor');
  25783. var constants = _dereq_('./constants');
  25784. module.exports = function(gd) {
  25785. var fullLayout = gd._fullLayout;
  25786. var rangeSliderData = fullLayout._rangeSliderData;
  25787. for(var i = 0; i < rangeSliderData.length; i++) {
  25788. var opts = rangeSliderData[i][constants.name];
  25789. // fullLayout._uid may not exist when we call makeData
  25790. opts._clipId = opts._id + '-' + fullLayout._uid;
  25791. }
  25792. /*
  25793. * <g container />
  25794. * <rect bg />
  25795. * < .... range plot />
  25796. * <rect mask-min />
  25797. * <rect mask-max />
  25798. * <rect slidebox />
  25799. * <g grabber-min />
  25800. * <rect handle-min />
  25801. * <rect grabare-min />
  25802. * <g grabber-max />
  25803. * <rect handle-max />
  25804. * <rect grabare-max />
  25805. *
  25806. * ...
  25807. */
  25808. function keyFunction(axisOpts) {
  25809. return axisOpts._name;
  25810. }
  25811. var rangeSliders = fullLayout._infolayer
  25812. .selectAll('g.' + constants.containerClassName)
  25813. .data(rangeSliderData, keyFunction);
  25814. // remove exiting sliders and their corresponding clip paths
  25815. rangeSliders.exit().each(function(axisOpts) {
  25816. var opts = axisOpts[constants.name];
  25817. fullLayout._topdefs.select('#' + opts._clipId).remove();
  25818. }).remove();
  25819. // return early if no range slider is visible
  25820. if(rangeSliderData.length === 0) return;
  25821. rangeSliders.enter().append('g')
  25822. .classed(constants.containerClassName, true)
  25823. .attr('pointer-events', 'all');
  25824. // for all present range sliders
  25825. rangeSliders.each(function(axisOpts) {
  25826. var rangeSlider = d3.select(this);
  25827. var opts = axisOpts[constants.name];
  25828. var oppAxisOpts = fullLayout[axisIDs.id2name(axisOpts.anchor)];
  25829. var oppAxisRangeOpts = opts[axisIDs.id2name(axisOpts.anchor)];
  25830. // update range
  25831. // Expand slider range to the axis range
  25832. if(opts.range) {
  25833. var rng = Lib.simpleMap(opts.range, axisOpts.r2l);
  25834. var axRng = Lib.simpleMap(axisOpts.range, axisOpts.r2l);
  25835. var newRng;
  25836. if(axRng[0] < axRng[1]) {
  25837. newRng = [
  25838. Math.min(rng[0], axRng[0]),
  25839. Math.max(rng[1], axRng[1])
  25840. ];
  25841. } else {
  25842. newRng = [
  25843. Math.max(rng[0], axRng[0]),
  25844. Math.min(rng[1], axRng[1])
  25845. ];
  25846. }
  25847. opts.range = opts._input.range = Lib.simpleMap(newRng, axisOpts.l2r);
  25848. }
  25849. axisOpts.cleanRange('rangeslider.range');
  25850. // update range slider dimensions
  25851. var margin = fullLayout.margin;
  25852. var graphSize = fullLayout._size;
  25853. var domain = axisOpts.domain;
  25854. var tickHeight = opts._tickHeight;
  25855. var oppBottom = opts._oppBottom;
  25856. opts._width = graphSize.w * (domain[1] - domain[0]);
  25857. var x = Math.round(margin.l + (graphSize.w * domain[0]));
  25858. var y = Math.round(
  25859. graphSize.t + graphSize.h * (1 - oppBottom) +
  25860. tickHeight +
  25861. opts._offsetShift + constants.extraPad
  25862. );
  25863. rangeSlider.attr('transform', 'translate(' + x + ',' + y + ')');
  25864. // update data <--> pixel coordinate conversion methods
  25865. var range0 = axisOpts.r2l(opts.range[0]);
  25866. var range1 = axisOpts.r2l(opts.range[1]);
  25867. var dist = range1 - range0;
  25868. opts.p2d = function(v) {
  25869. return (v / opts._width) * dist + range0;
  25870. };
  25871. opts.d2p = function(v) {
  25872. return (v - range0) / dist * opts._width;
  25873. };
  25874. opts._rl = [range0, range1];
  25875. if(oppAxisRangeOpts.rangemode !== 'match') {
  25876. var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]);
  25877. var range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]);
  25878. var distOppAxis = range1OppAxis - range0OppAxis;
  25879. opts.d2pOppAxis = function(v) {
  25880. return (v - range0OppAxis) / distOppAxis * opts._height;
  25881. };
  25882. }
  25883. // update inner nodes
  25884. rangeSlider
  25885. .call(drawBg, gd, axisOpts, opts)
  25886. .call(addClipPath, gd, axisOpts, opts)
  25887. .call(drawRangePlot, gd, axisOpts, opts)
  25888. .call(drawMasks, gd, axisOpts, opts, oppAxisRangeOpts)
  25889. .call(drawSlideBox, gd, axisOpts, opts)
  25890. .call(drawGrabbers, gd, axisOpts, opts);
  25891. // setup drag element
  25892. setupDragElement(rangeSlider, gd, axisOpts, opts);
  25893. // update current range
  25894. setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts);
  25895. // title goes next to range slider instead of tick labels, so
  25896. // just take it over and draw it from here
  25897. if(axisOpts.side === 'bottom') {
  25898. Titles.draw(gd, axisOpts._id + 'title', {
  25899. propContainer: axisOpts,
  25900. propName: axisOpts._name + '.title',
  25901. placeholder: fullLayout._dfltTitle.x,
  25902. attributes: {
  25903. x: axisOpts._offset + axisOpts._length / 2,
  25904. y: y + opts._height + opts._offsetShift + 10 + 1.5 * axisOpts.title.font.size,
  25905. 'text-anchor': 'middle'
  25906. }
  25907. });
  25908. }
  25909. });
  25910. };
  25911. function setupDragElement(rangeSlider, gd, axisOpts, opts) {
  25912. var slideBox = rangeSlider.select('rect.' + constants.slideBoxClassName).node();
  25913. var grabAreaMin = rangeSlider.select('rect.' + constants.grabAreaMinClassName).node();
  25914. var grabAreaMax = rangeSlider.select('rect.' + constants.grabAreaMaxClassName).node();
  25915. rangeSlider.on('mousedown', function() {
  25916. var event = d3.event;
  25917. var target = event.target;
  25918. var startX = event.clientX;
  25919. var offsetX = startX - rangeSlider.node().getBoundingClientRect().left;
  25920. var minVal = opts.d2p(axisOpts._rl[0]);
  25921. var maxVal = opts.d2p(axisOpts._rl[1]);
  25922. var dragCover = dragElement.coverSlip();
  25923. dragCover.addEventListener('mousemove', mouseMove);
  25924. dragCover.addEventListener('mouseup', mouseUp);
  25925. function mouseMove(e) {
  25926. var delta = +e.clientX - startX;
  25927. var pixelMin, pixelMax, cursor;
  25928. switch(target) {
  25929. case slideBox:
  25930. cursor = 'ew-resize';
  25931. pixelMin = minVal + delta;
  25932. pixelMax = maxVal + delta;
  25933. break;
  25934. case grabAreaMin:
  25935. cursor = 'col-resize';
  25936. pixelMin = minVal + delta;
  25937. pixelMax = maxVal;
  25938. break;
  25939. case grabAreaMax:
  25940. cursor = 'col-resize';
  25941. pixelMin = minVal;
  25942. pixelMax = maxVal + delta;
  25943. break;
  25944. default:
  25945. cursor = 'ew-resize';
  25946. pixelMin = offsetX;
  25947. pixelMax = offsetX + delta;
  25948. break;
  25949. }
  25950. if(pixelMax < pixelMin) {
  25951. var tmp = pixelMax;
  25952. pixelMax = pixelMin;
  25953. pixelMin = tmp;
  25954. }
  25955. opts._pixelMin = pixelMin;
  25956. opts._pixelMax = pixelMax;
  25957. setCursor(d3.select(dragCover), cursor);
  25958. setDataRange(rangeSlider, gd, axisOpts, opts);
  25959. }
  25960. function mouseUp() {
  25961. dragCover.removeEventListener('mousemove', mouseMove);
  25962. dragCover.removeEventListener('mouseup', mouseUp);
  25963. Lib.removeElement(dragCover);
  25964. }
  25965. });
  25966. }
  25967. function setDataRange(rangeSlider, gd, axisOpts, opts) {
  25968. function clamp(v) {
  25969. return axisOpts.l2r(Lib.constrain(v, opts._rl[0], opts._rl[1]));
  25970. }
  25971. var dataMin = clamp(opts.p2d(opts._pixelMin));
  25972. var dataMax = clamp(opts.p2d(opts._pixelMax));
  25973. window.requestAnimationFrame(function() {
  25974. Registry.call('_guiRelayout', gd, axisOpts._name + '.range', [dataMin, dataMax]);
  25975. });
  25976. }
  25977. function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) {
  25978. var hw2 = constants.handleWidth / 2;
  25979. function clamp(v) {
  25980. return Lib.constrain(v, 0, opts._width);
  25981. }
  25982. function clampOppAxis(v) {
  25983. return Lib.constrain(v, 0, opts._height);
  25984. }
  25985. function clampHandle(v) {
  25986. return Lib.constrain(v, -hw2, opts._width + hw2);
  25987. }
  25988. var pixelMin = clamp(opts.d2p(axisOpts._rl[0]));
  25989. var pixelMax = clamp(opts.d2p(axisOpts._rl[1]));
  25990. rangeSlider.select('rect.' + constants.slideBoxClassName)
  25991. .attr('x', pixelMin)
  25992. .attr('width', pixelMax - pixelMin);
  25993. rangeSlider.select('rect.' + constants.maskMinClassName)
  25994. .attr('width', pixelMin);
  25995. rangeSlider.select('rect.' + constants.maskMaxClassName)
  25996. .attr('x', pixelMax)
  25997. .attr('width', opts._width - pixelMax);
  25998. if(oppAxisRangeOpts.rangemode !== 'match') {
  25999. var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1]));
  26000. var pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0]));
  26001. rangeSlider.select('rect.' + constants.maskMinOppAxisClassName)
  26002. .attr('x', pixelMin)
  26003. .attr('height', pixelMinOppAxis)
  26004. .attr('width', pixelMax - pixelMin);
  26005. rangeSlider.select('rect.' + constants.maskMaxOppAxisClassName)
  26006. .attr('x', pixelMin)
  26007. .attr('y', pixelMaxOppAxis)
  26008. .attr('height', opts._height - pixelMaxOppAxis)
  26009. .attr('width', pixelMax - pixelMin);
  26010. rangeSlider.select('rect.' + constants.slideBoxClassName)
  26011. .attr('y', pixelMinOppAxis)
  26012. .attr('height', pixelMaxOppAxis - pixelMinOppAxis);
  26013. }
  26014. // add offset for crispier corners
  26015. // https://github.com/plotly/plotly.js/pull/1409
  26016. var offset = 0.5;
  26017. var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset;
  26018. var xMax = Math.round(clampHandle(pixelMax - hw2)) + offset;
  26019. rangeSlider.select('g.' + constants.grabberMinClassName)
  26020. .attr('transform', 'translate(' + xMin + ',' + offset + ')');
  26021. rangeSlider.select('g.' + constants.grabberMaxClassName)
  26022. .attr('transform', 'translate(' + xMax + ',' + offset + ')');
  26023. }
  26024. function drawBg(rangeSlider, gd, axisOpts, opts) {
  26025. var bg = Lib.ensureSingle(rangeSlider, 'rect', constants.bgClassName, function(s) {
  26026. s.attr({
  26027. x: 0,
  26028. y: 0,
  26029. 'shape-rendering': 'crispEdges'
  26030. });
  26031. });
  26032. var borderCorrect = (opts.borderwidth % 2) === 0 ?
  26033. opts.borderwidth :
  26034. opts.borderwidth - 1;
  26035. var offsetShift = -opts._offsetShift;
  26036. var lw = Drawing.crispRound(gd, opts.borderwidth);
  26037. bg.attr({
  26038. width: opts._width + borderCorrect,
  26039. height: opts._height + borderCorrect,
  26040. transform: 'translate(' + offsetShift + ',' + offsetShift + ')',
  26041. fill: opts.bgcolor,
  26042. stroke: opts.bordercolor,
  26043. 'stroke-width': lw
  26044. });
  26045. }
  26046. function addClipPath(rangeSlider, gd, axisOpts, opts) {
  26047. var fullLayout = gd._fullLayout;
  26048. var clipPath = Lib.ensureSingleById(fullLayout._topdefs, 'clipPath', opts._clipId, function(s) {
  26049. s.append('rect').attr({ x: 0, y: 0 });
  26050. });
  26051. clipPath.select('rect').attr({
  26052. width: opts._width,
  26053. height: opts._height
  26054. });
  26055. }
  26056. function drawRangePlot(rangeSlider, gd, axisOpts, opts) {
  26057. var calcData = gd.calcdata;
  26058. var rangePlots = rangeSlider.selectAll('g.' + constants.rangePlotClassName)
  26059. .data(axisOpts._subplotsWith, Lib.identity);
  26060. rangePlots.enter().append('g')
  26061. .attr('class', function(id) { return constants.rangePlotClassName + ' ' + id; })
  26062. .call(Drawing.setClipUrl, opts._clipId, gd);
  26063. rangePlots.order();
  26064. rangePlots.exit().remove();
  26065. var mainplotinfo;
  26066. rangePlots.each(function(id, i) {
  26067. var plotgroup = d3.select(this);
  26068. var isMainPlot = (i === 0);
  26069. var oppAxisOpts = axisIDs.getFromId(gd, id, 'y');
  26070. var oppAxisName = oppAxisOpts._name;
  26071. var oppAxisRangeOpts = opts[oppAxisName];
  26072. var mockFigure = {
  26073. data: [],
  26074. layout: {
  26075. xaxis: {
  26076. type: axisOpts.type,
  26077. domain: [0, 1],
  26078. range: opts.range.slice(),
  26079. calendar: axisOpts.calendar
  26080. },
  26081. width: opts._width,
  26082. height: opts._height,
  26083. margin: { t: 0, b: 0, l: 0, r: 0 }
  26084. },
  26085. _context: gd._context
  26086. };
  26087. mockFigure.layout[oppAxisName] = {
  26088. type: oppAxisOpts.type,
  26089. domain: [0, 1],
  26090. range: oppAxisRangeOpts.rangemode !== 'match' ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(),
  26091. calendar: oppAxisOpts.calendar
  26092. };
  26093. Plots.supplyDefaults(mockFigure);
  26094. var xa = mockFigure._fullLayout.xaxis;
  26095. var ya = mockFigure._fullLayout[oppAxisName];
  26096. xa.clearCalc();
  26097. xa.setScale();
  26098. ya.clearCalc();
  26099. ya.setScale();
  26100. var plotinfo = {
  26101. id: id,
  26102. plotgroup: plotgroup,
  26103. xaxis: xa,
  26104. yaxis: ya,
  26105. isRangePlot: true
  26106. };
  26107. if(isMainPlot) mainplotinfo = plotinfo;
  26108. else {
  26109. plotinfo.mainplot = 'xy';
  26110. plotinfo.mainplotinfo = mainplotinfo;
  26111. }
  26112. Cartesian.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id));
  26113. });
  26114. }
  26115. function filterRangePlotCalcData(calcData, subplotId) {
  26116. var out = [];
  26117. for(var i = 0; i < calcData.length; i++) {
  26118. var calcTrace = calcData[i];
  26119. var trace = calcTrace[0].trace;
  26120. if(trace.xaxis + trace.yaxis === subplotId) {
  26121. out.push(calcTrace);
  26122. }
  26123. }
  26124. return out;
  26125. }
  26126. function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) {
  26127. var maskMin = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMinClassName, function(s) {
  26128. s.attr({
  26129. x: 0,
  26130. y: 0,
  26131. 'shape-rendering': 'crispEdges'
  26132. });
  26133. });
  26134. maskMin
  26135. .attr('height', opts._height)
  26136. .call(Color.fill, constants.maskColor);
  26137. var maskMax = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMaxClassName, function(s) {
  26138. s.attr({
  26139. y: 0,
  26140. 'shape-rendering': 'crispEdges'
  26141. });
  26142. });
  26143. maskMax
  26144. .attr('height', opts._height)
  26145. .call(Color.fill, constants.maskColor);
  26146. // masks used for oppAxis zoom
  26147. if(oppAxisRangeOpts.rangemode !== 'match') {
  26148. var maskMinOppAxis = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMinOppAxisClassName, function(s) {
  26149. s.attr({
  26150. y: 0,
  26151. 'shape-rendering': 'crispEdges'
  26152. });
  26153. });
  26154. maskMinOppAxis
  26155. .attr('width', opts._width)
  26156. .call(Color.fill, constants.maskOppAxisColor);
  26157. var maskMaxOppAxis = Lib.ensureSingle(rangeSlider, 'rect', constants.maskMaxOppAxisClassName, function(s) {
  26158. s.attr({
  26159. y: 0,
  26160. 'shape-rendering': 'crispEdges'
  26161. });
  26162. });
  26163. maskMaxOppAxis
  26164. .attr('width', opts._width)
  26165. .style('border-top', constants.maskOppBorder)
  26166. .call(Color.fill, constants.maskOppAxisColor);
  26167. }
  26168. }
  26169. function drawSlideBox(rangeSlider, gd, axisOpts, opts) {
  26170. if(gd._context.staticPlot) return;
  26171. var slideBox = Lib.ensureSingle(rangeSlider, 'rect', constants.slideBoxClassName, function(s) {
  26172. s.attr({
  26173. y: 0,
  26174. cursor: constants.slideBoxCursor,
  26175. 'shape-rendering': 'crispEdges'
  26176. });
  26177. });
  26178. slideBox.attr({
  26179. height: opts._height,
  26180. fill: constants.slideBoxFill
  26181. });
  26182. }
  26183. function drawGrabbers(rangeSlider, gd, axisOpts, opts) {
  26184. // <g grabber />
  26185. var grabberMin = Lib.ensureSingle(rangeSlider, 'g', constants.grabberMinClassName);
  26186. var grabberMax = Lib.ensureSingle(rangeSlider, 'g', constants.grabberMaxClassName);
  26187. // <g handle />
  26188. var handleFixAttrs = {
  26189. x: 0,
  26190. width: constants.handleWidth,
  26191. rx: constants.handleRadius,
  26192. fill: Color.background,
  26193. stroke: Color.defaultLine,
  26194. 'stroke-width': constants.handleStrokeWidth,
  26195. 'shape-rendering': 'crispEdges'
  26196. };
  26197. var handleDynamicAttrs = {
  26198. y: Math.round(opts._height / 4),
  26199. height: Math.round(opts._height / 2),
  26200. };
  26201. var handleMin = Lib.ensureSingle(grabberMin, 'rect', constants.handleMinClassName, function(s) {
  26202. s.attr(handleFixAttrs);
  26203. });
  26204. handleMin.attr(handleDynamicAttrs);
  26205. var handleMax = Lib.ensureSingle(grabberMax, 'rect', constants.handleMaxClassName, function(s) {
  26206. s.attr(handleFixAttrs);
  26207. });
  26208. handleMax.attr(handleDynamicAttrs);
  26209. // <g grabarea />
  26210. if(gd._context.staticPlot) return;
  26211. var grabAreaFixAttrs = {
  26212. width: constants.grabAreaWidth,
  26213. x: 0,
  26214. y: 0,
  26215. fill: constants.grabAreaFill,
  26216. cursor: constants.grabAreaCursor
  26217. };
  26218. var grabAreaMin = Lib.ensureSingle(grabberMin, 'rect', constants.grabAreaMinClassName, function(s) {
  26219. s.attr(grabAreaFixAttrs);
  26220. });
  26221. grabAreaMin.attr('height', opts._height);
  26222. var grabAreaMax = Lib.ensureSingle(grabberMax, 'rect', constants.grabAreaMaxClassName, function(s) {
  26223. s.attr(grabAreaFixAttrs);
  26224. });
  26225. grabAreaMax.attr('height', opts._height);
  26226. }
  26227. },{"../../lib":168,"../../lib/setcursor":187,"../../plots/cartesian":224,"../../plots/cartesian/axis_ids":215,"../../plots/plots":245,"../../registry":257,"../color":51,"../dragelement":69,"../drawing":72,"../titles":139,"./constants":121,"d3":16}],124:[function(_dereq_,module,exports){
  26228. /**
  26229. * Copyright 2012-2019, Plotly, Inc.
  26230. * All rights reserved.
  26231. *
  26232. * This source code is licensed under the MIT license found in the
  26233. * LICENSE file in the root directory of this source tree.
  26234. */
  26235. 'use strict';
  26236. var axisIDs = _dereq_('../../plots/cartesian/axis_ids');
  26237. var constants = _dereq_('./constants');
  26238. var name = constants.name;
  26239. function isVisible(ax) {
  26240. var rangeSlider = ax && ax[name];
  26241. return rangeSlider && rangeSlider.visible;
  26242. }
  26243. exports.isVisible = isVisible;
  26244. exports.makeData = function(fullLayout) {
  26245. var axes = axisIDs.list({ _fullLayout: fullLayout }, 'x', true);
  26246. var margin = fullLayout.margin;
  26247. var rangeSliderData = [];
  26248. if(!fullLayout._has('gl2d')) {
  26249. for(var i = 0; i < axes.length; i++) {
  26250. var ax = axes[i];
  26251. if(isVisible(ax)) {
  26252. rangeSliderData.push(ax);
  26253. var opts = ax[name];
  26254. opts._id = name + ax._id;
  26255. opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness;
  26256. opts._offsetShift = Math.floor(opts.borderwidth / 2);
  26257. }
  26258. }
  26259. }
  26260. fullLayout._rangeSliderData = rangeSliderData;
  26261. };
  26262. exports.autoMarginOpts = function(gd, ax) {
  26263. var opts = ax[name];
  26264. var oppBottom = Infinity;
  26265. var counterAxes = ax._counterAxes;
  26266. for(var j = 0; j < counterAxes.length; j++) {
  26267. var counterId = counterAxes[j];
  26268. var oppAxis = axisIDs.getFromId(gd, counterId);
  26269. oppBottom = Math.min(oppBottom, oppAxis.domain[0]);
  26270. }
  26271. opts._oppBottom = oppBottom;
  26272. var tickHeight = (ax.side === 'bottom' && ax._boundingBox.height) || 0;
  26273. opts._tickHeight = tickHeight;
  26274. return {
  26275. x: 0,
  26276. y: oppBottom,
  26277. l: 0,
  26278. r: 0,
  26279. t: 0,
  26280. b: opts._height + gd._fullLayout.margin.b + tickHeight,
  26281. pad: constants.extraPad + opts._offsetShift * 2
  26282. };
  26283. };
  26284. },{"../../plots/cartesian/axis_ids":215,"./constants":121}],125:[function(_dereq_,module,exports){
  26285. /**
  26286. * Copyright 2012-2019, Plotly, Inc.
  26287. * All rights reserved.
  26288. *
  26289. * This source code is licensed under the MIT license found in the
  26290. * LICENSE file in the root directory of this source tree.
  26291. */
  26292. 'use strict';
  26293. var Lib = _dereq_('../../lib');
  26294. var attrs = _dereq_('./attributes');
  26295. var oppAxisAttrs = _dereq_('./oppaxis_attributes');
  26296. var helpers = _dereq_('./helpers');
  26297. module.exports = {
  26298. moduleType: 'component',
  26299. name: 'rangeslider',
  26300. schema: {
  26301. subplots: {
  26302. xaxis: {
  26303. rangeslider: Lib.extendFlat({}, attrs, {
  26304. yaxis: oppAxisAttrs
  26305. })
  26306. }
  26307. }
  26308. },
  26309. layoutAttributes: _dereq_('./attributes'),
  26310. handleDefaults: _dereq_('./defaults'),
  26311. calcAutorange: _dereq_('./calc_autorange'),
  26312. draw: _dereq_('./draw'),
  26313. isVisible: helpers.isVisible,
  26314. makeData: helpers.makeData,
  26315. autoMarginOpts: helpers.autoMarginOpts
  26316. };
  26317. },{"../../lib":168,"./attributes":119,"./calc_autorange":120,"./defaults":122,"./draw":123,"./helpers":124,"./oppaxis_attributes":126}],126:[function(_dereq_,module,exports){
  26318. /**
  26319. * Copyright 2012-2019, Plotly, Inc.
  26320. * All rights reserved.
  26321. *
  26322. * This source code is licensed under the MIT license found in the
  26323. * LICENSE file in the root directory of this source tree.
  26324. */
  26325. 'use strict';
  26326. module.exports = {
  26327. // not really a 'subplot' attribute container,
  26328. // but this is the flag we use to denote attributes that
  26329. // support yaxis, yaxis2, yaxis3, ... counters
  26330. _isSubplotObj: true,
  26331. rangemode: {
  26332. valType: 'enumerated',
  26333. values: ['auto', 'fixed', 'match'],
  26334. dflt: 'match',
  26335. editType: 'calc',
  26336. },
  26337. range: {
  26338. valType: 'info_array',
  26339. items: [
  26340. {valType: 'any', editType: 'plot'},
  26341. {valType: 'any', editType: 'plot'}
  26342. ],
  26343. editType: 'plot',
  26344. },
  26345. editType: 'calc'
  26346. };
  26347. },{}],127:[function(_dereq_,module,exports){
  26348. /**
  26349. * Copyright 2012-2019, Plotly, Inc.
  26350. * All rights reserved.
  26351. *
  26352. * This source code is licensed under the MIT license found in the
  26353. * LICENSE file in the root directory of this source tree.
  26354. */
  26355. 'use strict';
  26356. var annAttrs = _dereq_('../annotations/attributes');
  26357. var scatterLineAttrs = _dereq_('../../traces/scatter/attributes').line;
  26358. var dash = _dereq_('../drawing/attributes').dash;
  26359. var extendFlat = _dereq_('../../lib/extend').extendFlat;
  26360. var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;
  26361. module.exports = templatedArray('shape', {
  26362. visible: {
  26363. valType: 'boolean',
  26364. dflt: true,
  26365. editType: 'calc+arraydraw',
  26366. },
  26367. type: {
  26368. valType: 'enumerated',
  26369. values: ['circle', 'rect', 'path', 'line'],
  26370. editType: 'calc+arraydraw',
  26371. },
  26372. layer: {
  26373. valType: 'enumerated',
  26374. values: ['below', 'above'],
  26375. dflt: 'above',
  26376. editType: 'arraydraw',
  26377. },
  26378. xref: extendFlat({}, annAttrs.xref, {
  26379. }),
  26380. xsizemode: {
  26381. valType: 'enumerated',
  26382. values: ['scaled', 'pixel'],
  26383. dflt: 'scaled',
  26384. editType: 'calc+arraydraw',
  26385. },
  26386. xanchor: {
  26387. valType: 'any',
  26388. editType: 'calc+arraydraw',
  26389. },
  26390. x0: {
  26391. valType: 'any',
  26392. editType: 'calc+arraydraw',
  26393. },
  26394. x1: {
  26395. valType: 'any',
  26396. editType: 'calc+arraydraw',
  26397. },
  26398. yref: extendFlat({}, annAttrs.yref, {
  26399. }),
  26400. ysizemode: {
  26401. valType: 'enumerated',
  26402. values: ['scaled', 'pixel'],
  26403. dflt: 'scaled',
  26404. editType: 'calc+arraydraw',
  26405. },
  26406. yanchor: {
  26407. valType: 'any',
  26408. editType: 'calc+arraydraw',
  26409. },
  26410. y0: {
  26411. valType: 'any',
  26412. editType: 'calc+arraydraw',
  26413. },
  26414. y1: {
  26415. valType: 'any',
  26416. editType: 'calc+arraydraw',
  26417. },
  26418. path: {
  26419. valType: 'string',
  26420. editType: 'calc+arraydraw',
  26421. },
  26422. opacity: {
  26423. valType: 'number',
  26424. min: 0,
  26425. max: 1,
  26426. dflt: 1,
  26427. editType: 'arraydraw',
  26428. },
  26429. line: {
  26430. color: extendFlat({}, scatterLineAttrs.color, {editType: 'arraydraw'}),
  26431. width: extendFlat({}, scatterLineAttrs.width, {editType: 'calc+arraydraw'}),
  26432. dash: extendFlat({}, dash, {editType: 'arraydraw'}),
  26433. editType: 'calc+arraydraw'
  26434. },
  26435. fillcolor: {
  26436. valType: 'color',
  26437. dflt: 'rgba(0,0,0,0)',
  26438. editType: 'arraydraw',
  26439. },
  26440. editType: 'arraydraw'
  26441. });
  26442. },{"../../lib/extend":162,"../../plot_api/plot_template":202,"../../traces/scatter/attributes":367,"../annotations/attributes":36,"../drawing/attributes":71}],128:[function(_dereq_,module,exports){
  26443. /**
  26444. * Copyright 2012-2019, Plotly, Inc.
  26445. * All rights reserved.
  26446. *
  26447. * This source code is licensed under the MIT license found in the
  26448. * LICENSE file in the root directory of this source tree.
  26449. */
  26450. 'use strict';
  26451. var Lib = _dereq_('../../lib');
  26452. var Axes = _dereq_('../../plots/cartesian/axes');
  26453. var constants = _dereq_('./constants');
  26454. var helpers = _dereq_('./helpers');
  26455. module.exports = function calcAutorange(gd) {
  26456. var fullLayout = gd._fullLayout;
  26457. var shapeList = Lib.filterVisible(fullLayout.shapes);
  26458. if(!shapeList.length || !gd._fullData.length) return;
  26459. for(var i = 0; i < shapeList.length; i++) {
  26460. var shape = shapeList[i];
  26461. shape._extremes = {};
  26462. var ax, bounds;
  26463. if(shape.xref !== 'paper') {
  26464. var vx0 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x0;
  26465. var vx1 = shape.xsizemode === 'pixel' ? shape.xanchor : shape.x1;
  26466. ax = Axes.getFromId(gd, shape.xref);
  26467. bounds = shapeBounds(ax, vx0, vx1, shape.path, constants.paramIsX);
  26468. if(bounds) {
  26469. shape._extremes[ax._id] = Axes.findExtremes(ax, bounds, calcXPaddingOptions(shape));
  26470. }
  26471. }
  26472. if(shape.yref !== 'paper') {
  26473. var vy0 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y0;
  26474. var vy1 = shape.ysizemode === 'pixel' ? shape.yanchor : shape.y1;
  26475. ax = Axes.getFromId(gd, shape.yref);
  26476. bounds = shapeBounds(ax, vy0, vy1, shape.path, constants.paramIsY);
  26477. if(bounds) {
  26478. shape._extremes[ax._id] = Axes.findExtremes(ax, bounds, calcYPaddingOptions(shape));
  26479. }
  26480. }
  26481. }
  26482. };
  26483. function calcXPaddingOptions(shape) {
  26484. return calcPaddingOptions(shape.line.width, shape.xsizemode, shape.x0, shape.x1, shape.path, false);
  26485. }
  26486. function calcYPaddingOptions(shape) {
  26487. return calcPaddingOptions(shape.line.width, shape.ysizemode, shape.y0, shape.y1, shape.path, true);
  26488. }
  26489. function calcPaddingOptions(lineWidth, sizeMode, v0, v1, path, isYAxis) {
  26490. var ppad = lineWidth / 2;
  26491. var axisDirectionReverted = isYAxis;
  26492. if(sizeMode === 'pixel') {
  26493. var coords = path ?
  26494. helpers.extractPathCoords(path, isYAxis ? constants.paramIsY : constants.paramIsX) :
  26495. [v0, v1];
  26496. var maxValue = Lib.aggNums(Math.max, null, coords);
  26497. var minValue = Lib.aggNums(Math.min, null, coords);
  26498. var beforePad = minValue < 0 ? Math.abs(minValue) + ppad : ppad;
  26499. var afterPad = maxValue > 0 ? maxValue + ppad : ppad;
  26500. return {
  26501. ppad: ppad,
  26502. ppadplus: axisDirectionReverted ? beforePad : afterPad,
  26503. ppadminus: axisDirectionReverted ? afterPad : beforePad
  26504. };
  26505. } else {
  26506. return {ppad: ppad};
  26507. }
  26508. }
  26509. function shapeBounds(ax, v0, v1, path, paramsToUse) {
  26510. var convertVal = (ax.type === 'category' || ax.type === 'multicategory') ? ax.r2c : ax.d2c;
  26511. if(v0 !== undefined) return [convertVal(v0), convertVal(v1)];
  26512. if(!path) return;
  26513. var min = Infinity;
  26514. var max = -Infinity;
  26515. var segments = path.match(constants.segmentRE);
  26516. var i;
  26517. var segment;
  26518. var drawnParam;
  26519. var params;
  26520. var val;
  26521. if(ax.type === 'date') convertVal = helpers.decodeDate(convertVal);
  26522. for(i = 0; i < segments.length; i++) {
  26523. segment = segments[i];
  26524. drawnParam = paramsToUse[segment.charAt(0)].drawn;
  26525. if(drawnParam === undefined) continue;
  26526. params = segments[i].substr(1).match(constants.paramRE);
  26527. if(!params || params.length < drawnParam) continue;
  26528. val = convertVal(params[drawnParam]);
  26529. if(val < min) min = val;
  26530. if(val > max) max = val;
  26531. }
  26532. if(max >= min) return [min, max];
  26533. }
  26534. },{"../../lib":168,"../../plots/cartesian/axes":212,"./constants":129,"./helpers":132}],129:[function(_dereq_,module,exports){
  26535. /**
  26536. * Copyright 2012-2019, Plotly, Inc.
  26537. * All rights reserved.
  26538. *
  26539. * This source code is licensed under the MIT license found in the
  26540. * LICENSE file in the root directory of this source tree.
  26541. */
  26542. 'use strict';
  26543. module.exports = {
  26544. segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g,
  26545. paramRE: /[^\s,]+/g,
  26546. // which numbers in each path segment are x (or y) values
  26547. // drawn is which param is a drawn point, as opposed to a
  26548. // control point (which doesn't count toward autorange.
  26549. // TODO: this means curved paths could extend beyond the
  26550. // autorange bounds. This is a bit tricky to get right
  26551. // unless we revert to bounding boxes, but perhaps there's
  26552. // a calculation we could do...)
  26553. paramIsX: {
  26554. M: {0: true, drawn: 0},
  26555. L: {0: true, drawn: 0},
  26556. H: {0: true, drawn: 0},
  26557. V: {},
  26558. Q: {0: true, 2: true, drawn: 2},
  26559. C: {0: true, 2: true, 4: true, drawn: 4},
  26560. T: {0: true, drawn: 0},
  26561. S: {0: true, 2: true, drawn: 2},
  26562. // A: {0: true, 5: true},
  26563. Z: {}
  26564. },
  26565. paramIsY: {
  26566. M: {1: true, drawn: 1},
  26567. L: {1: true, drawn: 1},
  26568. H: {},
  26569. V: {0: true, drawn: 0},
  26570. Q: {1: true, 3: true, drawn: 3},
  26571. C: {1: true, 3: true, 5: true, drawn: 5},
  26572. T: {1: true, drawn: 1},
  26573. S: {1: true, 3: true, drawn: 5},
  26574. // A: {1: true, 6: true},
  26575. Z: {}
  26576. },
  26577. numParams: {
  26578. M: 2,
  26579. L: 2,
  26580. H: 1,
  26581. V: 1,
  26582. Q: 4,
  26583. C: 6,
  26584. T: 2,
  26585. S: 4,
  26586. // A: 7,
  26587. Z: 0
  26588. }
  26589. };
  26590. },{}],130:[function(_dereq_,module,exports){
  26591. /**
  26592. * Copyright 2012-2019, Plotly, Inc.
  26593. * All rights reserved.
  26594. *
  26595. * This source code is licensed under the MIT license found in the
  26596. * LICENSE file in the root directory of this source tree.
  26597. */
  26598. 'use strict';
  26599. var Lib = _dereq_('../../lib');
  26600. var Axes = _dereq_('../../plots/cartesian/axes');
  26601. var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');
  26602. var attributes = _dereq_('./attributes');
  26603. var helpers = _dereq_('./helpers');
  26604. module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
  26605. handleArrayContainerDefaults(layoutIn, layoutOut, {
  26606. name: 'shapes',
  26607. handleItemDefaults: handleShapeDefaults
  26608. });
  26609. };
  26610. function handleShapeDefaults(shapeIn, shapeOut, fullLayout) {
  26611. function coerce(attr, dflt) {
  26612. return Lib.coerce(shapeIn, shapeOut, attributes, attr, dflt);
  26613. }
  26614. var visible = coerce('visible');
  26615. if(!visible) return;
  26616. coerce('layer');
  26617. coerce('opacity');
  26618. coerce('fillcolor');
  26619. coerce('line.color');
  26620. coerce('line.width');
  26621. coerce('line.dash');
  26622. var dfltType = shapeIn.path ? 'path' : 'rect';
  26623. var shapeType = coerce('type', dfltType);
  26624. var xSizeMode = coerce('xsizemode');
  26625. var ySizeMode = coerce('ysizemode');
  26626. // positioning
  26627. var axLetters = ['x', 'y'];
  26628. for(var i = 0; i < 2; i++) {
  26629. var axLetter = axLetters[i];
  26630. var attrAnchor = axLetter + 'anchor';
  26631. var sizeMode = axLetter === 'x' ? xSizeMode : ySizeMode;
  26632. var gdMock = {_fullLayout: fullLayout};
  26633. var ax;
  26634. var pos2r;
  26635. var r2pos;
  26636. // xref, yref
  26637. var axRef = Axes.coerceRef(shapeIn, shapeOut, gdMock, axLetter, '', 'paper');
  26638. if(axRef !== 'paper') {
  26639. ax = Axes.getFromId(gdMock, axRef);
  26640. ax._shapeIndices.push(shapeOut._index);
  26641. r2pos = helpers.rangeToShapePosition(ax);
  26642. pos2r = helpers.shapePositionToRange(ax);
  26643. }
  26644. else {
  26645. pos2r = r2pos = Lib.identity;
  26646. }
  26647. // Coerce x0, x1, y0, y1
  26648. if(shapeType !== 'path') {
  26649. var dflt0 = 0.25;
  26650. var dflt1 = 0.75;
  26651. // hack until V2.0 when log has regular range behavior - make it look like other
  26652. // ranges to send to coerce, then put it back after
  26653. // this is all to give reasonable default position behavior on log axes, which is
  26654. // a pretty unimportant edge case so we could just ignore this.
  26655. var attr0 = axLetter + '0';
  26656. var attr1 = axLetter + '1';
  26657. var in0 = shapeIn[attr0];
  26658. var in1 = shapeIn[attr1];
  26659. shapeIn[attr0] = pos2r(shapeIn[attr0], true);
  26660. shapeIn[attr1] = pos2r(shapeIn[attr1], true);
  26661. if(sizeMode === 'pixel') {
  26662. coerce(attr0, 0);
  26663. coerce(attr1, 10);
  26664. } else {
  26665. Axes.coercePosition(shapeOut, gdMock, coerce, axRef, attr0, dflt0);
  26666. Axes.coercePosition(shapeOut, gdMock, coerce, axRef, attr1, dflt1);
  26667. }
  26668. // hack part 2
  26669. shapeOut[attr0] = r2pos(shapeOut[attr0]);
  26670. shapeOut[attr1] = r2pos(shapeOut[attr1]);
  26671. shapeIn[attr0] = in0;
  26672. shapeIn[attr1] = in1;
  26673. }
  26674. // Coerce xanchor and yanchor
  26675. if(sizeMode === 'pixel') {
  26676. // Hack for log axis described above
  26677. var inAnchor = shapeIn[attrAnchor];
  26678. shapeIn[attrAnchor] = pos2r(shapeIn[attrAnchor], true);
  26679. Axes.coercePosition(shapeOut, gdMock, coerce, axRef, attrAnchor, 0.25);
  26680. // Hack part 2
  26681. shapeOut[attrAnchor] = r2pos(shapeOut[attrAnchor]);
  26682. shapeIn[attrAnchor] = inAnchor;
  26683. }
  26684. }
  26685. if(shapeType === 'path') {
  26686. coerce('path');
  26687. }
  26688. else {
  26689. Lib.noneOrAll(shapeIn, shapeOut, ['x0', 'x1', 'y0', 'y1']);
  26690. }
  26691. }
  26692. },{"../../lib":168,"../../plots/array_container_defaults":208,"../../plots/cartesian/axes":212,"./attributes":127,"./helpers":132}],131:[function(_dereq_,module,exports){
  26693. /**
  26694. * Copyright 2012-2019, Plotly, Inc.
  26695. * All rights reserved.
  26696. *
  26697. * This source code is licensed under the MIT license found in the
  26698. * LICENSE file in the root directory of this source tree.
  26699. */
  26700. 'use strict';
  26701. var Registry = _dereq_('../../registry');
  26702. var Lib = _dereq_('../../lib');
  26703. var Axes = _dereq_('../../plots/cartesian/axes');
  26704. var Color = _dereq_('../color');
  26705. var Drawing = _dereq_('../drawing');
  26706. var arrayEditor = _dereq_('../../plot_api/plot_template').arrayEditor;
  26707. var dragElement = _dereq_('../dragelement');
  26708. var setCursor = _dereq_('../../lib/setcursor');
  26709. var constants = _dereq_('./constants');
  26710. var helpers = _dereq_('./helpers');
  26711. // Shapes are stored in gd.layout.shapes, an array of objects
  26712. // index can point to one item in this array,
  26713. // or non-numeric to simply add a new one
  26714. // or -1 to modify all existing
  26715. // opt can be the full options object, or one key (to be set to value)
  26716. // or undefined to simply redraw
  26717. // if opt is blank, val can be 'add' or a full options object to add a new
  26718. // annotation at that point in the array, or 'remove' to delete this one
  26719. module.exports = {
  26720. draw: draw,
  26721. drawOne: drawOne
  26722. };
  26723. function draw(gd) {
  26724. var fullLayout = gd._fullLayout;
  26725. // Remove previous shapes before drawing new in shapes in fullLayout.shapes
  26726. fullLayout._shapeUpperLayer.selectAll('path').remove();
  26727. fullLayout._shapeLowerLayer.selectAll('path').remove();
  26728. for(var k in fullLayout._plots) {
  26729. var shapelayer = fullLayout._plots[k].shapelayer;
  26730. if(shapelayer) shapelayer.selectAll('path').remove();
  26731. }
  26732. for(var i = 0; i < fullLayout.shapes.length; i++) {
  26733. if(fullLayout.shapes[i].visible) {
  26734. drawOne(gd, i);
  26735. }
  26736. }
  26737. // may need to resurrect this if we put text (LaTeX) in shapes
  26738. // return Plots.previousPromises(gd);
  26739. }
  26740. function drawOne(gd, index) {
  26741. // remove the existing shape if there is one.
  26742. // because indices can change, we need to look in all shape layers
  26743. gd._fullLayout._paperdiv
  26744. .selectAll('.shapelayer [data-index="' + index + '"]')
  26745. .remove();
  26746. var options = gd._fullLayout.shapes[index] || {};
  26747. // this shape is gone - quit now after deleting it
  26748. // TODO: use d3 idioms instead of deleting and redrawing every time
  26749. if(!options._input || options.visible === false) return;
  26750. if(options.layer !== 'below') {
  26751. drawShape(gd._fullLayout._shapeUpperLayer);
  26752. }
  26753. else if(options.xref === 'paper' || options.yref === 'paper') {
  26754. drawShape(gd._fullLayout._shapeLowerLayer);
  26755. }
  26756. else {
  26757. var plotinfo = gd._fullLayout._plots[options.xref + options.yref];
  26758. if(plotinfo) {
  26759. var mainPlot = plotinfo.mainplotinfo || plotinfo;
  26760. drawShape(mainPlot.shapelayer);
  26761. }
  26762. else {
  26763. // Fall back to _shapeLowerLayer in case the requested subplot doesn't exist.
  26764. // This can happen if you reference the shape to an x / y axis combination
  26765. // that doesn't have any data on it (and layer is below)
  26766. drawShape(gd._fullLayout._shapeLowerLayer);
  26767. }
  26768. }
  26769. function drawShape(shapeLayer) {
  26770. var attrs = {
  26771. 'data-index': index,
  26772. 'fill-rule': 'evenodd',
  26773. d: getPathString(gd, options)
  26774. };
  26775. var lineColor = options.line.width ? options.line.color : 'rgba(0,0,0,0)';
  26776. var path = shapeLayer.append('path')
  26777. .attr(attrs)
  26778. .style('opacity', options.opacity)
  26779. .call(Color.stroke, lineColor)
  26780. .call(Color.fill, options.fillcolor)
  26781. .call(Drawing.dashLine, options.line.dash, options.line.width);
  26782. setClipPath(path, gd, options);
  26783. if(gd._context.edits.shapePosition) setupDragElement(gd, path, options, index, shapeLayer);
  26784. }
  26785. }
  26786. function setClipPath(shapePath, gd, shapeOptions) {
  26787. // note that for layer="below" the clipAxes can be different from the
  26788. // subplot we're drawing this in. This could cause problems if the shape
  26789. // spans two subplots. See https://github.com/plotly/plotly.js/issues/1452
  26790. var clipAxes = (shapeOptions.xref + shapeOptions.yref).replace(/paper/g, '');
  26791. Drawing.setClipUrl(
  26792. shapePath,
  26793. clipAxes ? 'clip' + gd._fullLayout._uid + clipAxes : null,
  26794. gd
  26795. );
  26796. }
  26797. function setupDragElement(gd, shapePath, shapeOptions, index, shapeLayer) {
  26798. var MINWIDTH = 10;
  26799. var MINHEIGHT = 10;
  26800. var xPixelSized = shapeOptions.xsizemode === 'pixel';
  26801. var yPixelSized = shapeOptions.ysizemode === 'pixel';
  26802. var isLine = shapeOptions.type === 'line';
  26803. var isPath = shapeOptions.type === 'path';
  26804. var editHelpers = arrayEditor(gd.layout, 'shapes', shapeOptions);
  26805. var modifyItem = editHelpers.modifyItem;
  26806. var x0, y0, x1, y1, xAnchor, yAnchor;
  26807. var n0, s0, w0, e0, optN, optS, optW, optE;
  26808. var pathIn;
  26809. // setup conversion functions
  26810. var xa = Axes.getFromId(gd, shapeOptions.xref);
  26811. var ya = Axes.getFromId(gd, shapeOptions.yref);
  26812. var x2p = helpers.getDataToPixel(gd, xa);
  26813. var y2p = helpers.getDataToPixel(gd, ya, true);
  26814. var p2x = helpers.getPixelToData(gd, xa);
  26815. var p2y = helpers.getPixelToData(gd, ya, true);
  26816. var sensoryElement = obtainSensoryElement();
  26817. var dragOptions = {
  26818. element: sensoryElement.node(),
  26819. gd: gd,
  26820. prepFn: startDrag,
  26821. doneFn: endDrag,
  26822. clickFn: abortDrag
  26823. };
  26824. var dragMode;
  26825. dragElement.init(dragOptions);
  26826. sensoryElement.node().onmousemove = updateDragMode;
  26827. function obtainSensoryElement() {
  26828. return isLine ? createLineDragHandles() : shapePath;
  26829. }
  26830. function createLineDragHandles() {
  26831. var minSensoryWidth = 10;
  26832. var sensoryWidth = Math.max(shapeOptions.line.width, minSensoryWidth);
  26833. // Helper shapes group
  26834. // Note that by setting the `data-index` attr, it is ensured that
  26835. // the helper group is purged in this modules `draw` function
  26836. var g = shapeLayer.append('g')
  26837. .attr('data-index', index);
  26838. // Helper path for moving
  26839. g.append('path')
  26840. .attr('d', shapePath.attr('d'))
  26841. .style({
  26842. 'cursor': 'move',
  26843. 'stroke-width': sensoryWidth,
  26844. 'stroke-opacity': '0' // ensure not visible
  26845. });
  26846. // Helper circles for resizing
  26847. var circleStyle = {
  26848. 'fill-opacity': '0' // ensure not visible
  26849. };
  26850. var circleRadius = sensoryWidth / 2 > minSensoryWidth ? sensoryWidth / 2 : minSensoryWidth;
  26851. g.append('circle')
  26852. .attr({
  26853. 'data-line-point': 'start-point',
  26854. 'cx': xPixelSized ? x2p(shapeOptions.xanchor) + shapeOptions.x0 : x2p(shapeOptions.x0),
  26855. 'cy': yPixelSized ? y2p(shapeOptions.yanchor) - shapeOptions.y0 : y2p(shapeOptions.y0),
  26856. 'r': circleRadius
  26857. })
  26858. .style(circleStyle)
  26859. .classed('cursor-grab', true);
  26860. g.append('circle')
  26861. .attr({
  26862. 'data-line-point': 'end-point',
  26863. 'cx': xPixelSized ? x2p(shapeOptions.xanchor) + shapeOptions.x1 : x2p(shapeOptions.x1),
  26864. 'cy': yPixelSized ? y2p(shapeOptions.yanchor) - shapeOptions.y1 : y2p(shapeOptions.y1),
  26865. 'r': circleRadius
  26866. })
  26867. .style(circleStyle)
  26868. .classed('cursor-grab', true);
  26869. return g;
  26870. }
  26871. function updateDragMode(evt) {
  26872. if(isLine) {
  26873. if(evt.target.tagName === 'path') {
  26874. dragMode = 'move';
  26875. } else {
  26876. dragMode = evt.target.attributes['data-line-point'].value === 'start-point' ?
  26877. 'resize-over-start-point' : 'resize-over-end-point';
  26878. }
  26879. } else {
  26880. // element might not be on screen at time of setup,
  26881. // so obtain bounding box here
  26882. var dragBBox = dragOptions.element.getBoundingClientRect();
  26883. // choose 'move' or 'resize'
  26884. // based on initial position of cursor within the drag element
  26885. var w = dragBBox.right - dragBBox.left;
  26886. var h = dragBBox.bottom - dragBBox.top;
  26887. var x = evt.clientX - dragBBox.left;
  26888. var y = evt.clientY - dragBBox.top;
  26889. var cursor = (!isPath && w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey) ?
  26890. dragElement.getCursor(x / w, 1 - y / h) :
  26891. 'move';
  26892. setCursor(shapePath, cursor);
  26893. // possible values 'move', 'sw', 'w', 'se', 'e', 'ne', 'n', 'nw' and 'w'
  26894. dragMode = cursor.split('-')[0];
  26895. }
  26896. }
  26897. function startDrag(evt) {
  26898. // setup update strings and initial values
  26899. if(xPixelSized) {
  26900. xAnchor = x2p(shapeOptions.xanchor);
  26901. }
  26902. if(yPixelSized) {
  26903. yAnchor = y2p(shapeOptions.yanchor);
  26904. }
  26905. if(shapeOptions.type === 'path') {
  26906. pathIn = shapeOptions.path;
  26907. }
  26908. else {
  26909. x0 = xPixelSized ? shapeOptions.x0 : x2p(shapeOptions.x0);
  26910. y0 = yPixelSized ? shapeOptions.y0 : y2p(shapeOptions.y0);
  26911. x1 = xPixelSized ? shapeOptions.x1 : x2p(shapeOptions.x1);
  26912. y1 = yPixelSized ? shapeOptions.y1 : y2p(shapeOptions.y1);
  26913. }
  26914. if(x0 < x1) {
  26915. w0 = x0;
  26916. optW = 'x0';
  26917. e0 = x1;
  26918. optE = 'x1';
  26919. }
  26920. else {
  26921. w0 = x1;
  26922. optW = 'x1';
  26923. e0 = x0;
  26924. optE = 'x0';
  26925. }
  26926. // For fixed size shapes take opposing direction of y-axis into account.
  26927. // Hint: For data sized shapes this is done by the y2p function.
  26928. if((!yPixelSized && y0 < y1) || (yPixelSized && y0 > y1)) {
  26929. n0 = y0;
  26930. optN = 'y0';
  26931. s0 = y1;
  26932. optS = 'y1';
  26933. }
  26934. else {
  26935. n0 = y1;
  26936. optN = 'y1';
  26937. s0 = y0;
  26938. optS = 'y0';
  26939. }
  26940. // setup dragMode and the corresponding handler
  26941. updateDragMode(evt);
  26942. renderVisualCues(shapeLayer, shapeOptions);
  26943. deactivateClipPathTemporarily(shapePath, shapeOptions, gd);
  26944. dragOptions.moveFn = (dragMode === 'move') ? moveShape : resizeShape;
  26945. }
  26946. function endDrag() {
  26947. setCursor(shapePath);
  26948. removeVisualCues(shapeLayer);
  26949. // Don't rely on clipPath being activated during re-layout
  26950. setClipPath(shapePath, gd, shapeOptions);
  26951. Registry.call('_guiRelayout', gd, editHelpers.getUpdateObj());
  26952. }
  26953. function abortDrag() {
  26954. removeVisualCues(shapeLayer);
  26955. }
  26956. function moveShape(dx, dy) {
  26957. if(shapeOptions.type === 'path') {
  26958. var noOp = function(coord) { return coord; };
  26959. var moveX = noOp;
  26960. var moveY = noOp;
  26961. if(xPixelSized) {
  26962. modifyItem('xanchor', shapeOptions.xanchor = p2x(xAnchor + dx));
  26963. } else {
  26964. moveX = function moveX(x) { return p2x(x2p(x) + dx); };
  26965. if(xa && xa.type === 'date') moveX = helpers.encodeDate(moveX);
  26966. }
  26967. if(yPixelSized) {
  26968. modifyItem('yanchor', shapeOptions.yanchor = p2y(yAnchor + dy));
  26969. } else {
  26970. moveY = function moveY(y) { return p2y(y2p(y) + dy); };
  26971. if(ya && ya.type === 'date') moveY = helpers.encodeDate(moveY);
  26972. }
  26973. modifyItem('path', shapeOptions.path = movePath(pathIn, moveX, moveY));
  26974. }
  26975. else {
  26976. if(xPixelSized) {
  26977. modifyItem('xanchor', shapeOptions.xanchor = p2x(xAnchor + dx));
  26978. } else {
  26979. modifyItem('x0', shapeOptions.x0 = p2x(x0 + dx));
  26980. modifyItem('x1', shapeOptions.x1 = p2x(x1 + dx));
  26981. }
  26982. if(yPixelSized) {
  26983. modifyItem('yanchor', shapeOptions.yanchor = p2y(yAnchor + dy));
  26984. } else {
  26985. modifyItem('y0', shapeOptions.y0 = p2y(y0 + dy));
  26986. modifyItem('y1', shapeOptions.y1 = p2y(y1 + dy));
  26987. }
  26988. }
  26989. shapePath.attr('d', getPathString(gd, shapeOptions));
  26990. renderVisualCues(shapeLayer, shapeOptions);
  26991. }
  26992. function resizeShape(dx, dy) {
  26993. if(isPath) {
  26994. // TODO: implement path resize, don't forget to update dragMode code
  26995. var noOp = function(coord) { return coord; };
  26996. var moveX = noOp;
  26997. var moveY = noOp;
  26998. if(xPixelSized) {
  26999. modifyItem('xanchor', shapeOptions.xanchor = p2x(xAnchor + dx));
  27000. } else {
  27001. moveX = function moveX(x) { return p2x(x2p(x) + dx); };
  27002. if(xa && xa.type === 'date') moveX = helpers.encodeDate(moveX);
  27003. }
  27004. if(yPixelSized) {
  27005. modifyItem('yanchor', shapeOptions.yanchor = p2y(yAnchor + dy));
  27006. } else {
  27007. moveY = function moveY(y) { return p2y(y2p(y) + dy); };
  27008. if(ya && ya.type === 'date') moveY = helpers.encodeDate(moveY);
  27009. }
  27010. modifyItem('path', shapeOptions.path = movePath(pathIn, moveX, moveY));
  27011. }
  27012. else if(isLine) {
  27013. if(dragMode === 'resize-over-start-point') {
  27014. var newX0 = x0 + dx;
  27015. var newY0 = yPixelSized ? y0 - dy : y0 + dy;
  27016. modifyItem('x0', shapeOptions.x0 = xPixelSized ? newX0 : p2x(newX0));
  27017. modifyItem('y0', shapeOptions.y0 = yPixelSized ? newY0 : p2y(newY0));
  27018. } else if(dragMode === 'resize-over-end-point') {
  27019. var newX1 = x1 + dx;
  27020. var newY1 = yPixelSized ? y1 - dy : y1 + dy;
  27021. modifyItem('x1', shapeOptions.x1 = xPixelSized ? newX1 : p2x(newX1));
  27022. modifyItem('y1', shapeOptions.y1 = yPixelSized ? newY1 : p2y(newY1));
  27023. }
  27024. }
  27025. else {
  27026. var newN = (~dragMode.indexOf('n')) ? n0 + dy : n0;
  27027. var newS = (~dragMode.indexOf('s')) ? s0 + dy : s0;
  27028. var newW = (~dragMode.indexOf('w')) ? w0 + dx : w0;
  27029. var newE = (~dragMode.indexOf('e')) ? e0 + dx : e0;
  27030. // Do things in opposing direction for y-axis.
  27031. // Hint: for data-sized shapes the reversal of axis direction is done in p2y.
  27032. if(~dragMode.indexOf('n') && yPixelSized) newN = n0 - dy;
  27033. if(~dragMode.indexOf('s') && yPixelSized) newS = s0 - dy;
  27034. // Update shape eventually. Again, be aware of the
  27035. // opposing direction of the y-axis of fixed size shapes.
  27036. if((!yPixelSized && newS - newN > MINHEIGHT) ||
  27037. (yPixelSized && newN - newS > MINHEIGHT)) {
  27038. modifyItem(optN, shapeOptions[optN] = yPixelSized ? newN : p2y(newN));
  27039. modifyItem(optS, shapeOptions[optS] = yPixelSized ? newS : p2y(newS));
  27040. }
  27041. if(newE - newW > MINWIDTH) {
  27042. modifyItem(optW, shapeOptions[optW] = xPixelSized ? newW : p2x(newW));
  27043. modifyItem(optE, shapeOptions[optE] = xPixelSized ? newE : p2x(newE));
  27044. }
  27045. }
  27046. shapePath.attr('d', getPathString(gd, shapeOptions));
  27047. renderVisualCues(shapeLayer, shapeOptions);
  27048. }
  27049. function renderVisualCues(shapeLayer, shapeOptions) {
  27050. if(xPixelSized || yPixelSized) {
  27051. renderAnchor();
  27052. }
  27053. function renderAnchor() {
  27054. var isNotPath = shapeOptions.type !== 'path';
  27055. // d3 join with dummy data to satisfy d3 data-binding
  27056. var visualCues = shapeLayer.selectAll('.visual-cue').data([0]);
  27057. // Enter
  27058. var strokeWidth = 1;
  27059. visualCues.enter()
  27060. .append('path')
  27061. .attr({
  27062. 'fill': '#fff',
  27063. 'fill-rule': 'evenodd',
  27064. 'stroke': '#000',
  27065. 'stroke-width': strokeWidth
  27066. })
  27067. .classed('visual-cue', true);
  27068. // Update
  27069. var posX = x2p(
  27070. xPixelSized ?
  27071. shapeOptions.xanchor :
  27072. Lib.midRange(
  27073. isNotPath ?
  27074. [shapeOptions.x0, shapeOptions.x1] :
  27075. helpers.extractPathCoords(shapeOptions.path, constants.paramIsX))
  27076. );
  27077. var posY = y2p(
  27078. yPixelSized ?
  27079. shapeOptions.yanchor :
  27080. Lib.midRange(
  27081. isNotPath ?
  27082. [shapeOptions.y0, shapeOptions.y1] :
  27083. helpers.extractPathCoords(shapeOptions.path, constants.paramIsY))
  27084. );
  27085. posX = helpers.roundPositionForSharpStrokeRendering(posX, strokeWidth);
  27086. posY = helpers.roundPositionForSharpStrokeRendering(posY, strokeWidth);
  27087. if(xPixelSized && yPixelSized) {
  27088. var crossPath = 'M' + (posX - 1 - strokeWidth) + ',' + (posY - 1 - strokeWidth) +
  27089. 'h-8v2h8 v8h2v-8 h8v-2h-8 v-8h-2 Z';
  27090. visualCues.attr('d', crossPath);
  27091. } else if(xPixelSized) {
  27092. var vBarPath = 'M' + (posX - 1 - strokeWidth) + ',' + (posY - 9 - strokeWidth) +
  27093. 'v18 h2 v-18 Z';
  27094. visualCues.attr('d', vBarPath);
  27095. } else {
  27096. var hBarPath = 'M' + (posX - 9 - strokeWidth) + ',' + (posY - 1 - strokeWidth) +
  27097. 'h18 v2 h-18 Z';
  27098. visualCues.attr('d', hBarPath);
  27099. }
  27100. }
  27101. }
  27102. function removeVisualCues(shapeLayer) {
  27103. shapeLayer.selectAll('.visual-cue').remove();
  27104. }
  27105. function deactivateClipPathTemporarily(shapePath, shapeOptions, gd) {
  27106. var xref = shapeOptions.xref;
  27107. var yref = shapeOptions.yref;
  27108. var xa = Axes.getFromId(gd, xref);
  27109. var ya = Axes.getFromId(gd, yref);
  27110. var clipAxes = '';
  27111. if(xref !== 'paper' && !xa.autorange) clipAxes += xref;
  27112. if(yref !== 'paper' && !ya.autorange) clipAxes += yref;
  27113. Drawing.setClipUrl(
  27114. shapePath,
  27115. clipAxes ? 'clip' + gd._fullLayout._uid + clipAxes : null,
  27116. gd
  27117. );
  27118. }
  27119. }
  27120. function getPathString(gd, options) {
  27121. var type = options.type;
  27122. var xa = Axes.getFromId(gd, options.xref);
  27123. var ya = Axes.getFromId(gd, options.yref);
  27124. var gs = gd._fullLayout._size;
  27125. var x2r, x2p, y2r, y2p;
  27126. var x0, x1, y0, y1;
  27127. if(xa) {
  27128. x2r = helpers.shapePositionToRange(xa);
  27129. x2p = function(v) { return xa._offset + xa.r2p(x2r(v, true)); };
  27130. }
  27131. else {
  27132. x2p = function(v) { return gs.l + gs.w * v; };
  27133. }
  27134. if(ya) {
  27135. y2r = helpers.shapePositionToRange(ya);
  27136. y2p = function(v) { return ya._offset + ya.r2p(y2r(v, true)); };
  27137. }
  27138. else {
  27139. y2p = function(v) { return gs.t + gs.h * (1 - v); };
  27140. }
  27141. if(type === 'path') {
  27142. if(xa && xa.type === 'date') x2p = helpers.decodeDate(x2p);
  27143. if(ya && ya.type === 'date') y2p = helpers.decodeDate(y2p);
  27144. return convertPath(options, x2p, y2p);
  27145. }
  27146. if(options.xsizemode === 'pixel') {
  27147. var xAnchorPos = x2p(options.xanchor);
  27148. x0 = xAnchorPos + options.x0;
  27149. x1 = xAnchorPos + options.x1;
  27150. }
  27151. else {
  27152. x0 = x2p(options.x0);
  27153. x1 = x2p(options.x1);
  27154. }
  27155. if(options.ysizemode === 'pixel') {
  27156. var yAnchorPos = y2p(options.yanchor);
  27157. y0 = yAnchorPos - options.y0;
  27158. y1 = yAnchorPos - options.y1;
  27159. }
  27160. else {
  27161. y0 = y2p(options.y0);
  27162. y1 = y2p(options.y1);
  27163. }
  27164. if(type === 'line') return 'M' + x0 + ',' + y0 + 'L' + x1 + ',' + y1;
  27165. if(type === 'rect') return 'M' + x0 + ',' + y0 + 'H' + x1 + 'V' + y1 + 'H' + x0 + 'Z';
  27166. // circle
  27167. var cx = (x0 + x1) / 2;
  27168. var cy = (y0 + y1) / 2;
  27169. var rx = Math.abs(cx - x0);
  27170. var ry = Math.abs(cy - y0);
  27171. var rArc = 'A' + rx + ',' + ry;
  27172. var rightPt = (cx + rx) + ',' + cy;
  27173. var topPt = cx + ',' + (cy - ry);
  27174. return 'M' + rightPt + rArc + ' 0 1,1 ' + topPt +
  27175. rArc + ' 0 0,1 ' + rightPt + 'Z';
  27176. }
  27177. function convertPath(options, x2p, y2p) {
  27178. var pathIn = options.path;
  27179. var xSizemode = options.xsizemode;
  27180. var ySizemode = options.ysizemode;
  27181. var xAnchor = options.xanchor;
  27182. var yAnchor = options.yanchor;
  27183. return pathIn.replace(constants.segmentRE, function(segment) {
  27184. var paramNumber = 0;
  27185. var segmentType = segment.charAt(0);
  27186. var xParams = constants.paramIsX[segmentType];
  27187. var yParams = constants.paramIsY[segmentType];
  27188. var nParams = constants.numParams[segmentType];
  27189. var paramString = segment.substr(1).replace(constants.paramRE, function(param) {
  27190. if(xParams[paramNumber]) {
  27191. if(xSizemode === 'pixel') param = x2p(xAnchor) + Number(param);
  27192. else param = x2p(param);
  27193. }
  27194. else if(yParams[paramNumber]) {
  27195. if(ySizemode === 'pixel') param = y2p(yAnchor) - Number(param);
  27196. else param = y2p(param);
  27197. }
  27198. paramNumber++;
  27199. if(paramNumber > nParams) param = 'X';
  27200. return param;
  27201. });
  27202. if(paramNumber > nParams) {
  27203. paramString = paramString.replace(/[\s,]*X.*/, '');
  27204. Lib.log('Ignoring extra params in segment ' + segment);
  27205. }
  27206. return segmentType + paramString;
  27207. });
  27208. }
  27209. function movePath(pathIn, moveX, moveY) {
  27210. return pathIn.replace(constants.segmentRE, function(segment) {
  27211. var paramNumber = 0;
  27212. var segmentType = segment.charAt(0);
  27213. var xParams = constants.paramIsX[segmentType];
  27214. var yParams = constants.paramIsY[segmentType];
  27215. var nParams = constants.numParams[segmentType];
  27216. var paramString = segment.substr(1).replace(constants.paramRE, function(param) {
  27217. if(paramNumber >= nParams) return param;
  27218. if(xParams[paramNumber]) param = moveX(param);
  27219. else if(yParams[paramNumber]) param = moveY(param);
  27220. paramNumber++;
  27221. return param;
  27222. });
  27223. return segmentType + paramString;
  27224. });
  27225. }
  27226. },{"../../lib":168,"../../lib/setcursor":187,"../../plot_api/plot_template":202,"../../plots/cartesian/axes":212,"../../registry":257,"../color":51,"../dragelement":69,"../drawing":72,"./constants":129,"./helpers":132}],132:[function(_dereq_,module,exports){
  27227. /**
  27228. * Copyright 2012-2019, Plotly, Inc.
  27229. * All rights reserved.
  27230. *
  27231. * This source code is licensed under the MIT license found in the
  27232. * LICENSE file in the root directory of this source tree.
  27233. */
  27234. 'use strict';
  27235. var constants = _dereq_('./constants');
  27236. var Lib = _dereq_('../../lib');
  27237. // special position conversion functions... category axis positions can't be
  27238. // specified by their data values, because they don't make a continuous mapping.
  27239. // so these have to be specified in terms of the category serial numbers,
  27240. // but can take fractional values. Other axis types we specify position based on
  27241. // the actual data values.
  27242. // TODO: in V2.0 (when log axis ranges are in data units) range and shape position
  27243. // will be identical, so rangeToShapePosition and shapePositionToRange can be
  27244. // removed entirely.
  27245. exports.rangeToShapePosition = function(ax) {
  27246. return (ax.type === 'log') ? ax.r2d : function(v) { return v; };
  27247. };
  27248. exports.shapePositionToRange = function(ax) {
  27249. return (ax.type === 'log') ? ax.d2r : function(v) { return v; };
  27250. };
  27251. exports.decodeDate = function(convertToPx) {
  27252. return function(v) {
  27253. if(v.replace) v = v.replace('_', ' ');
  27254. return convertToPx(v);
  27255. };
  27256. };
  27257. exports.encodeDate = function(convertToDate) {
  27258. return function(v) { return convertToDate(v).replace(' ', '_'); };
  27259. };
  27260. exports.extractPathCoords = function(path, paramsToUse) {
  27261. var extractedCoordinates = [];
  27262. var segments = path.match(constants.segmentRE);
  27263. segments.forEach(function(segment) {
  27264. var relevantParamIdx = paramsToUse[segment.charAt(0)].drawn;
  27265. if(relevantParamIdx === undefined) return;
  27266. var params = segment.substr(1).match(constants.paramRE);
  27267. if(!params || params.length < relevantParamIdx) return;
  27268. extractedCoordinates.push(Lib.cleanNumber(params[relevantParamIdx]));
  27269. });
  27270. return extractedCoordinates;
  27271. };
  27272. exports.getDataToPixel = function(gd, axis, isVertical) {
  27273. var gs = gd._fullLayout._size;
  27274. var dataToPixel;
  27275. if(axis) {
  27276. var d2r = exports.shapePositionToRange(axis);
  27277. dataToPixel = function(v) {
  27278. return axis._offset + axis.r2p(d2r(v, true));
  27279. };
  27280. if(axis.type === 'date') dataToPixel = exports.decodeDate(dataToPixel);
  27281. }
  27282. else if(isVertical) {
  27283. dataToPixel = function(v) { return gs.t + gs.h * (1 - v); };
  27284. }
  27285. else {
  27286. dataToPixel = function(v) { return gs.l + gs.w * v; };
  27287. }
  27288. return dataToPixel;
  27289. };
  27290. exports.getPixelToData = function(gd, axis, isVertical) {
  27291. var gs = gd._fullLayout._size;
  27292. var pixelToData;
  27293. if(axis) {
  27294. var r2d = exports.rangeToShapePosition(axis);
  27295. pixelToData = function(p) { return r2d(axis.p2r(p - axis._offset)); };
  27296. }
  27297. else if(isVertical) {
  27298. pixelToData = function(p) { return 1 - (p - gs.t) / gs.h; };
  27299. }
  27300. else {
  27301. pixelToData = function(p) { return (p - gs.l) / gs.w; };
  27302. }
  27303. return pixelToData;
  27304. };
  27305. /**
  27306. * Based on the given stroke width, rounds the passed
  27307. * position value to represent either a full or half pixel.
  27308. *
  27309. * In case of an odd stroke width (e.g. 1), this measure ensures
  27310. * that a stroke positioned at the returned position isn't rendered
  27311. * blurry due to anti-aliasing.
  27312. *
  27313. * In case of an even stroke width (e.g. 2), this measure ensures
  27314. * that the position value is transformed to a full pixel value
  27315. * so that anti-aliasing doesn't take effect either.
  27316. *
  27317. * @param {number} pos The raw position value to be transformed
  27318. * @param {number} strokeWidth The stroke width
  27319. * @returns {number} either an integer or a .5 decimal number
  27320. */
  27321. exports.roundPositionForSharpStrokeRendering = function(pos, strokeWidth) {
  27322. var strokeWidthIsOdd = Math.round(strokeWidth % 2) === 1;
  27323. var posValAsInt = Math.round(pos);
  27324. return strokeWidthIsOdd ? posValAsInt + 0.5 : posValAsInt;
  27325. };
  27326. },{"../../lib":168,"./constants":129}],133:[function(_dereq_,module,exports){
  27327. /**
  27328. * Copyright 2012-2019, Plotly, Inc.
  27329. * All rights reserved.
  27330. *
  27331. * This source code is licensed under the MIT license found in the
  27332. * LICENSE file in the root directory of this source tree.
  27333. */
  27334. 'use strict';
  27335. var drawModule = _dereq_('./draw');
  27336. module.exports = {
  27337. moduleType: 'component',
  27338. name: 'shapes',
  27339. layoutAttributes: _dereq_('./attributes'),
  27340. supplyLayoutDefaults: _dereq_('./defaults'),
  27341. includeBasePlot: _dereq_('../../plots/cartesian/include_components')('shapes'),
  27342. calcAutorange: _dereq_('./calc_autorange'),
  27343. draw: drawModule.draw,
  27344. drawOne: drawModule.drawOne
  27345. };
  27346. },{"../../plots/cartesian/include_components":223,"./attributes":127,"./calc_autorange":128,"./defaults":130,"./draw":131}],134:[function(_dereq_,module,exports){
  27347. /**
  27348. * Copyright 2012-2019, Plotly, Inc.
  27349. * All rights reserved.
  27350. *
  27351. * This source code is licensed under the MIT license found in the
  27352. * LICENSE file in the root directory of this source tree.
  27353. */
  27354. 'use strict';
  27355. var fontAttrs = _dereq_('../../plots/font_attributes');
  27356. var padAttrs = _dereq_('../../plots/pad_attributes');
  27357. var extendDeepAll = _dereq_('../../lib/extend').extendDeepAll;
  27358. var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
  27359. var animationAttrs = _dereq_('../../plots/animation_attributes');
  27360. var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;
  27361. var constants = _dereq_('./constants');
  27362. var stepsAttrs = templatedArray('step', {
  27363. visible: {
  27364. valType: 'boolean',
  27365. dflt: true,
  27366. },
  27367. method: {
  27368. valType: 'enumerated',
  27369. values: ['restyle', 'relayout', 'animate', 'update', 'skip'],
  27370. dflt: 'restyle',
  27371. },
  27372. args: {
  27373. valType: 'info_array',
  27374. freeLength: true,
  27375. items: [
  27376. { valType: 'any' },
  27377. { valType: 'any' },
  27378. { valType: 'any' }
  27379. ],
  27380. },
  27381. label: {
  27382. valType: 'string',
  27383. },
  27384. value: {
  27385. valType: 'string',
  27386. },
  27387. execute: {
  27388. valType: 'boolean',
  27389. dflt: true,
  27390. }
  27391. });
  27392. module.exports = overrideAll(templatedArray('slider', {
  27393. visible: {
  27394. valType: 'boolean',
  27395. dflt: true,
  27396. },
  27397. active: {
  27398. valType: 'number',
  27399. min: 0,
  27400. dflt: 0,
  27401. },
  27402. steps: stepsAttrs,
  27403. lenmode: {
  27404. valType: 'enumerated',
  27405. values: ['fraction', 'pixels'],
  27406. dflt: 'fraction',
  27407. },
  27408. len: {
  27409. valType: 'number',
  27410. min: 0,
  27411. dflt: 1,
  27412. },
  27413. x: {
  27414. valType: 'number',
  27415. min: -2,
  27416. max: 3,
  27417. dflt: 0,
  27418. },
  27419. pad: extendDeepAll(padAttrs({editType: 'arraydraw'}), {
  27420. }, {t: {dflt: 20}}),
  27421. xanchor: {
  27422. valType: 'enumerated',
  27423. values: ['auto', 'left', 'center', 'right'],
  27424. dflt: 'left',
  27425. },
  27426. y: {
  27427. valType: 'number',
  27428. min: -2,
  27429. max: 3,
  27430. dflt: 0,
  27431. },
  27432. yanchor: {
  27433. valType: 'enumerated',
  27434. values: ['auto', 'top', 'middle', 'bottom'],
  27435. dflt: 'top',
  27436. },
  27437. transition: {
  27438. duration: {
  27439. valType: 'number',
  27440. min: 0,
  27441. dflt: 150,
  27442. },
  27443. easing: {
  27444. valType: 'enumerated',
  27445. values: animationAttrs.transition.easing.values,
  27446. dflt: 'cubic-in-out',
  27447. }
  27448. },
  27449. currentvalue: {
  27450. visible: {
  27451. valType: 'boolean',
  27452. dflt: true,
  27453. },
  27454. xanchor: {
  27455. valType: 'enumerated',
  27456. values: ['left', 'center', 'right'],
  27457. dflt: 'left',
  27458. },
  27459. offset: {
  27460. valType: 'number',
  27461. dflt: 10,
  27462. },
  27463. prefix: {
  27464. valType: 'string',
  27465. },
  27466. suffix: {
  27467. valType: 'string',
  27468. },
  27469. font: fontAttrs({
  27470. })
  27471. },
  27472. font: fontAttrs({
  27473. }),
  27474. activebgcolor: {
  27475. valType: 'color',
  27476. dflt: constants.gripBgActiveColor,
  27477. },
  27478. bgcolor: {
  27479. valType: 'color',
  27480. dflt: constants.railBgColor,
  27481. },
  27482. bordercolor: {
  27483. valType: 'color',
  27484. dflt: constants.railBorderColor,
  27485. },
  27486. borderwidth: {
  27487. valType: 'number',
  27488. min: 0,
  27489. dflt: constants.railBorderWidth,
  27490. },
  27491. ticklen: {
  27492. valType: 'number',
  27493. min: 0,
  27494. dflt: constants.tickLength,
  27495. },
  27496. tickcolor: {
  27497. valType: 'color',
  27498. dflt: constants.tickColor,
  27499. },
  27500. tickwidth: {
  27501. valType: 'number',
  27502. min: 0,
  27503. dflt: 1,
  27504. },
  27505. minorticklen: {
  27506. valType: 'number',
  27507. min: 0,
  27508. dflt: constants.minorTickLength,
  27509. }
  27510. }), 'arraydraw', 'from-root');
  27511. },{"../../lib/extend":162,"../../plot_api/edit_types":195,"../../plot_api/plot_template":202,"../../plots/animation_attributes":207,"../../plots/font_attributes":239,"../../plots/pad_attributes":244,"./constants":135}],135:[function(_dereq_,module,exports){
  27512. /**
  27513. * Copyright 2012-2019, Plotly, Inc.
  27514. * All rights reserved.
  27515. *
  27516. * This source code is licensed under the MIT license found in the
  27517. * LICENSE file in the root directory of this source tree.
  27518. */
  27519. 'use strict';
  27520. module.exports = {
  27521. // layout attribute name
  27522. name: 'sliders',
  27523. // class names
  27524. containerClassName: 'slider-container',
  27525. groupClassName: 'slider-group',
  27526. inputAreaClass: 'slider-input-area',
  27527. railRectClass: 'slider-rail-rect',
  27528. railTouchRectClass: 'slider-rail-touch-rect',
  27529. gripRectClass: 'slider-grip-rect',
  27530. tickRectClass: 'slider-tick-rect',
  27531. inputProxyClass: 'slider-input-proxy',
  27532. labelsClass: 'slider-labels',
  27533. labelGroupClass: 'slider-label-group',
  27534. labelClass: 'slider-label',
  27535. currentValueClass: 'slider-current-value',
  27536. railHeight: 5,
  27537. // DOM attribute name in button group keeping track
  27538. // of active update menu
  27539. menuIndexAttrName: 'slider-active-index',
  27540. // id root pass to Plots.autoMargin
  27541. autoMarginIdRoot: 'slider-',
  27542. // min item width / height
  27543. minWidth: 30,
  27544. minHeight: 30,
  27545. // padding around item text
  27546. textPadX: 40,
  27547. // arrow offset off right edge
  27548. arrowOffsetX: 4,
  27549. railRadius: 2,
  27550. railWidth: 5,
  27551. railBorder: 4,
  27552. railBorderWidth: 1,
  27553. railBorderColor: '#bec8d9',
  27554. railBgColor: '#f8fafc',
  27555. // The distance of the rail from the edge of the touchable area
  27556. // Slightly less than the step inset because of the curved edges
  27557. // of the rail
  27558. railInset: 8,
  27559. // The distance from the extremal tick marks to the edge of the
  27560. // touchable area. This is basically the same as the grip radius,
  27561. // but for other styles it wouldn't really need to be.
  27562. stepInset: 10,
  27563. gripRadius: 10,
  27564. gripWidth: 20,
  27565. gripHeight: 20,
  27566. gripBorder: 20,
  27567. gripBorderWidth: 1,
  27568. gripBorderColor: '#bec8d9',
  27569. gripBgColor: '#f6f8fa',
  27570. gripBgActiveColor: '#dbdde0',
  27571. labelPadding: 8,
  27572. labelOffset: 0,
  27573. tickWidth: 1,
  27574. tickColor: '#333',
  27575. tickOffset: 25,
  27576. tickLength: 7,
  27577. minorTickOffset: 25,
  27578. minorTickColor: '#333',
  27579. minorTickLength: 4,
  27580. // Extra space below the current value label:
  27581. currentValuePadding: 8,
  27582. currentValueInset: 0,
  27583. };
  27584. },{}],136:[function(_dereq_,module,exports){
  27585. /**
  27586. * Copyright 2012-2019, Plotly, Inc.
  27587. * All rights reserved.
  27588. *
  27589. * This source code is licensed under the MIT license found in the
  27590. * LICENSE file in the root directory of this source tree.
  27591. */
  27592. 'use strict';
  27593. var Lib = _dereq_('../../lib');
  27594. var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');
  27595. var attributes = _dereq_('./attributes');
  27596. var constants = _dereq_('./constants');
  27597. var name = constants.name;
  27598. var stepAttrs = attributes.steps;
  27599. module.exports = function slidersDefaults(layoutIn, layoutOut) {
  27600. handleArrayContainerDefaults(layoutIn, layoutOut, {
  27601. name: name,
  27602. handleItemDefaults: sliderDefaults
  27603. });
  27604. };
  27605. function sliderDefaults(sliderIn, sliderOut, layoutOut) {
  27606. function coerce(attr, dflt) {
  27607. return Lib.coerce(sliderIn, sliderOut, attributes, attr, dflt);
  27608. }
  27609. var steps = handleArrayContainerDefaults(sliderIn, sliderOut, {
  27610. name: 'steps',
  27611. handleItemDefaults: stepDefaults
  27612. });
  27613. var stepCount = 0;
  27614. for(var i = 0; i < steps.length; i++) {
  27615. if(steps[i].visible) stepCount++;
  27616. }
  27617. var visible;
  27618. // If it has fewer than two options, it's not really a slider
  27619. if(stepCount < 2) visible = sliderOut.visible = false;
  27620. else visible = coerce('visible');
  27621. if(!visible) return;
  27622. sliderOut._stepCount = stepCount;
  27623. var visSteps = sliderOut._visibleSteps = Lib.filterVisible(steps);
  27624. var active = coerce('active');
  27625. if(!(steps[active] || {}).visible) sliderOut.active = visSteps[0]._index;
  27626. coerce('x');
  27627. coerce('y');
  27628. Lib.noneOrAll(sliderIn, sliderOut, ['x', 'y']);
  27629. coerce('xanchor');
  27630. coerce('yanchor');
  27631. coerce('len');
  27632. coerce('lenmode');
  27633. coerce('pad.t');
  27634. coerce('pad.r');
  27635. coerce('pad.b');
  27636. coerce('pad.l');
  27637. Lib.coerceFont(coerce, 'font', layoutOut.font);
  27638. var currentValueIsVisible = coerce('currentvalue.visible');
  27639. if(currentValueIsVisible) {
  27640. coerce('currentvalue.xanchor');
  27641. coerce('currentvalue.prefix');
  27642. coerce('currentvalue.suffix');
  27643. coerce('currentvalue.offset');
  27644. Lib.coerceFont(coerce, 'currentvalue.font', sliderOut.font);
  27645. }
  27646. coerce('transition.duration');
  27647. coerce('transition.easing');
  27648. coerce('bgcolor');
  27649. coerce('activebgcolor');
  27650. coerce('bordercolor');
  27651. coerce('borderwidth');
  27652. coerce('ticklen');
  27653. coerce('tickwidth');
  27654. coerce('tickcolor');
  27655. coerce('minorticklen');
  27656. }
  27657. function stepDefaults(valueIn, valueOut) {
  27658. function coerce(attr, dflt) {
  27659. return Lib.coerce(valueIn, valueOut, stepAttrs, attr, dflt);
  27660. }
  27661. var visible;
  27662. if(valueIn.method !== 'skip' && !Array.isArray(valueIn.args)) {
  27663. visible = valueOut.visible = false;
  27664. }
  27665. else visible = coerce('visible');
  27666. if(visible) {
  27667. coerce('method');
  27668. coerce('args');
  27669. var label = coerce('label', 'step-' + valueOut._index);
  27670. coerce('value', label);
  27671. coerce('execute');
  27672. }
  27673. }
  27674. },{"../../lib":168,"../../plots/array_container_defaults":208,"./attributes":134,"./constants":135}],137:[function(_dereq_,module,exports){
  27675. /**
  27676. * Copyright 2012-2019, Plotly, Inc.
  27677. * All rights reserved.
  27678. *
  27679. * This source code is licensed under the MIT license found in the
  27680. * LICENSE file in the root directory of this source tree.
  27681. */
  27682. 'use strict';
  27683. var d3 = _dereq_('d3');
  27684. var Plots = _dereq_('../../plots/plots');
  27685. var Color = _dereq_('../color');
  27686. var Drawing = _dereq_('../drawing');
  27687. var Lib = _dereq_('../../lib');
  27688. var svgTextUtils = _dereq_('../../lib/svg_text_utils');
  27689. var arrayEditor = _dereq_('../../plot_api/plot_template').arrayEditor;
  27690. var constants = _dereq_('./constants');
  27691. var alignmentConstants = _dereq_('../../constants/alignment');
  27692. var LINE_SPACING = alignmentConstants.LINE_SPACING;
  27693. var FROM_TL = alignmentConstants.FROM_TL;
  27694. var FROM_BR = alignmentConstants.FROM_BR;
  27695. module.exports = function draw(gd) {
  27696. var fullLayout = gd._fullLayout;
  27697. var sliderData = makeSliderData(fullLayout, gd);
  27698. // draw a container for *all* sliders:
  27699. var sliders = fullLayout._infolayer
  27700. .selectAll('g.' + constants.containerClassName)
  27701. .data(sliderData.length > 0 ? [0] : []);
  27702. sliders.enter().append('g')
  27703. .classed(constants.containerClassName, true)
  27704. .style('cursor', 'ew-resize');
  27705. function clearSlider(sliderOpts) {
  27706. if(sliderOpts._commandObserver) {
  27707. sliderOpts._commandObserver.remove();
  27708. delete sliderOpts._commandObserver;
  27709. }
  27710. // Most components don't need to explicitly remove autoMargin, because
  27711. // marginPushers does this - but slider updates don't go through
  27712. // a full replot so we need to explicitly remove it.
  27713. Plots.autoMargin(gd, autoMarginId(sliderOpts));
  27714. }
  27715. sliders.exit().each(function() {
  27716. d3.select(this).selectAll('g.' + constants.groupClassName)
  27717. .each(clearSlider);
  27718. })
  27719. .remove();
  27720. // Return early if no menus visible:
  27721. if(sliderData.length === 0) return;
  27722. var sliderGroups = sliders.selectAll('g.' + constants.groupClassName)
  27723. .data(sliderData, keyFunction);
  27724. sliderGroups.enter().append('g')
  27725. .classed(constants.groupClassName, true);
  27726. sliderGroups.exit()
  27727. .each(clearSlider)
  27728. .remove();
  27729. // Find the dimensions of the sliders:
  27730. for(var i = 0; i < sliderData.length; i++) {
  27731. var sliderOpts = sliderData[i];
  27732. findDimensions(gd, sliderOpts);
  27733. }
  27734. sliderGroups.each(function(sliderOpts) {
  27735. var gSlider = d3.select(this);
  27736. computeLabelSteps(sliderOpts);
  27737. Plots.manageCommandObserver(gd, sliderOpts, sliderOpts._visibleSteps, function(data) {
  27738. // NB: Same as below. This is *not* always the same as sliderOpts since
  27739. // if a new set of steps comes in, the reference in this callback would
  27740. // be invalid. We need to refetch it from the slider group, which is
  27741. // the join data that creates this slider. So if this slider still exists,
  27742. // the group should be valid, *to the best of my knowledge.* If not,
  27743. // we'd have to look it up by d3 data join index/key.
  27744. var opts = gSlider.data()[0];
  27745. if(opts.active === data.index) return;
  27746. if(opts._dragging) return;
  27747. setActive(gd, gSlider, opts, data.index, false, true);
  27748. });
  27749. drawSlider(gd, d3.select(this), sliderOpts);
  27750. });
  27751. };
  27752. function autoMarginId(sliderOpts) {
  27753. return constants.autoMarginIdRoot + sliderOpts._index;
  27754. }
  27755. // This really only just filters by visibility:
  27756. function makeSliderData(fullLayout, gd) {
  27757. var contOpts = fullLayout[constants.name];
  27758. var sliderData = [];
  27759. for(var i = 0; i < contOpts.length; i++) {
  27760. var item = contOpts[i];
  27761. if(!item.visible) continue;
  27762. item._gd = gd;
  27763. sliderData.push(item);
  27764. }
  27765. return sliderData;
  27766. }
  27767. // This is set in the defaults step:
  27768. function keyFunction(opts) {
  27769. return opts._index;
  27770. }
  27771. // Compute the dimensions (mutates sliderOpts):
  27772. function findDimensions(gd, sliderOpts) {
  27773. var sliderLabels = Drawing.tester.selectAll('g.' + constants.labelGroupClass)
  27774. .data(sliderOpts._visibleSteps);
  27775. sliderLabels.enter().append('g')
  27776. .classed(constants.labelGroupClass, true);
  27777. // loop over fake buttons to find width / height
  27778. var maxLabelWidth = 0;
  27779. var labelHeight = 0;
  27780. sliderLabels.each(function(stepOpts) {
  27781. var labelGroup = d3.select(this);
  27782. var text = drawLabel(labelGroup, {step: stepOpts}, sliderOpts);
  27783. var textNode = text.node();
  27784. if(textNode) {
  27785. var bBox = Drawing.bBox(textNode);
  27786. labelHeight = Math.max(labelHeight, bBox.height);
  27787. maxLabelWidth = Math.max(maxLabelWidth, bBox.width);
  27788. }
  27789. });
  27790. sliderLabels.remove();
  27791. var dims = sliderOpts._dims = {};
  27792. dims.inputAreaWidth = Math.max(
  27793. constants.railWidth,
  27794. constants.gripHeight
  27795. );
  27796. // calculate some overall dimensions - some of these are needed for
  27797. // calculating the currentValue dimensions
  27798. var graphSize = gd._fullLayout._size;
  27799. dims.lx = graphSize.l + graphSize.w * sliderOpts.x;
  27800. dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y);
  27801. if(sliderOpts.lenmode === 'fraction') {
  27802. // fraction:
  27803. dims.outerLength = Math.round(graphSize.w * sliderOpts.len);
  27804. } else {
  27805. // pixels:
  27806. dims.outerLength = sliderOpts.len;
  27807. }
  27808. // The length of the rail, *excluding* padding on either end:
  27809. dims.inputAreaStart = 0;
  27810. dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r);
  27811. var textableInputLength = dims.inputAreaLength - 2 * constants.stepInset;
  27812. var availableSpacePerLabel = textableInputLength / (sliderOpts._stepCount - 1);
  27813. var computedSpacePerLabel = maxLabelWidth + constants.labelPadding;
  27814. dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel));
  27815. dims.labelHeight = labelHeight;
  27816. // loop over all possible values for currentValue to find the
  27817. // area we need for it
  27818. dims.currentValueMaxWidth = 0;
  27819. dims.currentValueHeight = 0;
  27820. dims.currentValueTotalHeight = 0;
  27821. dims.currentValueMaxLines = 1;
  27822. if(sliderOpts.currentvalue.visible) {
  27823. // Get the dimensions of the current value label:
  27824. var dummyGroup = Drawing.tester.append('g');
  27825. sliderLabels.each(function(stepOpts) {
  27826. var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label);
  27827. var curValSize = (curValPrefix.node() && Drawing.bBox(curValPrefix.node())) || {width: 0, height: 0};
  27828. var lines = svgTextUtils.lineCount(curValPrefix);
  27829. dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width));
  27830. dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height));
  27831. dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines);
  27832. });
  27833. dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset;
  27834. dummyGroup.remove();
  27835. }
  27836. dims.height = dims.currentValueTotalHeight + constants.tickOffset + sliderOpts.ticklen + constants.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b;
  27837. var xanchor = 'left';
  27838. if(Lib.isRightAnchor(sliderOpts)) {
  27839. dims.lx -= dims.outerLength;
  27840. xanchor = 'right';
  27841. }
  27842. if(Lib.isCenterAnchor(sliderOpts)) {
  27843. dims.lx -= dims.outerLength / 2;
  27844. xanchor = 'center';
  27845. }
  27846. var yanchor = 'top';
  27847. if(Lib.isBottomAnchor(sliderOpts)) {
  27848. dims.ly -= dims.height;
  27849. yanchor = 'bottom';
  27850. }
  27851. if(Lib.isMiddleAnchor(sliderOpts)) {
  27852. dims.ly -= dims.height / 2;
  27853. yanchor = 'middle';
  27854. }
  27855. dims.outerLength = Math.ceil(dims.outerLength);
  27856. dims.height = Math.ceil(dims.height);
  27857. dims.lx = Math.round(dims.lx);
  27858. dims.ly = Math.round(dims.ly);
  27859. var marginOpts = {
  27860. y: sliderOpts.y,
  27861. b: dims.height * FROM_BR[yanchor],
  27862. t: dims.height * FROM_TL[yanchor]
  27863. };
  27864. if(sliderOpts.lenmode === 'fraction') {
  27865. marginOpts.l = 0;
  27866. marginOpts.xl = sliderOpts.x - sliderOpts.len * FROM_TL[xanchor];
  27867. marginOpts.r = 0;
  27868. marginOpts.xr = sliderOpts.x + sliderOpts.len * FROM_BR[xanchor];
  27869. }
  27870. else {
  27871. marginOpts.x = sliderOpts.x;
  27872. marginOpts.l = dims.outerLength * FROM_TL[xanchor];
  27873. marginOpts.r = dims.outerLength * FROM_BR[xanchor];
  27874. }
  27875. Plots.autoMargin(gd, autoMarginId(sliderOpts), marginOpts);
  27876. }
  27877. function drawSlider(gd, sliderGroup, sliderOpts) {
  27878. // This is related to the other long notes in this file regarding what happens
  27879. // when slider steps disappear. This particular fix handles what happens when
  27880. // the *current* slider step is removed. The drawing functions will error out
  27881. // when they fail to find it, so the fix for now is that it will just draw the
  27882. // slider in the first position but will not execute the command.
  27883. if(!((sliderOpts.steps[sliderOpts.active] || {}).visible)) {
  27884. sliderOpts.active = sliderOpts._visibleSteps[0]._index;
  27885. }
  27886. // These are carefully ordered for proper z-ordering:
  27887. sliderGroup
  27888. .call(drawCurrentValue, sliderOpts)
  27889. .call(drawRail, sliderOpts)
  27890. .call(drawLabelGroup, sliderOpts)
  27891. .call(drawTicks, sliderOpts)
  27892. .call(drawTouchRect, gd, sliderOpts)
  27893. .call(drawGrip, gd, sliderOpts);
  27894. var dims = sliderOpts._dims;
  27895. // Position the rectangle:
  27896. Drawing.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t);
  27897. sliderGroup.call(setGripPosition, sliderOpts, false);
  27898. sliderGroup.call(drawCurrentValue, sliderOpts);
  27899. }
  27900. function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) {
  27901. if(!sliderOpts.currentvalue.visible) return;
  27902. var dims = sliderOpts._dims;
  27903. var x0, textAnchor;
  27904. switch(sliderOpts.currentvalue.xanchor) {
  27905. case 'right':
  27906. // This is anchored left and adjusted by the width of the longest label
  27907. // so that the prefix doesn't move. The goal of this is to emphasize
  27908. // what's actually changing and make the update less distracting.
  27909. x0 = dims.inputAreaLength - constants.currentValueInset - dims.currentValueMaxWidth;
  27910. textAnchor = 'left';
  27911. break;
  27912. case 'center':
  27913. x0 = dims.inputAreaLength * 0.5;
  27914. textAnchor = 'middle';
  27915. break;
  27916. default:
  27917. x0 = constants.currentValueInset;
  27918. textAnchor = 'left';
  27919. }
  27920. var text = Lib.ensureSingle(sliderGroup, 'text', constants.labelClass, function(s) {
  27921. s.classed('user-select-none', true)
  27922. .attr({
  27923. 'text-anchor': textAnchor,
  27924. 'data-notex': 1
  27925. });
  27926. });
  27927. var str = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : '';
  27928. if(typeof valueOverride === 'string') {
  27929. str += valueOverride;
  27930. } else {
  27931. var curVal = sliderOpts.steps[sliderOpts.active].label;
  27932. str += curVal;
  27933. }
  27934. if(sliderOpts.currentvalue.suffix) {
  27935. str += sliderOpts.currentvalue.suffix;
  27936. }
  27937. text.call(Drawing.font, sliderOpts.currentvalue.font)
  27938. .text(str)
  27939. .call(svgTextUtils.convertToTspans, sliderOpts._gd);
  27940. var lines = svgTextUtils.lineCount(text);
  27941. var y0 = (dims.currentValueMaxLines + 1 - lines) *
  27942. sliderOpts.currentvalue.font.size * LINE_SPACING;
  27943. svgTextUtils.positionText(text, x0, y0);
  27944. return text;
  27945. }
  27946. function drawGrip(sliderGroup, gd, sliderOpts) {
  27947. var grip = Lib.ensureSingle(sliderGroup, 'rect', constants.gripRectClass, function(s) {
  27948. s.call(attachGripEvents, gd, sliderGroup, sliderOpts)
  27949. .style('pointer-events', 'all');
  27950. });
  27951. grip.attr({
  27952. width: constants.gripWidth,
  27953. height: constants.gripHeight,
  27954. rx: constants.gripRadius,
  27955. ry: constants.gripRadius,
  27956. })
  27957. .call(Color.stroke, sliderOpts.bordercolor)
  27958. .call(Color.fill, sliderOpts.bgcolor)
  27959. .style('stroke-width', sliderOpts.borderwidth + 'px');
  27960. }
  27961. function drawLabel(item, data, sliderOpts) {
  27962. var text = Lib.ensureSingle(item, 'text', constants.labelClass, function(s) {
  27963. s.classed('user-select-none', true)
  27964. .attr({
  27965. 'text-anchor': 'middle',
  27966. 'data-notex': 1
  27967. });
  27968. });
  27969. text.call(Drawing.font, sliderOpts.font)
  27970. .text(data.step.label)
  27971. .call(svgTextUtils.convertToTspans, sliderOpts._gd);
  27972. return text;
  27973. }
  27974. function drawLabelGroup(sliderGroup, sliderOpts) {
  27975. var labels = Lib.ensureSingle(sliderGroup, 'g', constants.labelsClass);
  27976. var dims = sliderOpts._dims;
  27977. var labelItems = labels.selectAll('g.' + constants.labelGroupClass)
  27978. .data(dims.labelSteps);
  27979. labelItems.enter().append('g')
  27980. .classed(constants.labelGroupClass, true);
  27981. labelItems.exit().remove();
  27982. labelItems.each(function(d) {
  27983. var item = d3.select(this);
  27984. item.call(drawLabel, d, sliderOpts);
  27985. Drawing.setTranslate(item,
  27986. normalizedValueToPosition(sliderOpts, d.fraction),
  27987. constants.tickOffset +
  27988. sliderOpts.ticklen +
  27989. // position is the baseline of the top line of text only, even
  27990. // if the label spans multiple lines
  27991. sliderOpts.font.size * LINE_SPACING +
  27992. constants.labelOffset +
  27993. dims.currentValueTotalHeight
  27994. );
  27995. });
  27996. }
  27997. function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) {
  27998. var quantizedPosition = Math.round(normalizedPosition * (sliderOpts._stepCount - 1));
  27999. var quantizedIndex = sliderOpts._visibleSteps[quantizedPosition]._index;
  28000. if(quantizedIndex !== sliderOpts.active) {
  28001. setActive(gd, sliderGroup, sliderOpts, quantizedIndex, true, doTransition);
  28002. }
  28003. }
  28004. function setActive(gd, sliderGroup, sliderOpts, index, doCallback, doTransition) {
  28005. var previousActive = sliderOpts.active;
  28006. sliderOpts.active = index;
  28007. // due to templating, it's possible this slider doesn't even exist yet
  28008. arrayEditor(gd.layout, constants.name, sliderOpts)
  28009. .applyUpdate('active', index);
  28010. var step = sliderOpts.steps[sliderOpts.active];
  28011. sliderGroup.call(setGripPosition, sliderOpts, doTransition);
  28012. sliderGroup.call(drawCurrentValue, sliderOpts);
  28013. gd.emit('plotly_sliderchange', {
  28014. slider: sliderOpts,
  28015. step: sliderOpts.steps[sliderOpts.active],
  28016. interaction: doCallback,
  28017. previousActive: previousActive
  28018. });
  28019. if(step && step.method && doCallback) {
  28020. if(sliderGroup._nextMethod) {
  28021. // If we've already queued up an update, just overwrite it with the most recent:
  28022. sliderGroup._nextMethod.step = step;
  28023. sliderGroup._nextMethod.doCallback = doCallback;
  28024. sliderGroup._nextMethod.doTransition = doTransition;
  28025. } else {
  28026. sliderGroup._nextMethod = {step: step, doCallback: doCallback, doTransition: doTransition};
  28027. sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() {
  28028. var _step = sliderGroup._nextMethod.step;
  28029. if(!_step.method) return;
  28030. if(_step.execute) {
  28031. Plots.executeAPICommand(gd, _step.method, _step.args);
  28032. }
  28033. sliderGroup._nextMethod = null;
  28034. sliderGroup._nextMethodRaf = null;
  28035. });
  28036. }
  28037. }
  28038. }
  28039. function attachGripEvents(item, gd, sliderGroup) {
  28040. var node = sliderGroup.node();
  28041. var $gd = d3.select(gd);
  28042. // NB: This is *not* the same as sliderOpts itself! These callbacks
  28043. // are in a closure so this array won't actually be correct if the
  28044. // steps have changed since this was initialized. The sliderGroup,
  28045. // however, has not changed since that *is* the slider, so it must
  28046. // be present to receive mouse events.
  28047. function getSliderOpts() {
  28048. return sliderGroup.data()[0];
  28049. }
  28050. item.on('mousedown', function() {
  28051. var sliderOpts = getSliderOpts();
  28052. gd.emit('plotly_sliderstart', {slider: sliderOpts});
  28053. var grip = sliderGroup.select('.' + constants.gripRectClass);
  28054. d3.event.stopPropagation();
  28055. d3.event.preventDefault();
  28056. grip.call(Color.fill, sliderOpts.activebgcolor);
  28057. var normalizedPosition = positionToNormalizedValue(sliderOpts, d3.mouse(node)[0]);
  28058. handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true);
  28059. sliderOpts._dragging = true;
  28060. $gd.on('mousemove', function() {
  28061. var sliderOpts = getSliderOpts();
  28062. var normalizedPosition = positionToNormalizedValue(sliderOpts, d3.mouse(node)[0]);
  28063. handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, false);
  28064. });
  28065. $gd.on('mouseup', function() {
  28066. var sliderOpts = getSliderOpts();
  28067. sliderOpts._dragging = false;
  28068. grip.call(Color.fill, sliderOpts.bgcolor);
  28069. $gd.on('mouseup', null);
  28070. $gd.on('mousemove', null);
  28071. gd.emit('plotly_sliderend', {
  28072. slider: sliderOpts,
  28073. step: sliderOpts.steps[sliderOpts.active]
  28074. });
  28075. });
  28076. });
  28077. }
  28078. function drawTicks(sliderGroup, sliderOpts) {
  28079. var tick = sliderGroup.selectAll('rect.' + constants.tickRectClass)
  28080. .data(sliderOpts._visibleSteps);
  28081. var dims = sliderOpts._dims;
  28082. tick.enter().append('rect')
  28083. .classed(constants.tickRectClass, true);
  28084. tick.exit().remove();
  28085. tick.attr({
  28086. width: sliderOpts.tickwidth + 'px',
  28087. 'shape-rendering': 'crispEdges'
  28088. });
  28089. tick.each(function(d, i) {
  28090. var isMajor = i % dims.labelStride === 0;
  28091. var item = d3.select(this);
  28092. item
  28093. .attr({height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen})
  28094. .call(Color.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor);
  28095. Drawing.setTranslate(item,
  28096. normalizedValueToPosition(sliderOpts, i / (sliderOpts._stepCount - 1)) - 0.5 * sliderOpts.tickwidth,
  28097. (isMajor ? constants.tickOffset : constants.minorTickOffset) + dims.currentValueTotalHeight
  28098. );
  28099. });
  28100. }
  28101. function computeLabelSteps(sliderOpts) {
  28102. var dims = sliderOpts._dims;
  28103. dims.labelSteps = [];
  28104. var nsteps = sliderOpts._stepCount;
  28105. for(var i = 0; i < nsteps; i += dims.labelStride) {
  28106. dims.labelSteps.push({
  28107. fraction: i / (nsteps - 1),
  28108. step: sliderOpts._visibleSteps[i]
  28109. });
  28110. }
  28111. }
  28112. function setGripPosition(sliderGroup, sliderOpts, doTransition) {
  28113. var grip = sliderGroup.select('rect.' + constants.gripRectClass);
  28114. var quantizedIndex = 0;
  28115. for(var i = 0; i < sliderOpts._stepCount; i++) {
  28116. if(sliderOpts._visibleSteps[i]._index === sliderOpts.active) {
  28117. quantizedIndex = i;
  28118. break;
  28119. }
  28120. }
  28121. var x = normalizedValueToPosition(sliderOpts, quantizedIndex / (sliderOpts._stepCount - 1));
  28122. // If this is true, then *this component* is already invoking its own command
  28123. // and has triggered its own animation.
  28124. if(sliderOpts._invokingCommand) return;
  28125. var el = grip;
  28126. if(doTransition && sliderOpts.transition.duration > 0) {
  28127. el = el.transition()
  28128. .duration(sliderOpts.transition.duration)
  28129. .ease(sliderOpts.transition.easing);
  28130. }
  28131. // Drawing.setTranslate doesn't work here becasue of the transition duck-typing.
  28132. // It's also not necessary because there are no other transitions to preserve.
  28133. el.attr('transform', 'translate(' + (x - constants.gripWidth * 0.5) + ',' + (sliderOpts._dims.currentValueTotalHeight) + ')');
  28134. }
  28135. // Convert a number from [0-1] to a pixel position relative to the slider group container:
  28136. function normalizedValueToPosition(sliderOpts, normalizedPosition) {
  28137. var dims = sliderOpts._dims;
  28138. return dims.inputAreaStart + constants.stepInset +
  28139. (dims.inputAreaLength - 2 * constants.stepInset) * Math.min(1, Math.max(0, normalizedPosition));
  28140. }
  28141. // Convert a position relative to the slider group to a nubmer in [0, 1]
  28142. function positionToNormalizedValue(sliderOpts, position) {
  28143. var dims = sliderOpts._dims;
  28144. return Math.min(1, Math.max(0, (position - constants.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * constants.stepInset - 2 * dims.inputAreaStart)));
  28145. }
  28146. function drawTouchRect(sliderGroup, gd, sliderOpts) {
  28147. var dims = sliderOpts._dims;
  28148. var rect = Lib.ensureSingle(sliderGroup, 'rect', constants.railTouchRectClass, function(s) {
  28149. s.call(attachGripEvents, gd, sliderGroup, sliderOpts)
  28150. .style('pointer-events', 'all');
  28151. });
  28152. rect.attr({
  28153. width: dims.inputAreaLength,
  28154. height: Math.max(dims.inputAreaWidth, constants.tickOffset + sliderOpts.ticklen + dims.labelHeight)
  28155. })
  28156. .call(Color.fill, sliderOpts.bgcolor)
  28157. .attr('opacity', 0);
  28158. Drawing.setTranslate(rect, 0, dims.currentValueTotalHeight);
  28159. }
  28160. function drawRail(sliderGroup, sliderOpts) {
  28161. var dims = sliderOpts._dims;
  28162. var computedLength = dims.inputAreaLength - constants.railInset * 2;
  28163. var rect = Lib.ensureSingle(sliderGroup, 'rect', constants.railRectClass);
  28164. rect.attr({
  28165. width: computedLength,
  28166. height: constants.railWidth,
  28167. rx: constants.railRadius,
  28168. ry: constants.railRadius,
  28169. 'shape-rendering': 'crispEdges'
  28170. })
  28171. .call(Color.stroke, sliderOpts.bordercolor)
  28172. .call(Color.fill, sliderOpts.bgcolor)
  28173. .style('stroke-width', sliderOpts.borderwidth + 'px');
  28174. Drawing.setTranslate(rect,
  28175. constants.railInset,
  28176. (dims.inputAreaWidth - constants.railWidth) * 0.5 + dims.currentValueTotalHeight
  28177. );
  28178. }
  28179. },{"../../constants/alignment":146,"../../lib":168,"../../lib/svg_text_utils":189,"../../plot_api/plot_template":202,"../../plots/plots":245,"../color":51,"../drawing":72,"./constants":135,"d3":16}],138:[function(_dereq_,module,exports){
  28180. /**
  28181. * Copyright 2012-2019, Plotly, Inc.
  28182. * All rights reserved.
  28183. *
  28184. * This source code is licensed under the MIT license found in the
  28185. * LICENSE file in the root directory of this source tree.
  28186. */
  28187. 'use strict';
  28188. var constants = _dereq_('./constants');
  28189. module.exports = {
  28190. moduleType: 'component',
  28191. name: constants.name,
  28192. layoutAttributes: _dereq_('./attributes'),
  28193. supplyLayoutDefaults: _dereq_('./defaults'),
  28194. draw: _dereq_('./draw')
  28195. };
  28196. },{"./attributes":134,"./constants":135,"./defaults":136,"./draw":137}],139:[function(_dereq_,module,exports){
  28197. /**
  28198. * Copyright 2012-2019, Plotly, Inc.
  28199. * All rights reserved.
  28200. *
  28201. * This source code is licensed under the MIT license found in the
  28202. * LICENSE file in the root directory of this source tree.
  28203. */
  28204. 'use strict';
  28205. var d3 = _dereq_('d3');
  28206. var isNumeric = _dereq_('fast-isnumeric');
  28207. var Plots = _dereq_('../../plots/plots');
  28208. var Registry = _dereq_('../../registry');
  28209. var Lib = _dereq_('../../lib');
  28210. var Drawing = _dereq_('../drawing');
  28211. var Color = _dereq_('../color');
  28212. var svgTextUtils = _dereq_('../../lib/svg_text_utils');
  28213. var interactConstants = _dereq_('../../constants/interactions');
  28214. module.exports = {
  28215. draw: draw
  28216. };
  28217. var numStripRE = / [XY][0-9]* /;
  28218. /**
  28219. * Titles - (re)draw titles on the axes and plot:
  28220. * @param {DOM element} gd - the graphDiv
  28221. * @param {string} titleClass - the css class of this title
  28222. * @param {object} options - how and what to draw
  28223. * propContainer - the layout object containing `title` and `titlefont`
  28224. * attributes that apply to this title
  28225. * propName - the full name of the title property (for Plotly.relayout)
  28226. * [traceIndex] - include only if this property applies to one trace
  28227. * (such as a colorbar title) - then editing pipes to Plotly.restyle
  28228. * instead of Plotly.relayout
  28229. * placeholder - placeholder text for an empty editable title
  28230. * [avoid] {object} - include if this title should move to avoid other elements
  28231. * selection - d3 selection of elements to avoid
  28232. * side - which direction to move if there is a conflict
  28233. * [offsetLeft] - if these elements are subject to a translation
  28234. * wrt the title element
  28235. * [offsetTop]
  28236. * attributes {object} - position and alignment attributes
  28237. * x - pixels
  28238. * y - pixels
  28239. * text-anchor - start|middle|end
  28240. * transform {object} - how to transform the title after positioning
  28241. * rotate - degrees
  28242. * offset - shift up/down in the rotated frame (unused?)
  28243. * containerGroup - if an svg <g> element already exists to hold this
  28244. * title, include here. Otherwise it will go in fullLayout._infolayer
  28245. *
  28246. * @return {selection} d3 selection of title container group
  28247. */
  28248. function draw(gd, titleClass, options) {
  28249. var cont = options.propContainer;
  28250. var prop = options.propName;
  28251. var placeholder = options.placeholder;
  28252. var traceIndex = options.traceIndex;
  28253. var avoid = options.avoid || {};
  28254. var attributes = options.attributes;
  28255. var transform = options.transform;
  28256. var group = options.containerGroup;
  28257. var fullLayout = gd._fullLayout;
  28258. var opacity = 1;
  28259. var isplaceholder = false;
  28260. var title = cont.title;
  28261. var txt = (title && title.text ? title.text : '').trim();
  28262. var font = title && title.font ? title.font : {};
  28263. var fontFamily = font.family;
  28264. var fontSize = font.size;
  28265. var fontColor = font.color;
  28266. // only make this title editable if we positively identify its property
  28267. // as one that has editing enabled.
  28268. var editAttr;
  28269. if(prop === 'title.text') editAttr = 'titleText';
  28270. else if(prop.indexOf('axis') !== -1) editAttr = 'axisTitleText';
  28271. else if(prop.indexOf('colorbar' !== -1)) editAttr = 'colorbarTitleText';
  28272. var editable = gd._context.edits[editAttr];
  28273. if(txt === '') opacity = 0;
  28274. // look for placeholder text while stripping out numbers from eg X2, Y3
  28275. // this is just for backward compatibility with the old version that had
  28276. // "Click to enter X2 title" and may have gotten saved in some old plots,
  28277. // we don't want this to show up when these are displayed.
  28278. else if(txt.replace(numStripRE, ' % ') === placeholder.replace(numStripRE, ' % ')) {
  28279. opacity = 0.2;
  28280. isplaceholder = true;
  28281. if(!editable) txt = '';
  28282. }
  28283. if(fullLayout.meta) {
  28284. txt = Lib.templateString(txt, {meta: fullLayout.meta});
  28285. }
  28286. var elShouldExist = txt || editable;
  28287. if(!group) {
  28288. group = Lib.ensureSingle(fullLayout._infolayer, 'g', 'g-' + titleClass);
  28289. }
  28290. var el = group.selectAll('text')
  28291. .data(elShouldExist ? [0] : []);
  28292. el.enter().append('text');
  28293. el.text(txt)
  28294. // this is hacky, but convertToTspans uses the class
  28295. // to determine whether to rotate mathJax...
  28296. // so we need to clear out any old class and put the
  28297. // correct one (only relevant for colorbars, at least
  28298. // for now) - ie don't use .classed
  28299. .attr('class', titleClass);
  28300. el.exit().remove();
  28301. if(!elShouldExist) return group;
  28302. function titleLayout(titleEl) {
  28303. Lib.syncOrAsync([drawTitle, scootTitle], titleEl);
  28304. }
  28305. function drawTitle(titleEl) {
  28306. var transformVal;
  28307. if(transform) {
  28308. transformVal = '';
  28309. if(transform.rotate) {
  28310. transformVal += 'rotate(' + [transform.rotate, attributes.x, attributes.y] + ')';
  28311. }
  28312. if(transform.offset) {
  28313. transformVal += 'translate(0, ' + transform.offset + ')';
  28314. }
  28315. } else {
  28316. transformVal = null;
  28317. }
  28318. titleEl.attr('transform', transformVal);
  28319. titleEl.style({
  28320. 'font-family': fontFamily,
  28321. 'font-size': d3.round(fontSize, 2) + 'px',
  28322. fill: Color.rgb(fontColor),
  28323. opacity: opacity * Color.opacity(fontColor),
  28324. 'font-weight': Plots.fontWeight
  28325. })
  28326. .attr(attributes)
  28327. .call(svgTextUtils.convertToTspans, gd);
  28328. return Plots.previousPromises(gd);
  28329. }
  28330. function scootTitle(titleElIn) {
  28331. var titleGroup = d3.select(titleElIn.node().parentNode);
  28332. if(avoid && avoid.selection && avoid.side && txt) {
  28333. titleGroup.attr('transform', null);
  28334. // move toward avoid.side (= left, right, top, bottom) if needed
  28335. // can include pad (pixels, default 2)
  28336. var shift = 0;
  28337. var backside = {
  28338. left: 'right',
  28339. right: 'left',
  28340. top: 'bottom',
  28341. bottom: 'top'
  28342. }[avoid.side];
  28343. var shiftSign = (['left', 'top'].indexOf(avoid.side) !== -1) ?
  28344. -1 : 1;
  28345. var pad = isNumeric(avoid.pad) ? avoid.pad : 2;
  28346. var titlebb = Drawing.bBox(titleGroup.node());
  28347. var paperbb = {
  28348. left: 0,
  28349. top: 0,
  28350. right: fullLayout.width,
  28351. bottom: fullLayout.height
  28352. };
  28353. var maxshift = avoid.maxShift || (
  28354. (paperbb[avoid.side] - titlebb[avoid.side]) *
  28355. ((avoid.side === 'left' || avoid.side === 'top') ? -1 : 1));
  28356. // Prevent the title going off the paper
  28357. if(maxshift < 0) shift = maxshift;
  28358. else {
  28359. // so we don't have to offset each avoided element,
  28360. // give the title the opposite offset
  28361. var offsetLeft = avoid.offsetLeft || 0;
  28362. var offsetTop = avoid.offsetTop || 0;
  28363. titlebb.left -= offsetLeft;
  28364. titlebb.right -= offsetLeft;
  28365. titlebb.top -= offsetTop;
  28366. titlebb.bottom -= offsetTop;
  28367. // iterate over a set of elements (avoid.selection)
  28368. // to avoid collisions with
  28369. avoid.selection.each(function() {
  28370. var avoidbb = Drawing.bBox(this);
  28371. if(Lib.bBoxIntersect(titlebb, avoidbb, pad)) {
  28372. shift = Math.max(shift, shiftSign * (
  28373. avoidbb[avoid.side] - titlebb[backside]) + pad);
  28374. }
  28375. });
  28376. shift = Math.min(maxshift, shift);
  28377. }
  28378. if(shift > 0 || maxshift < 0) {
  28379. var shiftTemplate = {
  28380. left: [-shift, 0],
  28381. right: [shift, 0],
  28382. top: [0, -shift],
  28383. bottom: [0, shift]
  28384. }[avoid.side];
  28385. titleGroup.attr('transform',
  28386. 'translate(' + shiftTemplate + ')');
  28387. }
  28388. }
  28389. }
  28390. el.call(titleLayout);
  28391. function setPlaceholder() {
  28392. opacity = 0;
  28393. isplaceholder = true;
  28394. el.text(placeholder)
  28395. .on('mouseover.opacity', function() {
  28396. d3.select(this).transition()
  28397. .duration(interactConstants.SHOW_PLACEHOLDER).style('opacity', 1);
  28398. })
  28399. .on('mouseout.opacity', function() {
  28400. d3.select(this).transition()
  28401. .duration(interactConstants.HIDE_PLACEHOLDER).style('opacity', 0);
  28402. });
  28403. }
  28404. if(editable) {
  28405. if(!txt) setPlaceholder();
  28406. else el.on('.opacity', null);
  28407. el.call(svgTextUtils.makeEditable, {gd: gd})
  28408. .on('edit', function(text) {
  28409. if(traceIndex !== undefined) {
  28410. Registry.call('_guiRestyle', gd, prop, text, traceIndex);
  28411. } else {
  28412. Registry.call('_guiRelayout', gd, prop, text);
  28413. }
  28414. })
  28415. .on('cancel', function() {
  28416. this.text(this.attr('data-unformatted'))
  28417. .call(titleLayout);
  28418. })
  28419. .on('input', function(d) {
  28420. this.text(d || ' ')
  28421. .call(svgTextUtils.positionText, attributes.x, attributes.y);
  28422. });
  28423. }
  28424. el.classed('js-placeholder', isplaceholder);
  28425. return group;
  28426. }
  28427. },{"../../constants/interactions":148,"../../lib":168,"../../lib/svg_text_utils":189,"../../plots/plots":245,"../../registry":257,"../color":51,"../drawing":72,"d3":16,"fast-isnumeric":18}],140:[function(_dereq_,module,exports){
  28428. /**
  28429. * Copyright 2012-2019, Plotly, Inc.
  28430. * All rights reserved.
  28431. *
  28432. * This source code is licensed under the MIT license found in the
  28433. * LICENSE file in the root directory of this source tree.
  28434. */
  28435. 'use strict';
  28436. var fontAttrs = _dereq_('../../plots/font_attributes');
  28437. var colorAttrs = _dereq_('../color/attributes');
  28438. var extendFlat = _dereq_('../../lib/extend').extendFlat;
  28439. var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
  28440. var padAttrs = _dereq_('../../plots/pad_attributes');
  28441. var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;
  28442. var buttonsAttrs = templatedArray('button', {
  28443. visible: {
  28444. valType: 'boolean',
  28445. },
  28446. method: {
  28447. valType: 'enumerated',
  28448. values: ['restyle', 'relayout', 'animate', 'update', 'skip'],
  28449. dflt: 'restyle',
  28450. },
  28451. args: {
  28452. valType: 'info_array',
  28453. freeLength: true,
  28454. items: [
  28455. {valType: 'any'},
  28456. {valType: 'any'},
  28457. {valType: 'any'}
  28458. ],
  28459. },
  28460. label: {
  28461. valType: 'string',
  28462. dflt: '',
  28463. },
  28464. execute: {
  28465. valType: 'boolean',
  28466. dflt: true,
  28467. }
  28468. });
  28469. module.exports = overrideAll(templatedArray('updatemenu', {
  28470. _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/],
  28471. visible: {
  28472. valType: 'boolean',
  28473. },
  28474. type: {
  28475. valType: 'enumerated',
  28476. values: ['dropdown', 'buttons'],
  28477. dflt: 'dropdown',
  28478. },
  28479. direction: {
  28480. valType: 'enumerated',
  28481. values: ['left', 'right', 'up', 'down'],
  28482. dflt: 'down',
  28483. },
  28484. active: {
  28485. valType: 'integer',
  28486. min: -1,
  28487. dflt: 0,
  28488. },
  28489. showactive: {
  28490. valType: 'boolean',
  28491. dflt: true,
  28492. },
  28493. buttons: buttonsAttrs,
  28494. x: {
  28495. valType: 'number',
  28496. min: -2,
  28497. max: 3,
  28498. dflt: -0.05,
  28499. },
  28500. xanchor: {
  28501. valType: 'enumerated',
  28502. values: ['auto', 'left', 'center', 'right'],
  28503. dflt: 'right',
  28504. },
  28505. y: {
  28506. valType: 'number',
  28507. min: -2,
  28508. max: 3,
  28509. dflt: 1,
  28510. },
  28511. yanchor: {
  28512. valType: 'enumerated',
  28513. values: ['auto', 'top', 'middle', 'bottom'],
  28514. dflt: 'top',
  28515. },
  28516. pad: extendFlat(padAttrs({editType: 'arraydraw'}), {
  28517. }),
  28518. font: fontAttrs({
  28519. }),
  28520. bgcolor: {
  28521. valType: 'color',
  28522. },
  28523. bordercolor: {
  28524. valType: 'color',
  28525. dflt: colorAttrs.borderLine,
  28526. },
  28527. borderwidth: {
  28528. valType: 'number',
  28529. min: 0,
  28530. dflt: 1,
  28531. editType: 'arraydraw',
  28532. }
  28533. }), 'arraydraw', 'from-root');
  28534. },{"../../lib/extend":162,"../../plot_api/edit_types":195,"../../plot_api/plot_template":202,"../../plots/font_attributes":239,"../../plots/pad_attributes":244,"../color/attributes":50}],141:[function(_dereq_,module,exports){
  28535. /**
  28536. * Copyright 2012-2019, Plotly, Inc.
  28537. * All rights reserved.
  28538. *
  28539. * This source code is licensed under the MIT license found in the
  28540. * LICENSE file in the root directory of this source tree.
  28541. */
  28542. 'use strict';
  28543. module.exports = {
  28544. // layout attribute name
  28545. name: 'updatemenus',
  28546. // class names
  28547. containerClassName: 'updatemenu-container',
  28548. headerGroupClassName: 'updatemenu-header-group',
  28549. headerClassName: 'updatemenu-header',
  28550. headerArrowClassName: 'updatemenu-header-arrow',
  28551. dropdownButtonGroupClassName: 'updatemenu-dropdown-button-group',
  28552. dropdownButtonClassName: 'updatemenu-dropdown-button',
  28553. buttonClassName: 'updatemenu-button',
  28554. itemRectClassName: 'updatemenu-item-rect',
  28555. itemTextClassName: 'updatemenu-item-text',
  28556. // DOM attribute name in button group keeping track
  28557. // of active update menu
  28558. menuIndexAttrName: 'updatemenu-active-index',
  28559. // id root pass to Plots.autoMargin
  28560. autoMarginIdRoot: 'updatemenu-',
  28561. // options when 'active: -1'
  28562. blankHeaderOpts: { label: ' ' },
  28563. // min item width / height
  28564. minWidth: 30,
  28565. minHeight: 30,
  28566. // padding around item text
  28567. textPadX: 24,
  28568. arrowPadX: 16,
  28569. // item rect radii
  28570. rx: 2,
  28571. ry: 2,
  28572. // item text x offset off left edge
  28573. textOffsetX: 12,
  28574. // item text y offset (w.r.t. middle)
  28575. textOffsetY: 3,
  28576. // arrow offset off right edge
  28577. arrowOffsetX: 4,
  28578. // gap between header and buttons
  28579. gapButtonHeader: 5,
  28580. // gap between between buttons
  28581. gapButton: 2,
  28582. // color given to active buttons
  28583. activeColor: '#F4FAFF',
  28584. // color given to hovered buttons
  28585. hoverColor: '#F4FAFF',
  28586. // symbol for menu open arrow
  28587. arrowSymbol: {
  28588. left: '◄',
  28589. right: '►',
  28590. up: '▲',
  28591. down: '▼'
  28592. }
  28593. };
  28594. },{}],142:[function(_dereq_,module,exports){
  28595. /**
  28596. * Copyright 2012-2019, Plotly, Inc.
  28597. * All rights reserved.
  28598. *
  28599. * This source code is licensed under the MIT license found in the
  28600. * LICENSE file in the root directory of this source tree.
  28601. */
  28602. 'use strict';
  28603. var Lib = _dereq_('../../lib');
  28604. var handleArrayContainerDefaults = _dereq_('../../plots/array_container_defaults');
  28605. var attributes = _dereq_('./attributes');
  28606. var constants = _dereq_('./constants');
  28607. var name = constants.name;
  28608. var buttonAttrs = attributes.buttons;
  28609. module.exports = function updateMenusDefaults(layoutIn, layoutOut) {
  28610. var opts = {
  28611. name: name,
  28612. handleItemDefaults: menuDefaults
  28613. };
  28614. handleArrayContainerDefaults(layoutIn, layoutOut, opts);
  28615. };
  28616. function menuDefaults(menuIn, menuOut, layoutOut) {
  28617. function coerce(attr, dflt) {
  28618. return Lib.coerce(menuIn, menuOut, attributes, attr, dflt);
  28619. }
  28620. var buttons = handleArrayContainerDefaults(menuIn, menuOut, {
  28621. name: 'buttons',
  28622. handleItemDefaults: buttonDefaults
  28623. });
  28624. var visible = coerce('visible', buttons.length > 0);
  28625. if(!visible) return;
  28626. coerce('active');
  28627. coerce('direction');
  28628. coerce('type');
  28629. coerce('showactive');
  28630. coerce('x');
  28631. coerce('y');
  28632. Lib.noneOrAll(menuIn, menuOut, ['x', 'y']);
  28633. coerce('xanchor');
  28634. coerce('yanchor');
  28635. coerce('pad.t');
  28636. coerce('pad.r');
  28637. coerce('pad.b');
  28638. coerce('pad.l');
  28639. Lib.coerceFont(coerce, 'font', layoutOut.font);
  28640. coerce('bgcolor', layoutOut.paper_bgcolor);
  28641. coerce('bordercolor');
  28642. coerce('borderwidth');
  28643. }
  28644. function buttonDefaults(buttonIn, buttonOut) {
  28645. function coerce(attr, dflt) {
  28646. return Lib.coerce(buttonIn, buttonOut, buttonAttrs, attr, dflt);
  28647. }
  28648. var visible = coerce('visible',
  28649. (buttonIn.method === 'skip' || Array.isArray(buttonIn.args)));
  28650. if(visible) {
  28651. coerce('method');
  28652. coerce('args');
  28653. coerce('label');
  28654. coerce('execute');
  28655. }
  28656. }
  28657. },{"../../lib":168,"../../plots/array_container_defaults":208,"./attributes":140,"./constants":141}],143:[function(_dereq_,module,exports){
  28658. /**
  28659. * Copyright 2012-2019, Plotly, Inc.
  28660. * All rights reserved.
  28661. *
  28662. * This source code is licensed under the MIT license found in the
  28663. * LICENSE file in the root directory of this source tree.
  28664. */
  28665. 'use strict';
  28666. var d3 = _dereq_('d3');
  28667. var Plots = _dereq_('../../plots/plots');
  28668. var Color = _dereq_('../color');
  28669. var Drawing = _dereq_('../drawing');
  28670. var Lib = _dereq_('../../lib');
  28671. var svgTextUtils = _dereq_('../../lib/svg_text_utils');
  28672. var arrayEditor = _dereq_('../../plot_api/plot_template').arrayEditor;
  28673. var LINE_SPACING = _dereq_('../../constants/alignment').LINE_SPACING;
  28674. var constants = _dereq_('./constants');
  28675. var ScrollBox = _dereq_('./scrollbox');
  28676. module.exports = function draw(gd) {
  28677. var fullLayout = gd._fullLayout;
  28678. var menuData = Lib.filterVisible(fullLayout[constants.name]);
  28679. /* Update menu data is bound to the header-group.
  28680. * The items in the header group are always present.
  28681. *
  28682. * Upon clicking on a header its corresponding button
  28683. * data is bound to the button-group.
  28684. *
  28685. * We draw all headers in one group before all buttons
  28686. * so that the buttons *always* appear above the headers.
  28687. *
  28688. * Note that only one set of buttons are visible at once.
  28689. *
  28690. * <g container />
  28691. *
  28692. * <g header-group />
  28693. * <g item header />
  28694. * <text item header-arrow />
  28695. * <g header-group />
  28696. * <g item header />
  28697. * <text item header-arrow />
  28698. * ...
  28699. *
  28700. * <g button-group />
  28701. * <g item button />
  28702. * <g item button />
  28703. * ...
  28704. */
  28705. function clearAutoMargin(menuOpts) {
  28706. Plots.autoMargin(gd, autoMarginId(menuOpts));
  28707. }
  28708. // draw update menu container
  28709. var menus = fullLayout._menulayer
  28710. .selectAll('g.' + constants.containerClassName)
  28711. .data(menuData.length > 0 ? [0] : []);
  28712. menus.enter().append('g')
  28713. .classed(constants.containerClassName, true)
  28714. .style('cursor', 'pointer');
  28715. menus.exit().each(function() {
  28716. // Most components don't need to explicitly remove autoMargin, because
  28717. // marginPushers does this - but updatemenu updates don't go through
  28718. // a full replot so we need to explicitly remove it.
  28719. // This is for removing *all* updatemenus, removing individuals is
  28720. // handled below, in headerGroups.exit
  28721. d3.select(this).selectAll('g.' + constants.headerGroupClassName)
  28722. .each(clearAutoMargin);
  28723. }).remove();
  28724. // return early if no update menus are visible
  28725. if(menuData.length === 0) return;
  28726. // join header group
  28727. var headerGroups = menus.selectAll('g.' + constants.headerGroupClassName)
  28728. .data(menuData, keyFunction);
  28729. headerGroups.enter().append('g')
  28730. .classed(constants.headerGroupClassName, true);
  28731. // draw dropdown button container
  28732. var gButton = Lib.ensureSingle(menus, 'g', constants.dropdownButtonGroupClassName, function(s) {
  28733. s.style('pointer-events', 'all');
  28734. });
  28735. // find dimensions before plotting anything (this mutates menuOpts)
  28736. for(var i = 0; i < menuData.length; i++) {
  28737. var menuOpts = menuData[i];
  28738. findDimensions(gd, menuOpts);
  28739. }
  28740. // setup scrollbox
  28741. var scrollBoxId = 'updatemenus' + fullLayout._uid;
  28742. var scrollBox = new ScrollBox(gd, gButton, scrollBoxId);
  28743. // remove exiting header, remove dropped buttons and reset margins
  28744. if(headerGroups.enter().size()) {
  28745. // make sure gButton is on top of all headers
  28746. gButton.node().parentNode.appendChild(gButton.node());
  28747. gButton.call(removeAllButtons);
  28748. }
  28749. headerGroups.exit().each(function(menuOpts) {
  28750. gButton.call(removeAllButtons);
  28751. clearAutoMargin(menuOpts);
  28752. }).remove();
  28753. // draw headers!
  28754. headerGroups.each(function(menuOpts) {
  28755. var gHeader = d3.select(this);
  28756. var _gButton = menuOpts.type === 'dropdown' ? gButton : null;
  28757. Plots.manageCommandObserver(gd, menuOpts, menuOpts.buttons, function(data) {
  28758. setActive(gd, menuOpts, menuOpts.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true);
  28759. });
  28760. if(menuOpts.type === 'dropdown') {
  28761. drawHeader(gd, gHeader, gButton, scrollBox, menuOpts);
  28762. // if this menu is active, update the dropdown container
  28763. if(isActive(gButton, menuOpts)) {
  28764. drawButtons(gd, gHeader, gButton, scrollBox, menuOpts);
  28765. }
  28766. } else {
  28767. drawButtons(gd, gHeader, null, null, menuOpts);
  28768. }
  28769. });
  28770. };
  28771. // Note that '_index' is set at the default step,
  28772. // it corresponds to the menu index in the user layout update menu container.
  28773. // Because a menu can be set invisible,
  28774. // this is a more 'consistent' field than the index in the menuData.
  28775. function keyFunction(menuOpts) {
  28776. return menuOpts._index;
  28777. }
  28778. function isFolded(gButton) {
  28779. return +gButton.attr(constants.menuIndexAttrName) === -1;
  28780. }
  28781. function isActive(gButton, menuOpts) {
  28782. return +gButton.attr(constants.menuIndexAttrName) === menuOpts._index;
  28783. }
  28784. function setActive(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) {
  28785. // update 'active' attribute in menuOpts
  28786. menuOpts.active = buttonIndex;
  28787. // due to templating, it's possible this slider doesn't even exist yet
  28788. arrayEditor(gd.layout, constants.name, menuOpts)
  28789. .applyUpdate('active', buttonIndex);
  28790. if(menuOpts.type === 'buttons') {
  28791. drawButtons(gd, gHeader, null, null, menuOpts);
  28792. }
  28793. else if(menuOpts.type === 'dropdown') {
  28794. // fold up buttons and redraw header
  28795. gButton.attr(constants.menuIndexAttrName, '-1');
  28796. drawHeader(gd, gHeader, gButton, scrollBox, menuOpts);
  28797. if(!isSilentUpdate) {
  28798. drawButtons(gd, gHeader, gButton, scrollBox, menuOpts);
  28799. }
  28800. }
  28801. }
  28802. function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) {
  28803. var header = Lib.ensureSingle(gHeader, 'g', constants.headerClassName, function(s) {
  28804. s.style('pointer-events', 'all');
  28805. });
  28806. var dims = menuOpts._dims;
  28807. var active = menuOpts.active;
  28808. var headerOpts = menuOpts.buttons[active] || constants.blankHeaderOpts;
  28809. var posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 };
  28810. var positionOverrides = {
  28811. width: dims.headerWidth,
  28812. height: dims.headerHeight
  28813. };
  28814. header
  28815. .call(drawItem, menuOpts, headerOpts, gd)
  28816. .call(setItemPosition, menuOpts, posOpts, positionOverrides);
  28817. // draw drop arrow at the right edge
  28818. var arrow = Lib.ensureSingle(gHeader, 'text', constants.headerArrowClassName, function(s) {
  28819. s.classed('user-select-none', true)
  28820. .attr('text-anchor', 'end')
  28821. .call(Drawing.font, menuOpts.font)
  28822. .text(constants.arrowSymbol[menuOpts.direction]);
  28823. });
  28824. arrow.attr({
  28825. x: dims.headerWidth - constants.arrowOffsetX + menuOpts.pad.l,
  28826. y: dims.headerHeight / 2 + constants.textOffsetY + menuOpts.pad.t
  28827. });
  28828. header.on('click', function() {
  28829. gButton.call(removeAllButtons,
  28830. String(isActive(gButton, menuOpts) ? -1 : menuOpts._index)
  28831. );
  28832. drawButtons(gd, gHeader, gButton, scrollBox, menuOpts);
  28833. });
  28834. header.on('mouseover', function() {
  28835. header.call(styleOnMouseOver);
  28836. });
  28837. header.on('mouseout', function() {
  28838. header.call(styleOnMouseOut, menuOpts);
  28839. });
  28840. // translate header group
  28841. Drawing.setTranslate(gHeader, dims.lx, dims.ly);
  28842. }
  28843. function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) {
  28844. // If this is a set of buttons, set pointer events = all since we play
  28845. // some minor games with which container is which in order to simplify
  28846. // the drawing of *either* buttons or menus
  28847. if(!gButton) {
  28848. gButton = gHeader;
  28849. gButton.attr('pointer-events', 'all');
  28850. }
  28851. var buttonData = (!isFolded(gButton) || menuOpts.type === 'buttons') ?
  28852. menuOpts.buttons :
  28853. [];
  28854. var klass = menuOpts.type === 'dropdown' ? constants.dropdownButtonClassName : constants.buttonClassName;
  28855. var buttons = gButton.selectAll('g.' + klass)
  28856. .data(Lib.filterVisible(buttonData));
  28857. var enter = buttons.enter().append('g')
  28858. .classed(klass, true);
  28859. var exit = buttons.exit();
  28860. if(menuOpts.type === 'dropdown') {
  28861. enter.attr('opacity', '0')
  28862. .transition()
  28863. .attr('opacity', '1');
  28864. exit.transition()
  28865. .attr('opacity', '0')
  28866. .remove();
  28867. } else {
  28868. exit.remove();
  28869. }
  28870. var x0 = 0;
  28871. var y0 = 0;
  28872. var dims = menuOpts._dims;
  28873. var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1;
  28874. if(menuOpts.type === 'dropdown') {
  28875. if(isVertical) {
  28876. y0 = dims.headerHeight + constants.gapButtonHeader;
  28877. } else {
  28878. x0 = dims.headerWidth + constants.gapButtonHeader;
  28879. }
  28880. }
  28881. if(menuOpts.type === 'dropdown' && menuOpts.direction === 'up') {
  28882. y0 = -constants.gapButtonHeader + constants.gapButton - dims.openHeight;
  28883. }
  28884. if(menuOpts.type === 'dropdown' && menuOpts.direction === 'left') {
  28885. x0 = -constants.gapButtonHeader + constants.gapButton - dims.openWidth;
  28886. }
  28887. var posOpts = {
  28888. x: dims.lx + x0 + menuOpts.pad.l,
  28889. y: dims.ly + y0 + menuOpts.pad.t,
  28890. yPad: constants.gapButton,
  28891. xPad: constants.gapButton,
  28892. index: 0,
  28893. };
  28894. var scrollBoxPosition = {
  28895. l: posOpts.x + menuOpts.borderwidth,
  28896. t: posOpts.y + menuOpts.borderwidth
  28897. };
  28898. buttons.each(function(buttonOpts, buttonIndex) {
  28899. var button = d3.select(this);
  28900. button
  28901. .call(drawItem, menuOpts, buttonOpts, gd)
  28902. .call(setItemPosition, menuOpts, posOpts);
  28903. button.on('click', function() {
  28904. // skip `dragend` events
  28905. if(d3.event.defaultPrevented) return;
  28906. setActive(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex);
  28907. if(buttonOpts.execute) {
  28908. Plots.executeAPICommand(gd, buttonOpts.method, buttonOpts.args);
  28909. }
  28910. gd.emit('plotly_buttonclicked', {menu: menuOpts, button: buttonOpts, active: menuOpts.active});
  28911. });
  28912. button.on('mouseover', function() {
  28913. button.call(styleOnMouseOver);
  28914. });
  28915. button.on('mouseout', function() {
  28916. button.call(styleOnMouseOut, menuOpts);
  28917. buttons.call(styleButtons, menuOpts);
  28918. });
  28919. });
  28920. buttons.call(styleButtons, menuOpts);
  28921. if(isVertical) {
  28922. scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth);
  28923. scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t;
  28924. }
  28925. else {
  28926. scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l;
  28927. scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight);
  28928. }
  28929. scrollBoxPosition.direction = menuOpts.direction;
  28930. if(scrollBox) {
  28931. if(buttons.size()) {
  28932. drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition);
  28933. }
  28934. else {
  28935. hideScrollBox(scrollBox);
  28936. }
  28937. }
  28938. }
  28939. function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) {
  28940. // enable the scrollbox
  28941. var direction = menuOpts.direction;
  28942. var isVertical = (direction === 'up' || direction === 'down');
  28943. var dims = menuOpts._dims;
  28944. var active = menuOpts.active;
  28945. var translateX, translateY;
  28946. var i;
  28947. if(isVertical) {
  28948. translateY = 0;
  28949. for(i = 0; i < active; i++) {
  28950. translateY += dims.heights[i] + constants.gapButton;
  28951. }
  28952. }
  28953. else {
  28954. translateX = 0;
  28955. for(i = 0; i < active; i++) {
  28956. translateX += dims.widths[i] + constants.gapButton;
  28957. }
  28958. }
  28959. scrollBox.enable(position, translateX, translateY);
  28960. if(scrollBox.hbar) {
  28961. scrollBox.hbar
  28962. .attr('opacity', '0')
  28963. .transition()
  28964. .attr('opacity', '1');
  28965. }
  28966. if(scrollBox.vbar) {
  28967. scrollBox.vbar
  28968. .attr('opacity', '0')
  28969. .transition()
  28970. .attr('opacity', '1');
  28971. }
  28972. }
  28973. function hideScrollBox(scrollBox) {
  28974. var hasHBar = !!scrollBox.hbar;
  28975. var hasVBar = !!scrollBox.vbar;
  28976. if(hasHBar) {
  28977. scrollBox.hbar
  28978. .transition()
  28979. .attr('opacity', '0')
  28980. .each('end', function() {
  28981. hasHBar = false;
  28982. if(!hasVBar) scrollBox.disable();
  28983. });
  28984. }
  28985. if(hasVBar) {
  28986. scrollBox.vbar
  28987. .transition()
  28988. .attr('opacity', '0')
  28989. .each('end', function() {
  28990. hasVBar = false;
  28991. if(!hasHBar) scrollBox.disable();
  28992. });
  28993. }
  28994. }
  28995. function drawItem(item, menuOpts, itemOpts, gd) {
  28996. item.call(drawItemRect, menuOpts)
  28997. .call(drawItemText, menuOpts, itemOpts, gd);
  28998. }
  28999. function drawItemRect(item, menuOpts) {
  29000. var rect = Lib.ensureSingle(item, 'rect', constants.itemRectClassName, function(s) {
  29001. s.attr({
  29002. rx: constants.rx,
  29003. ry: constants.ry,
  29004. 'shape-rendering': 'crispEdges'
  29005. });
  29006. });
  29007. rect.call(Color.stroke, menuOpts.bordercolor)
  29008. .call(Color.fill, menuOpts.bgcolor)
  29009. .style('stroke-width', menuOpts.borderwidth + 'px');
  29010. }
  29011. function drawItemText(item, menuOpts, itemOpts, gd) {
  29012. var text = Lib.ensureSingle(item, 'text', constants.itemTextClassName, function(s) {
  29013. s.classed('user-select-none', true)
  29014. .attr({
  29015. 'text-anchor': 'start',
  29016. 'data-notex': 1
  29017. });
  29018. });
  29019. text.call(Drawing.font, menuOpts.font)
  29020. .text(itemOpts.label)
  29021. .call(svgTextUtils.convertToTspans, gd);
  29022. }
  29023. function styleButtons(buttons, menuOpts) {
  29024. var active = menuOpts.active;
  29025. buttons.each(function(buttonOpts, i) {
  29026. var button = d3.select(this);
  29027. if(i === active && menuOpts.showactive) {
  29028. button.select('rect.' + constants.itemRectClassName)
  29029. .call(Color.fill, constants.activeColor);
  29030. }
  29031. });
  29032. }
  29033. function styleOnMouseOver(item) {
  29034. item.select('rect.' + constants.itemRectClassName)
  29035. .call(Color.fill, constants.hoverColor);
  29036. }
  29037. function styleOnMouseOut(item, menuOpts) {
  29038. item.select('rect.' + constants.itemRectClassName)
  29039. .call(Color.fill, menuOpts.bgcolor);
  29040. }
  29041. // find item dimensions (this mutates menuOpts)
  29042. function findDimensions(gd, menuOpts) {
  29043. var dims = menuOpts._dims = {
  29044. width1: 0,
  29045. height1: 0,
  29046. heights: [],
  29047. widths: [],
  29048. totalWidth: 0,
  29049. totalHeight: 0,
  29050. openWidth: 0,
  29051. openHeight: 0,
  29052. lx: 0,
  29053. ly: 0
  29054. };
  29055. var fakeButtons = Drawing.tester.selectAll('g.' + constants.dropdownButtonClassName)
  29056. .data(Lib.filterVisible(menuOpts.buttons));
  29057. fakeButtons.enter().append('g')
  29058. .classed(constants.dropdownButtonClassName, true);
  29059. var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1;
  29060. // loop over fake buttons to find width / height
  29061. fakeButtons.each(function(buttonOpts, i) {
  29062. var button = d3.select(this);
  29063. button.call(drawItem, menuOpts, buttonOpts, gd);
  29064. var text = button.select('.' + constants.itemTextClassName);
  29065. // width is given by max width of all buttons
  29066. var tWidth = text.node() && Drawing.bBox(text.node()).width;
  29067. var wEff = Math.max(tWidth + constants.textPadX, constants.minWidth);
  29068. // height is determined by item text
  29069. var tHeight = menuOpts.font.size * LINE_SPACING;
  29070. var tLines = svgTextUtils.lineCount(text);
  29071. var hEff = Math.max(tHeight * tLines, constants.minHeight) + constants.textOffsetY;
  29072. hEff = Math.ceil(hEff);
  29073. wEff = Math.ceil(wEff);
  29074. // Store per-item sizes since a row of horizontal buttons, for example,
  29075. // don't all need to be the same width:
  29076. dims.widths[i] = wEff;
  29077. dims.heights[i] = hEff;
  29078. // Height and width of individual element:
  29079. dims.height1 = Math.max(dims.height1, hEff);
  29080. dims.width1 = Math.max(dims.width1, wEff);
  29081. if(isVertical) {
  29082. dims.totalWidth = Math.max(dims.totalWidth, wEff);
  29083. dims.openWidth = dims.totalWidth;
  29084. dims.totalHeight += hEff + constants.gapButton;
  29085. dims.openHeight += hEff + constants.gapButton;
  29086. } else {
  29087. dims.totalWidth += wEff + constants.gapButton;
  29088. dims.openWidth += wEff + constants.gapButton;
  29089. dims.totalHeight = Math.max(dims.totalHeight, hEff);
  29090. dims.openHeight = dims.totalHeight;
  29091. }
  29092. });
  29093. if(isVertical) {
  29094. dims.totalHeight -= constants.gapButton;
  29095. } else {
  29096. dims.totalWidth -= constants.gapButton;
  29097. }
  29098. dims.headerWidth = dims.width1 + constants.arrowPadX;
  29099. dims.headerHeight = dims.height1;
  29100. if(menuOpts.type === 'dropdown') {
  29101. if(isVertical) {
  29102. dims.width1 += constants.arrowPadX;
  29103. dims.totalHeight = dims.height1;
  29104. } else {
  29105. dims.totalWidth = dims.width1;
  29106. }
  29107. dims.totalWidth += constants.arrowPadX;
  29108. }
  29109. fakeButtons.remove();
  29110. var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r;
  29111. var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b;
  29112. var graphSize = gd._fullLayout._size;
  29113. dims.lx = graphSize.l + graphSize.w * menuOpts.x;
  29114. dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y);
  29115. var xanchor = 'left';
  29116. if(Lib.isRightAnchor(menuOpts)) {
  29117. dims.lx -= paddedWidth;
  29118. xanchor = 'right';
  29119. }
  29120. if(Lib.isCenterAnchor(menuOpts)) {
  29121. dims.lx -= paddedWidth / 2;
  29122. xanchor = 'center';
  29123. }
  29124. var yanchor = 'top';
  29125. if(Lib.isBottomAnchor(menuOpts)) {
  29126. dims.ly -= paddedHeight;
  29127. yanchor = 'bottom';
  29128. }
  29129. if(Lib.isMiddleAnchor(menuOpts)) {
  29130. dims.ly -= paddedHeight / 2;
  29131. yanchor = 'middle';
  29132. }
  29133. dims.totalWidth = Math.ceil(dims.totalWidth);
  29134. dims.totalHeight = Math.ceil(dims.totalHeight);
  29135. dims.lx = Math.round(dims.lx);
  29136. dims.ly = Math.round(dims.ly);
  29137. Plots.autoMargin(gd, autoMarginId(menuOpts), {
  29138. x: menuOpts.x,
  29139. y: menuOpts.y,
  29140. l: paddedWidth * ({right: 1, center: 0.5}[xanchor] || 0),
  29141. r: paddedWidth * ({left: 1, center: 0.5}[xanchor] || 0),
  29142. b: paddedHeight * ({top: 1, middle: 0.5}[yanchor] || 0),
  29143. t: paddedHeight * ({bottom: 1, middle: 0.5}[yanchor] || 0)
  29144. });
  29145. }
  29146. function autoMarginId(menuOpts) {
  29147. return constants.autoMarginIdRoot + menuOpts._index;
  29148. }
  29149. // set item positions (mutates posOpts)
  29150. function setItemPosition(item, menuOpts, posOpts, overrideOpts) {
  29151. overrideOpts = overrideOpts || {};
  29152. var rect = item.select('.' + constants.itemRectClassName);
  29153. var text = item.select('.' + constants.itemTextClassName);
  29154. var borderWidth = menuOpts.borderwidth;
  29155. var index = posOpts.index;
  29156. var dims = menuOpts._dims;
  29157. Drawing.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y);
  29158. var isVertical = ['up', 'down'].indexOf(menuOpts.direction) !== -1;
  29159. var finalHeight = overrideOpts.height || (isVertical ? dims.heights[index] : dims.height1);
  29160. rect.attr({
  29161. x: 0,
  29162. y: 0,
  29163. width: overrideOpts.width || (isVertical ? dims.width1 : dims.widths[index]),
  29164. height: finalHeight
  29165. });
  29166. var tHeight = menuOpts.font.size * LINE_SPACING;
  29167. var tLines = svgTextUtils.lineCount(text);
  29168. var spanOffset = ((tLines - 1) * tHeight / 2);
  29169. svgTextUtils.positionText(text, constants.textOffsetX,
  29170. finalHeight / 2 - spanOffset + constants.textOffsetY);
  29171. if(isVertical) {
  29172. posOpts.y += dims.heights[index] + posOpts.yPad;
  29173. } else {
  29174. posOpts.x += dims.widths[index] + posOpts.xPad;
  29175. }
  29176. posOpts.index++;
  29177. }
  29178. function removeAllButtons(gButton, newMenuIndexAttr) {
  29179. gButton
  29180. .attr(constants.menuIndexAttrName, newMenuIndexAttr || '-1')
  29181. .selectAll('g.' + constants.dropdownButtonClassName).remove();
  29182. }
  29183. },{"../../constants/alignment":146,"../../lib":168,"../../lib/svg_text_utils":189,"../../plot_api/plot_template":202,"../../plots/plots":245,"../color":51,"../drawing":72,"./constants":141,"./scrollbox":145,"d3":16}],144:[function(_dereq_,module,exports){
  29184. arguments[4][138][0].apply(exports,arguments)
  29185. },{"./attributes":140,"./constants":141,"./defaults":142,"./draw":143,"dup":138}],145:[function(_dereq_,module,exports){
  29186. /**
  29187. * Copyright 2012-2019, Plotly, Inc.
  29188. * All rights reserved.
  29189. *
  29190. * This source code is licensed under the MIT license found in the
  29191. * LICENSE file in the root directory of this source tree.
  29192. */
  29193. 'use strict';
  29194. module.exports = ScrollBox;
  29195. var d3 = _dereq_('d3');
  29196. var Color = _dereq_('../color');
  29197. var Drawing = _dereq_('../drawing');
  29198. var Lib = _dereq_('../../lib');
  29199. /**
  29200. * Helper class to setup a scroll box
  29201. *
  29202. * @class
  29203. * @param gd Plotly's graph div
  29204. * @param container Container to be scroll-boxed (as a D3 selection)
  29205. * @param {string} id Id for the clip path to implement the scroll box
  29206. */
  29207. function ScrollBox(gd, container, id) {
  29208. this.gd = gd;
  29209. this.container = container;
  29210. this.id = id;
  29211. // See ScrollBox.prototype.enable for further definition
  29212. this.position = null; // scrollbox position
  29213. this.translateX = null; // scrollbox horizontal translation
  29214. this.translateY = null; // scrollbox vertical translation
  29215. this.hbar = null; // horizontal scrollbar D3 selection
  29216. this.vbar = null; // vertical scrollbar D3 selection
  29217. // <rect> element to capture pointer events
  29218. this.bg = this.container.selectAll('rect.scrollbox-bg').data([0]);
  29219. this.bg.exit()
  29220. .on('.drag', null)
  29221. .on('wheel', null)
  29222. .remove();
  29223. this.bg.enter().append('rect')
  29224. .classed('scrollbox-bg', true)
  29225. .style('pointer-events', 'all')
  29226. .attr({
  29227. opacity: 0,
  29228. x: 0,
  29229. y: 0,
  29230. width: 0,
  29231. height: 0
  29232. });
  29233. }
  29234. // scroll bar dimensions
  29235. ScrollBox.barWidth = 2;
  29236. ScrollBox.barLength = 20;
  29237. ScrollBox.barRadius = 2;
  29238. ScrollBox.barPad = 1;
  29239. ScrollBox.barColor = '#808BA4';
  29240. /**
  29241. * If needed, setup a clip path and scrollbars
  29242. *
  29243. * @method
  29244. * @param {Object} position
  29245. * @param {number} position.l Left side position (in pixels)
  29246. * @param {number} position.t Top side (in pixels)
  29247. * @param {number} position.w Width (in pixels)
  29248. * @param {number} position.h Height (in pixels)
  29249. * @param {string} [position.direction='down']
  29250. * Either 'down', 'left', 'right' or 'up'
  29251. * @param {number} [translateX=0] Horizontal offset (in pixels)
  29252. * @param {number} [translateY=0] Vertical offset (in pixels)
  29253. */
  29254. ScrollBox.prototype.enable = function enable(position, translateX, translateY) {
  29255. var fullLayout = this.gd._fullLayout;
  29256. var fullWidth = fullLayout.width;
  29257. var fullHeight = fullLayout.height;
  29258. // compute position of scrollbox
  29259. this.position = position;
  29260. var l = this.position.l;
  29261. var w = this.position.w;
  29262. var t = this.position.t;
  29263. var h = this.position.h;
  29264. var direction = this.position.direction;
  29265. var isDown = (direction === 'down');
  29266. var isLeft = (direction === 'left');
  29267. var isRight = (direction === 'right');
  29268. var isUp = (direction === 'up');
  29269. var boxW = w;
  29270. var boxH = h;
  29271. var boxL, boxR;
  29272. var boxT, boxB;
  29273. if(!isDown && !isLeft && !isRight && !isUp) {
  29274. this.position.direction = 'down';
  29275. isDown = true;
  29276. }
  29277. var isVertical = isDown || isUp;
  29278. if(isVertical) {
  29279. boxL = l;
  29280. boxR = boxL + boxW;
  29281. if(isDown) {
  29282. // anchor to top side
  29283. boxT = t;
  29284. boxB = Math.min(boxT + boxH, fullHeight);
  29285. boxH = boxB - boxT;
  29286. }
  29287. else {
  29288. // anchor to bottom side
  29289. boxB = t + boxH;
  29290. boxT = Math.max(boxB - boxH, 0);
  29291. boxH = boxB - boxT;
  29292. }
  29293. }
  29294. else {
  29295. boxT = t;
  29296. boxB = boxT + boxH;
  29297. if(isLeft) {
  29298. // anchor to right side
  29299. boxR = l + boxW;
  29300. boxL = Math.max(boxR - boxW, 0);
  29301. boxW = boxR - boxL;
  29302. }
  29303. else {
  29304. // anchor to left side
  29305. boxL = l;
  29306. boxR = Math.min(boxL + boxW, fullWidth);
  29307. boxW = boxR - boxL;
  29308. }
  29309. }
  29310. this._box = {
  29311. l: boxL,
  29312. t: boxT,
  29313. w: boxW,
  29314. h: boxH
  29315. };
  29316. // compute position of horizontal scroll bar
  29317. var needsHorizontalScrollBar = (w > boxW);
  29318. var hbarW = ScrollBox.barLength + 2 * ScrollBox.barPad;
  29319. var hbarH = ScrollBox.barWidth + 2 * ScrollBox.barPad;
  29320. // draw horizontal scrollbar on the bottom side
  29321. var hbarL = l;
  29322. var hbarT = t + h;
  29323. if(hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH;
  29324. var hbar = this.container.selectAll('rect.scrollbar-horizontal').data(
  29325. (needsHorizontalScrollBar) ? [0] : []);
  29326. hbar.exit()
  29327. .on('.drag', null)
  29328. .remove();
  29329. hbar.enter().append('rect')
  29330. .classed('scrollbar-horizontal', true)
  29331. .call(Color.fill, ScrollBox.barColor);
  29332. if(needsHorizontalScrollBar) {
  29333. this.hbar = hbar.attr({
  29334. 'rx': ScrollBox.barRadius,
  29335. 'ry': ScrollBox.barRadius,
  29336. 'x': hbarL,
  29337. 'y': hbarT,
  29338. 'width': hbarW,
  29339. 'height': hbarH
  29340. });
  29341. // hbar center moves between hbarXMin and hbarXMin + hbarTranslateMax
  29342. this._hbarXMin = hbarL + hbarW / 2;
  29343. this._hbarTranslateMax = boxW - hbarW;
  29344. }
  29345. else {
  29346. delete this.hbar;
  29347. delete this._hbarXMin;
  29348. delete this._hbarTranslateMax;
  29349. }
  29350. // compute position of vertical scroll bar
  29351. var needsVerticalScrollBar = (h > boxH);
  29352. var vbarW = ScrollBox.barWidth + 2 * ScrollBox.barPad;
  29353. var vbarH = ScrollBox.barLength + 2 * ScrollBox.barPad;
  29354. // draw vertical scrollbar on the right side
  29355. var vbarL = l + w;
  29356. var vbarT = t;
  29357. if(vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW;
  29358. var vbar = this.container.selectAll('rect.scrollbar-vertical').data(
  29359. (needsVerticalScrollBar) ? [0] : []);
  29360. vbar.exit()
  29361. .on('.drag', null)
  29362. .remove();
  29363. vbar.enter().append('rect')
  29364. .classed('scrollbar-vertical', true)
  29365. .call(Color.fill, ScrollBox.barColor);
  29366. if(needsVerticalScrollBar) {
  29367. this.vbar = vbar.attr({
  29368. 'rx': ScrollBox.barRadius,
  29369. 'ry': ScrollBox.barRadius,
  29370. 'x': vbarL,
  29371. 'y': vbarT,
  29372. 'width': vbarW,
  29373. 'height': vbarH
  29374. });
  29375. // vbar center moves between vbarYMin and vbarYMin + vbarTranslateMax
  29376. this._vbarYMin = vbarT + vbarH / 2;
  29377. this._vbarTranslateMax = boxH - vbarH;
  29378. }
  29379. else {
  29380. delete this.vbar;
  29381. delete this._vbarYMin;
  29382. delete this._vbarTranslateMax;
  29383. }
  29384. // setup a clip path (if scroll bars are needed)
  29385. var clipId = this.id;
  29386. var clipL = boxL - 0.5;
  29387. var clipR = (needsVerticalScrollBar) ? boxR + vbarW + 0.5 : boxR + 0.5;
  29388. var clipT = boxT - 0.5;
  29389. var clipB = (needsHorizontalScrollBar) ? boxB + hbarH + 0.5 : boxB + 0.5;
  29390. var clipPath = fullLayout._topdefs.selectAll('#' + clipId)
  29391. .data((needsHorizontalScrollBar || needsVerticalScrollBar) ? [0] : []);
  29392. clipPath.exit().remove();
  29393. clipPath.enter()
  29394. .append('clipPath').attr('id', clipId)
  29395. .append('rect');
  29396. if(needsHorizontalScrollBar || needsVerticalScrollBar) {
  29397. this._clipRect = clipPath.select('rect').attr({
  29398. x: Math.floor(clipL),
  29399. y: Math.floor(clipT),
  29400. width: Math.ceil(clipR) - Math.floor(clipL),
  29401. height: Math.ceil(clipB) - Math.floor(clipT)
  29402. });
  29403. this.container.call(Drawing.setClipUrl, clipId, this.gd);
  29404. this.bg.attr({
  29405. x: l,
  29406. y: t,
  29407. width: w,
  29408. height: h
  29409. });
  29410. }
  29411. else {
  29412. this.bg.attr({
  29413. width: 0,
  29414. height: 0
  29415. });
  29416. this.container
  29417. .on('wheel', null)
  29418. .on('.drag', null)
  29419. .call(Drawing.setClipUrl, null);
  29420. delete this._clipRect;
  29421. }
  29422. // set up drag listeners (if scroll bars are needed)
  29423. if(needsHorizontalScrollBar || needsVerticalScrollBar) {
  29424. var onBoxDrag = d3.behavior.drag()
  29425. .on('dragstart', function() {
  29426. d3.event.sourceEvent.preventDefault();
  29427. })
  29428. .on('drag', this._onBoxDrag.bind(this));
  29429. this.container
  29430. .on('wheel', null)
  29431. .on('wheel', this._onBoxWheel.bind(this))
  29432. .on('.drag', null)
  29433. .call(onBoxDrag);
  29434. var onBarDrag = d3.behavior.drag()
  29435. .on('dragstart', function() {
  29436. d3.event.sourceEvent.preventDefault();
  29437. d3.event.sourceEvent.stopPropagation();
  29438. })
  29439. .on('drag', this._onBarDrag.bind(this));
  29440. if(needsHorizontalScrollBar) {
  29441. this.hbar
  29442. .on('.drag', null)
  29443. .call(onBarDrag);
  29444. }
  29445. if(needsVerticalScrollBar) {
  29446. this.vbar
  29447. .on('.drag', null)
  29448. .call(onBarDrag);
  29449. }
  29450. }
  29451. // set scrollbox translation
  29452. this.setTranslate(translateX, translateY);
  29453. };
  29454. /**
  29455. * If present, remove clip-path and scrollbars
  29456. *
  29457. * @method
  29458. */
  29459. ScrollBox.prototype.disable = function disable() {
  29460. if(this.hbar || this.vbar) {
  29461. this.bg.attr({
  29462. width: 0,
  29463. height: 0
  29464. });
  29465. this.container
  29466. .on('wheel', null)
  29467. .on('.drag', null)
  29468. .call(Drawing.setClipUrl, null);
  29469. delete this._clipRect;
  29470. }
  29471. if(this.hbar) {
  29472. this.hbar.on('.drag', null);
  29473. this.hbar.remove();
  29474. delete this.hbar;
  29475. delete this._hbarXMin;
  29476. delete this._hbarTranslateMax;
  29477. }
  29478. if(this.vbar) {
  29479. this.vbar.on('.drag', null);
  29480. this.vbar.remove();
  29481. delete this.vbar;
  29482. delete this._vbarYMin;
  29483. delete this._vbarTranslateMax;
  29484. }
  29485. };
  29486. /**
  29487. * Handles scroll box drag events
  29488. *
  29489. * @method
  29490. */
  29491. ScrollBox.prototype._onBoxDrag = function onBarDrag() {
  29492. var translateX = this.translateX;
  29493. var translateY = this.translateY;
  29494. if(this.hbar) {
  29495. translateX -= d3.event.dx;
  29496. }
  29497. if(this.vbar) {
  29498. translateY -= d3.event.dy;
  29499. }
  29500. this.setTranslate(translateX, translateY);
  29501. };
  29502. /**
  29503. * Handles scroll box wheel events
  29504. *
  29505. * @method
  29506. */
  29507. ScrollBox.prototype._onBoxWheel = function onBarWheel() {
  29508. var translateX = this.translateX;
  29509. var translateY = this.translateY;
  29510. if(this.hbar) {
  29511. translateX += d3.event.deltaY;
  29512. }
  29513. if(this.vbar) {
  29514. translateY += d3.event.deltaY;
  29515. }
  29516. this.setTranslate(translateX, translateY);
  29517. };
  29518. /**
  29519. * Handles scroll bar drag events
  29520. *
  29521. * @method
  29522. */
  29523. ScrollBox.prototype._onBarDrag = function onBarDrag() {
  29524. var translateX = this.translateX;
  29525. var translateY = this.translateY;
  29526. if(this.hbar) {
  29527. var xMin = translateX + this._hbarXMin;
  29528. var xMax = xMin + this._hbarTranslateMax;
  29529. var x = Lib.constrain(d3.event.x, xMin, xMax);
  29530. var xf = (x - xMin) / (xMax - xMin);
  29531. var translateXMax = this.position.w - this._box.w;
  29532. translateX = xf * translateXMax;
  29533. }
  29534. if(this.vbar) {
  29535. var yMin = translateY + this._vbarYMin;
  29536. var yMax = yMin + this._vbarTranslateMax;
  29537. var y = Lib.constrain(d3.event.y, yMin, yMax);
  29538. var yf = (y - yMin) / (yMax - yMin);
  29539. var translateYMax = this.position.h - this._box.h;
  29540. translateY = yf * translateYMax;
  29541. }
  29542. this.setTranslate(translateX, translateY);
  29543. };
  29544. /**
  29545. * Set clip path and scroll bar translate transform
  29546. *
  29547. * @method
  29548. * @param {number} [translateX=0] Horizontal offset (in pixels)
  29549. * @param {number} [translateY=0] Vertical offset (in pixels)
  29550. */
  29551. ScrollBox.prototype.setTranslate = function setTranslate(translateX, translateY) {
  29552. // store translateX and translateY (needed by mouse event handlers)
  29553. var translateXMax = this.position.w - this._box.w;
  29554. var translateYMax = this.position.h - this._box.h;
  29555. translateX = Lib.constrain(translateX || 0, 0, translateXMax);
  29556. translateY = Lib.constrain(translateY || 0, 0, translateYMax);
  29557. this.translateX = translateX;
  29558. this.translateY = translateY;
  29559. this.container.call(Drawing.setTranslate,
  29560. this._box.l - this.position.l - translateX,
  29561. this._box.t - this.position.t - translateY);
  29562. if(this._clipRect) {
  29563. this._clipRect.attr({
  29564. x: Math.floor(this.position.l + translateX - 0.5),
  29565. y: Math.floor(this.position.t + translateY - 0.5)
  29566. });
  29567. }
  29568. if(this.hbar) {
  29569. var xf = translateX / translateXMax;
  29570. this.hbar.call(Drawing.setTranslate,
  29571. translateX + xf * this._hbarTranslateMax,
  29572. translateY);
  29573. }
  29574. if(this.vbar) {
  29575. var yf = translateY / translateYMax;
  29576. this.vbar.call(Drawing.setTranslate,
  29577. translateX,
  29578. translateY + yf * this._vbarTranslateMax);
  29579. }
  29580. };
  29581. },{"../../lib":168,"../color":51,"../drawing":72,"d3":16}],146:[function(_dereq_,module,exports){
  29582. /**
  29583. * Copyright 2012-2019, Plotly, Inc.
  29584. * All rights reserved.
  29585. *
  29586. * This source code is licensed under the MIT license found in the
  29587. * LICENSE file in the root directory of this source tree.
  29588. */
  29589. 'use strict';
  29590. // fraction of some size to get to a named position
  29591. module.exports = {
  29592. // from bottom left: this is the origin of our paper-reference
  29593. // positioning system
  29594. FROM_BL: {
  29595. left: 0,
  29596. center: 0.5,
  29597. right: 1,
  29598. bottom: 0,
  29599. middle: 0.5,
  29600. top: 1
  29601. },
  29602. // from top left: this is the screen pixel positioning origin
  29603. FROM_TL: {
  29604. left: 0,
  29605. center: 0.5,
  29606. right: 1,
  29607. bottom: 1,
  29608. middle: 0.5,
  29609. top: 0
  29610. },
  29611. // from bottom right: sometimes you just need the opposite of ^^
  29612. FROM_BR: {
  29613. left: 1,
  29614. center: 0.5,
  29615. right: 0,
  29616. bottom: 0,
  29617. middle: 0.5,
  29618. top: 1
  29619. },
  29620. // multiple of fontSize to get the vertical offset between lines
  29621. LINE_SPACING: 1.3,
  29622. // multiple of fontSize to shift from the baseline
  29623. // to the cap (captical letter) line
  29624. // (to use when we don't calculate this shift from Drawing.bBox)
  29625. // This is an approximation since in reality cap height can differ
  29626. // from font to font. However, according to Wikipedia
  29627. // an "average" font might have a cap height of 70% of the em
  29628. // https://en.wikipedia.org/wiki/Em_(typography)#History
  29629. CAP_SHIFT: 0.70,
  29630. // half the cap height (distance between baseline and cap line)
  29631. // of an "average" font (for more info see above).
  29632. MID_SHIFT: 0.35,
  29633. OPPOSITE_SIDE: {
  29634. left: 'right',
  29635. right: 'left',
  29636. top: 'bottom',
  29637. bottom: 'top'
  29638. }
  29639. };
  29640. },{}],147:[function(_dereq_,module,exports){
  29641. /**
  29642. * Copyright 2012-2019, Plotly, Inc.
  29643. * All rights reserved.
  29644. *
  29645. * This source code is licensed under the MIT license found in the
  29646. * LICENSE file in the root directory of this source tree.
  29647. */
  29648. 'use strict';
  29649. module.exports = {
  29650. COMPARISON_OPS: ['=', '!=', '<', '>=', '>', '<='],
  29651. COMPARISON_OPS2: ['=', '<', '>=', '>', '<='],
  29652. INTERVAL_OPS: ['[]', '()', '[)', '(]', '][', ')(', '](', ')['],
  29653. SET_OPS: ['{}', '}{'],
  29654. CONSTRAINT_REDUCTION: {
  29655. // for contour constraints, open/closed endpoints are equivalent
  29656. '=': '=',
  29657. '<': '<',
  29658. '<=': '<',
  29659. '>': '>',
  29660. '>=': '>',
  29661. '[]': '[]',
  29662. '()': '[]',
  29663. '[)': '[]',
  29664. '(]': '[]',
  29665. '][': '][',
  29666. ')(': '][',
  29667. '](': '][',
  29668. ')[': ']['
  29669. }
  29670. };
  29671. },{}],148:[function(_dereq_,module,exports){
  29672. /**
  29673. * Copyright 2012-2019, Plotly, Inc.
  29674. * All rights reserved.
  29675. *
  29676. * This source code is licensed under the MIT license found in the
  29677. * LICENSE file in the root directory of this source tree.
  29678. */
  29679. 'use strict';
  29680. module.exports = {
  29681. /**
  29682. * Timing information for interactive elements
  29683. */
  29684. SHOW_PLACEHOLDER: 100,
  29685. HIDE_PLACEHOLDER: 1000,
  29686. // ms between first mousedown and 2nd mouseup to constitute dblclick...
  29687. // we don't seem to have access to the system setting
  29688. DBLCLICKDELAY: 300,
  29689. // opacity dimming fraction for points that are not in selection
  29690. DESELECTDIM: 0.2
  29691. };
  29692. },{}],149:[function(_dereq_,module,exports){
  29693. /**
  29694. * Copyright 2012-2019, Plotly, Inc.
  29695. * All rights reserved.
  29696. *
  29697. * This source code is licensed under the MIT license found in the
  29698. * LICENSE file in the root directory of this source tree.
  29699. */
  29700. 'use strict';
  29701. module.exports = {
  29702. /**
  29703. * Standardize all missing data in calcdata to use undefined
  29704. * never null or NaN.
  29705. * That way we can use !==undefined, or !== BADNUM,
  29706. * to test for real data
  29707. */
  29708. BADNUM: undefined,
  29709. /*
  29710. * Limit certain operations to well below floating point max value
  29711. * to avoid glitches: Make sure that even when you multiply it by the
  29712. * number of pixels on a giant screen it still works
  29713. */
  29714. FP_SAFE: Number.MAX_VALUE / 10000,
  29715. /*
  29716. * conversion of date units to milliseconds
  29717. * year and month constants are marked "AVG"
  29718. * to remind us that not all years and months
  29719. * have the same length
  29720. */
  29721. ONEAVGYEAR: 31557600000, // 365.25 days
  29722. ONEAVGMONTH: 2629800000, // 1/12 of ONEAVGYEAR
  29723. ONEDAY: 86400000,
  29724. ONEHOUR: 3600000,
  29725. ONEMIN: 60000,
  29726. ONESEC: 1000,
  29727. /*
  29728. * For fast conversion btwn world calendars and epoch ms, the Julian Day Number
  29729. * of the unix epoch. From calendars.instance().newDate(1970, 1, 1).toJD()
  29730. */
  29731. EPOCHJD: 2440587.5,
  29732. /*
  29733. * Are two values nearly equal? Compare to 1PPM
  29734. */
  29735. ALMOST_EQUAL: 1 - 1e-6,
  29736. /*
  29737. * If we're asked to clip a non-positive log value, how far off-screen
  29738. * do we put it?
  29739. */
  29740. LOG_CLIP: 10,
  29741. /*
  29742. * not a number, but for displaying numbers: the "minus sign" symbol is
  29743. * wider than the regular ascii dash "-"
  29744. */
  29745. MINUS_SIGN: '\u2212'
  29746. };
  29747. },{}],150:[function(_dereq_,module,exports){
  29748. /**
  29749. * Copyright 2012-2019, Plotly, Inc.
  29750. * All rights reserved.
  29751. *
  29752. * This source code is licensed under the MIT license found in the
  29753. * LICENSE file in the root directory of this source tree.
  29754. */
  29755. 'use strict';
  29756. exports.xmlns = 'http://www.w3.org/2000/xmlns/';
  29757. exports.svg = 'http://www.w3.org/2000/svg';
  29758. exports.xlink = 'http://www.w3.org/1999/xlink';
  29759. // the 'old' d3 quirk got fix in v3.5.7
  29760. // https://github.com/mbostock/d3/commit/a6f66e9dd37f764403fc7c1f26be09ab4af24fed
  29761. exports.svgAttrs = {
  29762. xmlns: exports.svg,
  29763. 'xmlns:xlink': exports.xlink
  29764. };
  29765. },{}],151:[function(_dereq_,module,exports){
  29766. /**
  29767. * Copyright 2012-2019, Plotly, Inc.
  29768. * All rights reserved.
  29769. *
  29770. * This source code is licensed under the MIT license found in the
  29771. * LICENSE file in the root directory of this source tree.
  29772. */
  29773. 'use strict';
  29774. // package version injected by `npm run preprocess`
  29775. exports.version = '1.44.4';
  29776. // inject promise polyfill
  29777. _dereq_('es6-promise').polyfill();
  29778. // inject plot css
  29779. _dereq_('../build/plotcss');
  29780. // inject default MathJax config
  29781. _dereq_('./fonts/mathjax_config')();
  29782. // include registry module and expose register method
  29783. var Registry = _dereq_('./registry');
  29784. var register = exports.register = Registry.register;
  29785. // expose plot api methods
  29786. var plotApi = _dereq_('./plot_api');
  29787. var methodNames = Object.keys(plotApi);
  29788. for(var i = 0; i < methodNames.length; i++) {
  29789. var name = methodNames[i];
  29790. // _ -> private API methods, but still registered for internal use
  29791. if(name.charAt(0) !== '_') exports[name] = plotApi[name];
  29792. register({
  29793. moduleType: 'apiMethod',
  29794. name: name,
  29795. fn: plotApi[name]
  29796. });
  29797. }
  29798. // scatter is the only trace included by default
  29799. register(_dereq_('./traces/scatter'));
  29800. // register all registrable components modules
  29801. register([
  29802. _dereq_('./components/fx'),
  29803. _dereq_('./components/legend'),
  29804. _dereq_('./components/annotations'),
  29805. _dereq_('./components/annotations3d'),
  29806. _dereq_('./components/shapes'),
  29807. _dereq_('./components/images'),
  29808. _dereq_('./components/updatemenus'),
  29809. _dereq_('./components/sliders'),
  29810. _dereq_('./components/rangeslider'),
  29811. _dereq_('./components/rangeselector'),
  29812. _dereq_('./components/grid'),
  29813. _dereq_('./components/errorbars'),
  29814. _dereq_('./components/colorscale')
  29815. ]);
  29816. // locales en and en-US are required for default behavior
  29817. register([
  29818. _dereq_('./locale-en'),
  29819. _dereq_('./locale-en-us')
  29820. ]);
  29821. // plot icons
  29822. exports.Icons = _dereq_('../build/ploticon');
  29823. // unofficial 'beta' plot methods, use at your own risk
  29824. exports.Plots = _dereq_('./plots/plots');
  29825. exports.Fx = _dereq_('./components/fx');
  29826. exports.Snapshot = _dereq_('./snapshot');
  29827. exports.PlotSchema = _dereq_('./plot_api/plot_schema');
  29828. exports.Queue = _dereq_('./lib/queue');
  29829. // export d3 used in the bundle
  29830. exports.d3 = _dereq_('d3');
  29831. },{"../build/plotcss":1,"../build/ploticon":2,"./components/annotations":44,"./components/annotations3d":49,"./components/colorscale":63,"./components/errorbars":78,"./components/fx":90,"./components/grid":94,"./components/images":99,"./components/legend":107,"./components/rangeselector":118,"./components/rangeslider":125,"./components/shapes":133,"./components/sliders":138,"./components/updatemenus":144,"./fonts/mathjax_config":152,"./lib/queue":182,"./locale-en":193,"./locale-en-us":192,"./plot_api":197,"./plot_api/plot_schema":201,"./plots/plots":245,"./registry":257,"./snapshot":262,"./traces/scatter":379,"d3":16,"es6-promise":17}],152:[function(_dereq_,module,exports){
  29832. /**
  29833. * Copyright 2012-2019, Plotly, Inc.
  29834. * All rights reserved.
  29835. *
  29836. * This source code is licensed under the MIT license found in the
  29837. * LICENSE file in the root directory of this source tree.
  29838. */
  29839. 'use strict';
  29840. /* global MathJax:false */
  29841. module.exports = function() {
  29842. if(typeof MathJax !== 'undefined') {
  29843. var globalConfig = (window.PlotlyConfig || {}).MathJaxConfig !== 'local';
  29844. if(globalConfig) {
  29845. MathJax.Hub.Config({
  29846. messageStyle: 'none',
  29847. skipStartupTypeset: true,
  29848. displayAlign: 'left',
  29849. tex2jax: {
  29850. inlineMath: [['$', '$'], ['\\(', '\\)']]
  29851. }
  29852. });
  29853. MathJax.Hub.Configured();
  29854. }
  29855. }
  29856. };
  29857. },{}],153:[function(_dereq_,module,exports){
  29858. /**
  29859. * Copyright 2012-2019, Plotly, Inc.
  29860. * All rights reserved.
  29861. *
  29862. * This source code is licensed under the MIT license found in the
  29863. * LICENSE file in the root directory of this source tree.
  29864. */
  29865. 'use strict';
  29866. /**
  29867. * Determine the position anchor property of x/y xanchor/yanchor components.
  29868. *
  29869. * - values < 1/3 align the low side at that fraction,
  29870. * - values [1/3, 2/3] align the center at that fraction,
  29871. * - values > 2/3 align the right at that fraction.
  29872. */
  29873. exports.isLeftAnchor = function isLeftAnchor(opts) {
  29874. return (
  29875. opts.xanchor === 'left' ||
  29876. (opts.xanchor === 'auto' && opts.x <= 1 / 3)
  29877. );
  29878. };
  29879. exports.isCenterAnchor = function isCenterAnchor(opts) {
  29880. return (
  29881. opts.xanchor === 'center' ||
  29882. (opts.xanchor === 'auto' && opts.x > 1 / 3 && opts.x < 2 / 3)
  29883. );
  29884. };
  29885. exports.isRightAnchor = function isRightAnchor(opts) {
  29886. return (
  29887. opts.xanchor === 'right' ||
  29888. (opts.xanchor === 'auto' && opts.x >= 2 / 3)
  29889. );
  29890. };
  29891. exports.isTopAnchor = function isTopAnchor(opts) {
  29892. return (
  29893. opts.yanchor === 'top' ||
  29894. (opts.yanchor === 'auto' && opts.y >= 2 / 3)
  29895. );
  29896. };
  29897. exports.isMiddleAnchor = function isMiddleAnchor(opts) {
  29898. return (
  29899. opts.yanchor === 'middle' ||
  29900. (opts.yanchor === 'auto' && opts.y > 1 / 3 && opts.y < 2 / 3)
  29901. );
  29902. };
  29903. exports.isBottomAnchor = function isBottomAnchor(opts) {
  29904. return (
  29905. opts.yanchor === 'bottom' ||
  29906. (opts.yanchor === 'auto' && opts.y <= 1 / 3)
  29907. );
  29908. };
  29909. },{}],154:[function(_dereq_,module,exports){
  29910. /**
  29911. * Copyright 2012-2019, Plotly, Inc.
  29912. * All rights reserved.
  29913. *
  29914. * This source code is licensed under the MIT license found in the
  29915. * LICENSE file in the root directory of this source tree.
  29916. */
  29917. 'use strict';
  29918. var modModule = _dereq_('./mod');
  29919. var mod = modModule.mod;
  29920. var modHalf = modModule.modHalf;
  29921. var PI = Math.PI;
  29922. var twoPI = 2 * PI;
  29923. function deg2rad(deg) { return deg / 180 * PI; }
  29924. function rad2deg(rad) { return rad / PI * 180; }
  29925. /**
  29926. * is sector a full circle?
  29927. * ... this comes up a lot in SVG path-drawing routines
  29928. *
  29929. * N.B. we consider all sectors that span more that 2pi 'full' circles
  29930. *
  29931. * @param {2-item array} aBnds : angular bounds in *radians*
  29932. * @return {boolean}
  29933. */
  29934. function isFullCircle(aBnds) {
  29935. return Math.abs(aBnds[1] - aBnds[0]) > twoPI - 1e-15;
  29936. }
  29937. /**
  29938. * angular delta between angle 'a' and 'b'
  29939. * solution taken from: https://stackoverflow.com/a/2007279
  29940. *
  29941. * @param {number} a : first angle in *radians*
  29942. * @param {number} b : second angle in *radians*
  29943. * @return {number} angular delta in *radians*
  29944. */
  29945. function angleDelta(a, b) {
  29946. return modHalf(b - a, twoPI);
  29947. }
  29948. /**
  29949. * angular distance between angle 'a' and 'b'
  29950. *
  29951. * @param {number} a : first angle in *radians*
  29952. * @param {number} b : second angle in *radians*
  29953. * @return {number} angular distance in *radians*
  29954. */
  29955. function angleDist(a, b) {
  29956. return Math.abs(angleDelta(a, b));
  29957. }
  29958. /**
  29959. * is angle inside sector?
  29960. *
  29961. * @param {number} a : angle to test in *radians*
  29962. * @param {2-item array} aBnds : sector's angular bounds in *radians*
  29963. * @param {boolean}
  29964. */
  29965. function isAngleInsideSector(a, aBnds) {
  29966. if(isFullCircle(aBnds)) return true;
  29967. var s0, s1;
  29968. if(aBnds[0] < aBnds[1]) {
  29969. s0 = aBnds[0];
  29970. s1 = aBnds[1];
  29971. } else {
  29972. s0 = aBnds[1];
  29973. s1 = aBnds[0];
  29974. }
  29975. s0 = mod(s0, twoPI);
  29976. s1 = mod(s1, twoPI);
  29977. if(s0 > s1) s1 += twoPI;
  29978. var a0 = mod(a, twoPI);
  29979. var a1 = a0 + twoPI;
  29980. return (a0 >= s0 && a0 <= s1) || (a1 >= s0 && a1 <= s1);
  29981. }
  29982. /**
  29983. * is pt (r,a) inside sector?
  29984. *
  29985. * @param {number} r : pt's radial coordinate
  29986. * @param {number} a : pt's angular coordinate in *radians*
  29987. * @param {2-item array} rBnds : sector's radial bounds
  29988. * @param {2-item array} aBnds : sector's angular bounds in *radians*
  29989. * @return {boolean}
  29990. */
  29991. function isPtInsideSector(r, a, rBnds, aBnds) {
  29992. if(!isAngleInsideSector(a, aBnds)) return false;
  29993. var r0, r1;
  29994. if(rBnds[0] < rBnds[1]) {
  29995. r0 = rBnds[0];
  29996. r1 = rBnds[1];
  29997. } else {
  29998. r0 = rBnds[1];
  29999. r1 = rBnds[0];
  30000. }
  30001. return r >= r0 && r <= r1;
  30002. }
  30003. // common to pathArc, pathSector and pathAnnulus
  30004. function _path(r0, r1, a0, a1, cx, cy, isClosed) {
  30005. cx = cx || 0;
  30006. cy = cy || 0;
  30007. var isCircle = isFullCircle([a0, a1]);
  30008. var aStart, aMid, aEnd;
  30009. var rStart, rEnd;
  30010. if(isCircle) {
  30011. aStart = 0;
  30012. aMid = PI;
  30013. aEnd = twoPI;
  30014. } else {
  30015. if(a0 < a1) {
  30016. aStart = a0;
  30017. aEnd = a1;
  30018. } else {
  30019. aStart = a1;
  30020. aEnd = a0;
  30021. }
  30022. }
  30023. if(r0 < r1) {
  30024. rStart = r0;
  30025. rEnd = r1;
  30026. } else {
  30027. rStart = r1;
  30028. rEnd = r0;
  30029. }
  30030. // N.B. svg coordinates here, where y increases downward
  30031. function pt(r, a) {
  30032. return [r * Math.cos(a) + cx, cy - r * Math.sin(a)];
  30033. }
  30034. var largeArc = Math.abs(aEnd - aStart) <= PI ? 0 : 1;
  30035. function arc(r, a, cw) {
  30036. return 'A' + [r, r] + ' ' + [0, largeArc, cw] + ' ' + pt(r, a);
  30037. }
  30038. var p;
  30039. if(isCircle) {
  30040. if(rStart === null) {
  30041. p = 'M' + pt(rEnd, aStart) +
  30042. arc(rEnd, aMid, 0) +
  30043. arc(rEnd, aEnd, 0) + 'Z';
  30044. } else {
  30045. p = 'M' + pt(rStart, aStart) +
  30046. arc(rStart, aMid, 0) +
  30047. arc(rStart, aEnd, 0) + 'Z' +
  30048. 'M' + pt(rEnd, aStart) +
  30049. arc(rEnd, aMid, 1) +
  30050. arc(rEnd, aEnd, 1) + 'Z';
  30051. }
  30052. } else {
  30053. if(rStart === null) {
  30054. p = 'M' + pt(rEnd, aStart) + arc(rEnd, aEnd, 0);
  30055. if(isClosed) p += 'L0,0Z';
  30056. } else {
  30057. p = 'M' + pt(rStart, aStart) +
  30058. 'L' + pt(rEnd, aStart) +
  30059. arc(rEnd, aEnd, 0) +
  30060. 'L' + pt(rStart, aEnd) +
  30061. arc(rStart, aStart, 1) + 'Z';
  30062. }
  30063. }
  30064. return p;
  30065. }
  30066. /**
  30067. * path an arc
  30068. *
  30069. * @param {number} r : radius
  30070. * @param {number} a0 : first angular coordinate in *radians*
  30071. * @param {number} a1 : second angular coordinate in *radians*
  30072. * @param {number (optional)} cx : x coordinate of center
  30073. * @param {number (optional)} cy : y coordinate of center
  30074. * @return {string} svg path
  30075. */
  30076. function pathArc(r, a0, a1, cx, cy) {
  30077. return _path(null, r, a0, a1, cx, cy, 0);
  30078. }
  30079. /**
  30080. * path a sector
  30081. *
  30082. * @param {number} r : radius
  30083. * @param {number} a0 : first angular coordinate in *radians*
  30084. * @param {number} a1 : second angular coordinate in *radians*
  30085. * @param {number (optional)} cx : x coordinate of center
  30086. * @param {number (optional)} cy : y coordinate of center
  30087. * @return {string} svg path
  30088. */
  30089. function pathSector(r, a0, a1, cx, cy) {
  30090. return _path(null, r, a0, a1, cx, cy, 1);
  30091. }
  30092. /**
  30093. * path an annulus
  30094. *
  30095. * @param {number} r0 : first radial coordinate
  30096. * @param {number} r1 : second radial coordinate
  30097. * @param {number} a0 : first angular coordinate in *radians*
  30098. * @param {number} a1 : second angular coordinate in *radians*
  30099. * @param {number (optional)} cx : x coordinate of center
  30100. * @param {number (optional)} cy : y coordinate of center
  30101. * @return {string} svg path
  30102. */
  30103. function pathAnnulus(r0, r1, a0, a1, cx, cy) {
  30104. return _path(r0, r1, a0, a1, cx, cy, 1);
  30105. }
  30106. module.exports = {
  30107. deg2rad: deg2rad,
  30108. rad2deg: rad2deg,
  30109. angleDelta: angleDelta,
  30110. angleDist: angleDist,
  30111. isFullCircle: isFullCircle,
  30112. isAngleInsideSector: isAngleInsideSector,
  30113. isPtInsideSector: isPtInsideSector,
  30114. pathArc: pathArc,
  30115. pathSector: pathSector,
  30116. pathAnnulus: pathAnnulus
  30117. };
  30118. },{"./mod":175}],155:[function(_dereq_,module,exports){
  30119. /**
  30120. * Copyright 2012-2019, Plotly, Inc.
  30121. * All rights reserved.
  30122. *
  30123. * This source code is licensed under the MIT license found in the
  30124. * LICENSE file in the root directory of this source tree.
  30125. */
  30126. 'use strict';
  30127. var isArray = Array.isArray;
  30128. // IE9 fallbacks
  30129. var ab = (typeof ArrayBuffer === 'undefined' || !ArrayBuffer.isView) ?
  30130. {isView: function() { return false; }} :
  30131. ArrayBuffer;
  30132. var dv = (typeof DataView === 'undefined') ?
  30133. function() {} :
  30134. DataView;
  30135. function isTypedArray(a) {
  30136. return ab.isView(a) && !(a instanceof dv);
  30137. }
  30138. exports.isTypedArray = isTypedArray;
  30139. function isArrayOrTypedArray(a) {
  30140. return isArray(a) || isTypedArray(a);
  30141. }
  30142. exports.isArrayOrTypedArray = isArrayOrTypedArray;
  30143. /*
  30144. * Test whether an input object is 1D.
  30145. *
  30146. * Assumes we already know the object is an array.
  30147. *
  30148. * Looks only at the first element, if the dimensionality is
  30149. * not consistent we won't figure that out here.
  30150. */
  30151. function isArray1D(a) {
  30152. return !isArrayOrTypedArray(a[0]);
  30153. }
  30154. exports.isArray1D = isArray1D;
  30155. /*
  30156. * Ensures an array has the right amount of storage space. If it doesn't
  30157. * exist, it creates an array. If it does exist, it returns it if too
  30158. * short or truncates it in-place.
  30159. *
  30160. * The goal is to just reuse memory to avoid a bit of excessive garbage
  30161. * collection.
  30162. */
  30163. exports.ensureArray = function(out, n) {
  30164. // TODO: typed array support here? This is only used in
  30165. // traces/carpet/compute_control_points
  30166. if(!isArray(out)) out = [];
  30167. // If too long, truncate. (If too short, it will grow
  30168. // automatically so we don't care about that case)
  30169. out.length = n;
  30170. return out;
  30171. };
  30172. /*
  30173. * TypedArray-compatible concatenation of n arrays
  30174. * if all arrays are the same type it will preserve that type,
  30175. * otherwise it falls back on Array.
  30176. * Also tries to avoid copying, in case one array has zero length
  30177. * But never mutates an existing array
  30178. */
  30179. exports.concat = function() {
  30180. var args = [];
  30181. var allArray = true;
  30182. var totalLen = 0;
  30183. var _constructor, arg0, i, argi, posi, leni, out, j;
  30184. for(i = 0; i < arguments.length; i++) {
  30185. argi = arguments[i];
  30186. leni = argi.length;
  30187. if(leni) {
  30188. if(arg0) args.push(argi);
  30189. else {
  30190. arg0 = argi;
  30191. posi = leni;
  30192. }
  30193. if(isArray(argi)) {
  30194. _constructor = false;
  30195. }
  30196. else {
  30197. allArray = false;
  30198. if(!totalLen) {
  30199. _constructor = argi.constructor;
  30200. }
  30201. else if(_constructor !== argi.constructor) {
  30202. // TODO: in principle we could upgrade here,
  30203. // ie keep typed array but convert all to Float64Array?
  30204. _constructor = false;
  30205. }
  30206. }
  30207. totalLen += leni;
  30208. }
  30209. }
  30210. if(!totalLen) return [];
  30211. if(!args.length) return arg0;
  30212. if(allArray) return arg0.concat.apply(arg0, args);
  30213. if(_constructor) {
  30214. // matching typed arrays
  30215. out = new _constructor(totalLen);
  30216. out.set(arg0);
  30217. for(i = 0; i < args.length; i++) {
  30218. argi = args[i];
  30219. out.set(argi, posi);
  30220. posi += argi.length;
  30221. }
  30222. return out;
  30223. }
  30224. // mismatched types or Array + typed
  30225. out = new Array(totalLen);
  30226. for(j = 0; j < arg0.length; j++) out[j] = arg0[j];
  30227. for(i = 0; i < args.length; i++) {
  30228. argi = args[i];
  30229. for(j = 0; j < argi.length; j++) out[posi + j] = argi[j];
  30230. posi += j;
  30231. }
  30232. return out;
  30233. };
  30234. exports.maxRowLength = function(z) {
  30235. return _rowLength(z, Math.max, 0);
  30236. };
  30237. exports.minRowLength = function(z) {
  30238. return _rowLength(z, Math.min, Infinity);
  30239. };
  30240. function _rowLength(z, fn, len0) {
  30241. if(isArrayOrTypedArray(z)) {
  30242. if(isArrayOrTypedArray(z[0])) {
  30243. var len = len0;
  30244. for(var i = 0; i < z.length; i++) {
  30245. len = fn(len, z[i].length);
  30246. }
  30247. return len;
  30248. } else {
  30249. return z.length;
  30250. }
  30251. }
  30252. return 0;
  30253. }
  30254. },{}],156:[function(_dereq_,module,exports){
  30255. /**
  30256. * Copyright 2012-2019, Plotly, Inc.
  30257. * All rights reserved.
  30258. *
  30259. * This source code is licensed under the MIT license found in the
  30260. * LICENSE file in the root directory of this source tree.
  30261. */
  30262. 'use strict';
  30263. var isNumeric = _dereq_('fast-isnumeric');
  30264. var BADNUM = _dereq_('../constants/numerical').BADNUM;
  30265. // precompile for speed
  30266. var JUNK = /^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g;
  30267. /**
  30268. * cleanNumber: remove common leading and trailing cruft
  30269. * Always returns either a number or BADNUM.
  30270. */
  30271. module.exports = function cleanNumber(v) {
  30272. if(typeof v === 'string') {
  30273. v = v.replace(JUNK, '');
  30274. }
  30275. if(isNumeric(v)) return Number(v);
  30276. return BADNUM;
  30277. };
  30278. },{"../constants/numerical":149,"fast-isnumeric":18}],157:[function(_dereq_,module,exports){
  30279. /**
  30280. * Copyright 2012-2019, Plotly, Inc.
  30281. * All rights reserved.
  30282. *
  30283. * This source code is licensed under the MIT license found in the
  30284. * LICENSE file in the root directory of this source tree.
  30285. */
  30286. 'use strict';
  30287. /**
  30288. * Clear gl frame (if any). This is a common pattern as
  30289. * we usually set `preserveDrawingBuffer: true` during
  30290. * gl context creation (e.g. via `reglUtils.prepare`).
  30291. *
  30292. * @param {DOM node or object} gd : graph div object
  30293. */
  30294. module.exports = function clearGlCanvases(gd) {
  30295. var fullLayout = gd._fullLayout;
  30296. if(fullLayout._glcanvas && fullLayout._glcanvas.size()) {
  30297. fullLayout._glcanvas.each(function(d) {
  30298. if(d.regl) d.regl.clear({color: true, depth: true});
  30299. });
  30300. }
  30301. };
  30302. },{}],158:[function(_dereq_,module,exports){
  30303. /**
  30304. * Copyright 2012-2019, Plotly, Inc.
  30305. * All rights reserved.
  30306. *
  30307. * This source code is licensed under the MIT license found in the
  30308. * LICENSE file in the root directory of this source tree.
  30309. */
  30310. 'use strict';
  30311. /**
  30312. * Clear responsive handlers (if any).
  30313. *
  30314. * @param {DOM node or object} gd : graph div object
  30315. */
  30316. module.exports = function clearResponsive(gd) {
  30317. if(gd._responsiveChartHandler) {
  30318. window.removeEventListener('resize', gd._responsiveChartHandler);
  30319. delete gd._responsiveChartHandler;
  30320. }
  30321. };
  30322. },{}],159:[function(_dereq_,module,exports){
  30323. /**
  30324. * Copyright 2012-2019, Plotly, Inc.
  30325. * All rights reserved.
  30326. *
  30327. * This source code is licensed under the MIT license found in the
  30328. * LICENSE file in the root directory of this source tree.
  30329. */
  30330. 'use strict';
  30331. var isNumeric = _dereq_('fast-isnumeric');
  30332. var tinycolor = _dereq_('tinycolor2');
  30333. var baseTraceAttrs = _dereq_('../plots/attributes');
  30334. var scales = _dereq_('../components/colorscale/scales');
  30335. var DESELECTDIM = _dereq_('../constants/interactions').DESELECTDIM;
  30336. var nestedProperty = _dereq_('./nested_property');
  30337. var counterRegex = _dereq_('./regex').counter;
  30338. var modHalf = _dereq_('./mod').modHalf;
  30339. var isArrayOrTypedArray = _dereq_('./array').isArrayOrTypedArray;
  30340. exports.valObjectMeta = {
  30341. data_array: {
  30342. // You can use *dflt=[] to force said array to exist though.
  30343. coerceFunction: function(v, propOut, dflt) {
  30344. // TODO maybe `v: {type: 'float32', vals: [/* ... */]}` also
  30345. if(isArrayOrTypedArray(v)) propOut.set(v);
  30346. else if(dflt !== undefined) propOut.set(dflt);
  30347. }
  30348. },
  30349. enumerated: {
  30350. coerceFunction: function(v, propOut, dflt, opts) {
  30351. if(opts.coerceNumber) v = +v;
  30352. if(opts.values.indexOf(v) === -1) propOut.set(dflt);
  30353. else propOut.set(v);
  30354. },
  30355. validateFunction: function(v, opts) {
  30356. if(opts.coerceNumber) v = +v;
  30357. var values = opts.values;
  30358. for(var i = 0; i < values.length; i++) {
  30359. var k = String(values[i]);
  30360. if((k.charAt(0) === '/' && k.charAt(k.length - 1) === '/')) {
  30361. var regex = new RegExp(k.substr(1, k.length - 2));
  30362. if(regex.test(v)) return true;
  30363. } else if(v === values[i]) return true;
  30364. }
  30365. return false;
  30366. }
  30367. },
  30368. 'boolean': {
  30369. coerceFunction: function(v, propOut, dflt) {
  30370. if(v === true || v === false) propOut.set(v);
  30371. else propOut.set(dflt);
  30372. }
  30373. },
  30374. number: {
  30375. coerceFunction: function(v, propOut, dflt, opts) {
  30376. if(!isNumeric(v) ||
  30377. (opts.min !== undefined && v < opts.min) ||
  30378. (opts.max !== undefined && v > opts.max)) {
  30379. propOut.set(dflt);
  30380. }
  30381. else propOut.set(+v);
  30382. }
  30383. },
  30384. integer: {
  30385. coerceFunction: function(v, propOut, dflt, opts) {
  30386. if(v % 1 || !isNumeric(v) ||
  30387. (opts.min !== undefined && v < opts.min) ||
  30388. (opts.max !== undefined && v > opts.max)) {
  30389. propOut.set(dflt);
  30390. }
  30391. else propOut.set(+v);
  30392. }
  30393. },
  30394. string: {
  30395. // TODO 'values shouldn't be in there (edge case: 'dash' in Scatter)
  30396. coerceFunction: function(v, propOut, dflt, opts) {
  30397. if(typeof v !== 'string') {
  30398. var okToCoerce = (typeof v === 'number');
  30399. if(opts.strict === true || !okToCoerce) propOut.set(dflt);
  30400. else propOut.set(String(v));
  30401. }
  30402. else if(opts.noBlank && !v) propOut.set(dflt);
  30403. else propOut.set(v);
  30404. }
  30405. },
  30406. color: {
  30407. coerceFunction: function(v, propOut, dflt) {
  30408. if(tinycolor(v).isValid()) propOut.set(v);
  30409. else propOut.set(dflt);
  30410. }
  30411. },
  30412. colorlist: {
  30413. coerceFunction: function(v, propOut, dflt) {
  30414. function isColor(color) {
  30415. return tinycolor(color).isValid();
  30416. }
  30417. if(!Array.isArray(v) || !v.length) propOut.set(dflt);
  30418. else if(v.every(isColor)) propOut.set(v);
  30419. else propOut.set(dflt);
  30420. }
  30421. },
  30422. colorscale: {
  30423. coerceFunction: function(v, propOut, dflt) {
  30424. propOut.set(scales.get(v, dflt));
  30425. }
  30426. },
  30427. angle: {
  30428. coerceFunction: function(v, propOut, dflt) {
  30429. if(v === 'auto') propOut.set('auto');
  30430. else if(!isNumeric(v)) propOut.set(dflt);
  30431. else propOut.set(modHalf(+v, 360));
  30432. }
  30433. },
  30434. subplotid: {
  30435. coerceFunction: function(v, propOut, dflt, opts) {
  30436. var regex = opts.regex || counterRegex(dflt);
  30437. if(typeof v === 'string' && regex.test(v)) {
  30438. propOut.set(v);
  30439. return;
  30440. }
  30441. propOut.set(dflt);
  30442. },
  30443. validateFunction: function(v, opts) {
  30444. var dflt = opts.dflt;
  30445. if(v === dflt) return true;
  30446. if(typeof v !== 'string') return false;
  30447. if(counterRegex(dflt).test(v)) return true;
  30448. return false;
  30449. }
  30450. },
  30451. flaglist: {
  30452. coerceFunction: function(v, propOut, dflt, opts) {
  30453. if(typeof v !== 'string') {
  30454. propOut.set(dflt);
  30455. return;
  30456. }
  30457. if((opts.extras || []).indexOf(v) !== -1) {
  30458. propOut.set(v);
  30459. return;
  30460. }
  30461. var vParts = v.split('+');
  30462. var i = 0;
  30463. while(i < vParts.length) {
  30464. var vi = vParts[i];
  30465. if(opts.flags.indexOf(vi) === -1 || vParts.indexOf(vi) < i) {
  30466. vParts.splice(i, 1);
  30467. }
  30468. else i++;
  30469. }
  30470. if(!vParts.length) propOut.set(dflt);
  30471. else propOut.set(vParts.join('+'));
  30472. }
  30473. },
  30474. any: {
  30475. coerceFunction: function(v, propOut, dflt) {
  30476. if(v === undefined) propOut.set(dflt);
  30477. else propOut.set(v);
  30478. }
  30479. },
  30480. info_array: {
  30481. // set `dimensions=2` for a 2D array or '1-2' for either
  30482. // `items` may be a single object instead of an array, in which case
  30483. // `freeLength` must be true.
  30484. // if `dimensions='1-2'` and items is a 1D array, then the value can
  30485. // either be a matching 1D array or an array of such matching 1D arrays
  30486. coerceFunction: function(v, propOut, dflt, opts) {
  30487. // simplified coerce function just for array items
  30488. function coercePart(v, opts, dflt) {
  30489. var out;
  30490. var propPart = {set: function(v) { out = v; }};
  30491. if(dflt === undefined) dflt = opts.dflt;
  30492. exports.valObjectMeta[opts.valType].coerceFunction(v, propPart, dflt, opts);
  30493. return out;
  30494. }
  30495. var twoD = opts.dimensions === 2 || (opts.dimensions === '1-2' && Array.isArray(v) && Array.isArray(v[0]));
  30496. if(!Array.isArray(v)) {
  30497. propOut.set(dflt);
  30498. return;
  30499. }
  30500. var items = opts.items;
  30501. var vOut = [];
  30502. var arrayItems = Array.isArray(items);
  30503. var arrayItems2D = arrayItems && twoD && Array.isArray(items[0]);
  30504. var innerItemsOnly = twoD && arrayItems && !arrayItems2D;
  30505. var len = (arrayItems && !innerItemsOnly) ? items.length : v.length;
  30506. var i, j, row, item, len2, vNew;
  30507. dflt = Array.isArray(dflt) ? dflt : [];
  30508. if(twoD) {
  30509. for(i = 0; i < len; i++) {
  30510. vOut[i] = [];
  30511. row = Array.isArray(v[i]) ? v[i] : [];
  30512. if(innerItemsOnly) len2 = items.length;
  30513. else if(arrayItems) len2 = items[i].length;
  30514. else len2 = row.length;
  30515. for(j = 0; j < len2; j++) {
  30516. if(innerItemsOnly) item = items[j];
  30517. else if(arrayItems) item = items[i][j];
  30518. else item = items;
  30519. vNew = coercePart(row[j], item, (dflt[i] || [])[j]);
  30520. if(vNew !== undefined) vOut[i][j] = vNew;
  30521. }
  30522. }
  30523. }
  30524. else {
  30525. for(i = 0; i < len; i++) {
  30526. vNew = coercePart(v[i], arrayItems ? items[i] : items, dflt[i]);
  30527. if(vNew !== undefined) vOut[i] = vNew;
  30528. }
  30529. }
  30530. propOut.set(vOut);
  30531. },
  30532. validateFunction: function(v, opts) {
  30533. if(!Array.isArray(v)) return false;
  30534. var items = opts.items;
  30535. var arrayItems = Array.isArray(items);
  30536. var twoD = opts.dimensions === 2;
  30537. // when free length is off, input and declared lengths must match
  30538. if(!opts.freeLength && v.length !== items.length) return false;
  30539. // valid when all input items are valid
  30540. for(var i = 0; i < v.length; i++) {
  30541. if(twoD) {
  30542. if(!Array.isArray(v[i]) || (!opts.freeLength && v[i].length !== items[i].length)) {
  30543. return false;
  30544. }
  30545. for(var j = 0; j < v[i].length; j++) {
  30546. if(!validate(v[i][j], arrayItems ? items[i][j] : items)) {
  30547. return false;
  30548. }
  30549. }
  30550. }
  30551. else if(!validate(v[i], arrayItems ? items[i] : items)) return false;
  30552. }
  30553. return true;
  30554. }
  30555. }
  30556. };
  30557. /**
  30558. * Ensures that container[attribute] has a valid value.
  30559. *
  30560. * attributes[attribute] is an object with possible keys:
  30561. * - valType: data_array, enumerated, boolean, ... as in valObjectMeta
  30562. * - values: (enumerated only) array of allowed vals
  30563. * - min, max: (number, integer only) inclusive bounds on allowed vals
  30564. * either or both may be omitted
  30565. * - dflt: if attribute is invalid or missing, use this default
  30566. * if dflt is provided as an argument to lib.coerce it takes precedence
  30567. * as a convenience, returns the value it finally set
  30568. */
  30569. exports.coerce = function(containerIn, containerOut, attributes, attribute, dflt) {
  30570. var opts = nestedProperty(attributes, attribute).get();
  30571. var propIn = nestedProperty(containerIn, attribute);
  30572. var propOut = nestedProperty(containerOut, attribute);
  30573. var v = propIn.get();
  30574. var template = containerOut._template;
  30575. if(v === undefined && template) {
  30576. v = nestedProperty(template, attribute).get();
  30577. // already used the template value, so short-circuit the second check
  30578. template = 0;
  30579. }
  30580. if(dflt === undefined) dflt = opts.dflt;
  30581. /**
  30582. * arrayOk: value MAY be an array, then we do no value checking
  30583. * at this point, because it can be more complicated than the
  30584. * individual form (eg. some array vals can be numbers, even if the
  30585. * single values must be color strings)
  30586. */
  30587. if(opts.arrayOk && isArrayOrTypedArray(v)) {
  30588. propOut.set(v);
  30589. return v;
  30590. }
  30591. var coerceFunction = exports.valObjectMeta[opts.valType].coerceFunction;
  30592. coerceFunction(v, propOut, dflt, opts);
  30593. var out = propOut.get();
  30594. // in case v was provided but invalid, try the template again so it still
  30595. // overrides the regular default
  30596. if(template && out === dflt && !validate(v, opts)) {
  30597. v = nestedProperty(template, attribute).get();
  30598. coerceFunction(v, propOut, dflt, opts);
  30599. out = propOut.get();
  30600. }
  30601. return out;
  30602. };
  30603. /**
  30604. * Variation on coerce
  30605. *
  30606. * Uses coerce to get attribute value if user input is valid,
  30607. * returns attribute default if user input it not valid or
  30608. * returns false if there is no user input.
  30609. */
  30610. exports.coerce2 = function(containerIn, containerOut, attributes, attribute, dflt) {
  30611. var propIn = nestedProperty(containerIn, attribute);
  30612. var propOut = exports.coerce(containerIn, containerOut, attributes, attribute, dflt);
  30613. var valIn = propIn.get();
  30614. return (valIn !== undefined && valIn !== null) ? propOut : false;
  30615. };
  30616. /*
  30617. * Shortcut to coerce the three font attributes
  30618. *
  30619. * 'coerce' is a lib.coerce wrapper with implied first three arguments
  30620. */
  30621. exports.coerceFont = function(coerce, attr, dfltObj) {
  30622. var out = {};
  30623. dfltObj = dfltObj || {};
  30624. out.family = coerce(attr + '.family', dfltObj.family);
  30625. out.size = coerce(attr + '.size', dfltObj.size);
  30626. out.color = coerce(attr + '.color', dfltObj.color);
  30627. return out;
  30628. };
  30629. /** Coerce shortcut for 'hoverinfo'
  30630. * handling 1-vs-multi-trace dflt logic
  30631. *
  30632. * @param {object} traceIn : user trace object
  30633. * @param {object} traceOut : full trace object (requires _module ref)
  30634. * @param {object} layoutOut : full layout object (require _dataLength ref)
  30635. * @return {any} : the coerced value
  30636. */
  30637. exports.coerceHoverinfo = function(traceIn, traceOut, layoutOut) {
  30638. var moduleAttrs = traceOut._module.attributes;
  30639. var attrs = moduleAttrs.hoverinfo ? moduleAttrs : baseTraceAttrs;
  30640. var valObj = attrs.hoverinfo;
  30641. var dflt;
  30642. if(layoutOut._dataLength === 1) {
  30643. var flags = valObj.dflt === 'all' ?
  30644. valObj.flags.slice() :
  30645. valObj.dflt.split('+');
  30646. flags.splice(flags.indexOf('name'), 1);
  30647. dflt = flags.join('+');
  30648. }
  30649. return exports.coerce(traceIn, traceOut, attrs, 'hoverinfo', dflt);
  30650. };
  30651. /** Coerce shortcut for [un]selected.marker.opacity,
  30652. * which has special default logic, to ensure that it corresponds to the
  30653. * default selection behavior while allowing to be overtaken by any other
  30654. * [un]selected attribute.
  30655. *
  30656. * N.B. This must be called *after* coercing all the other [un]selected attrs,
  30657. * to give the intended result.
  30658. *
  30659. * @param {object} traceOut : fullData item
  30660. * @param {function} coerce : lib.coerce wrapper with implied first three arguments
  30661. */
  30662. exports.coerceSelectionMarkerOpacity = function(traceOut, coerce) {
  30663. if(!traceOut.marker) return;
  30664. var mo = traceOut.marker.opacity;
  30665. // you can still have a `marker` container with no markers if there's text
  30666. if(mo === undefined) return;
  30667. var smoDflt;
  30668. var usmoDflt;
  30669. // Don't give [un]selected.marker.opacity a default value if
  30670. // marker.opacity is an array: handle this during style step.
  30671. //
  30672. // Only give [un]selected.marker.opacity a default value if you don't
  30673. // set any other [un]selected attributes.
  30674. if(!isArrayOrTypedArray(mo) && !traceOut.selected && !traceOut.unselected) {
  30675. smoDflt = mo;
  30676. usmoDflt = DESELECTDIM * mo;
  30677. }
  30678. coerce('selected.marker.opacity', smoDflt);
  30679. coerce('unselected.marker.opacity', usmoDflt);
  30680. };
  30681. function validate(value, opts) {
  30682. var valObjectDef = exports.valObjectMeta[opts.valType];
  30683. if(opts.arrayOk && isArrayOrTypedArray(value)) return true;
  30684. if(valObjectDef.validateFunction) {
  30685. return valObjectDef.validateFunction(value, opts);
  30686. }
  30687. var failed = {};
  30688. var out = failed;
  30689. var propMock = { set: function(v) { out = v; } };
  30690. // 'failed' just something mutable that won't be === anything else
  30691. valObjectDef.coerceFunction(value, propMock, failed, opts);
  30692. return out !== failed;
  30693. }
  30694. exports.validate = validate;
  30695. },{"../components/colorscale/scales":66,"../constants/interactions":148,"../plots/attributes":209,"./array":155,"./mod":175,"./nested_property":176,"./regex":183,"fast-isnumeric":18,"tinycolor2":34}],160:[function(_dereq_,module,exports){
  30696. /**
  30697. * Copyright 2012-2019, Plotly, Inc.
  30698. * All rights reserved.
  30699. *
  30700. * This source code is licensed under the MIT license found in the
  30701. * LICENSE file in the root directory of this source tree.
  30702. */
  30703. 'use strict';
  30704. var d3 = _dereq_('d3');
  30705. var isNumeric = _dereq_('fast-isnumeric');
  30706. var Loggers = _dereq_('./loggers');
  30707. var mod = _dereq_('./mod').mod;
  30708. var constants = _dereq_('../constants/numerical');
  30709. var BADNUM = constants.BADNUM;
  30710. var ONEDAY = constants.ONEDAY;
  30711. var ONEHOUR = constants.ONEHOUR;
  30712. var ONEMIN = constants.ONEMIN;
  30713. var ONESEC = constants.ONESEC;
  30714. var EPOCHJD = constants.EPOCHJD;
  30715. var Registry = _dereq_('../registry');
  30716. var utcFormat = d3.time.format.utc;
  30717. var DATETIME_REGEXP = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\d)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d:?\d\d)?)?)?)?)?\s*$/m;
  30718. // special regex for chinese calendars to support yyyy-mmi-dd etc for intercalary months
  30719. var DATETIME_REGEXP_CN = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\di?)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d:?\d\d)?)?)?)?)?\s*$/m;
  30720. // for 2-digit years, the first year we map them onto
  30721. var YFIRST = new Date().getFullYear() - 70;
  30722. function isWorldCalendar(calendar) {
  30723. return (
  30724. calendar &&
  30725. Registry.componentsRegistry.calendars &&
  30726. typeof calendar === 'string' && calendar !== 'gregorian'
  30727. );
  30728. }
  30729. /*
  30730. * dateTick0: get the canonical tick for this calendar
  30731. *
  30732. * bool sunday is for week ticks, shift it to a Sunday.
  30733. */
  30734. exports.dateTick0 = function(calendar, sunday) {
  30735. if(isWorldCalendar(calendar)) {
  30736. return sunday ?
  30737. Registry.getComponentMethod('calendars', 'CANONICAL_SUNDAY')[calendar] :
  30738. Registry.getComponentMethod('calendars', 'CANONICAL_TICK')[calendar];
  30739. }
  30740. else {
  30741. return sunday ? '2000-01-02' : '2000-01-01';
  30742. }
  30743. };
  30744. /*
  30745. * dfltRange: for each calendar, give a valid default range
  30746. */
  30747. exports.dfltRange = function(calendar) {
  30748. if(isWorldCalendar(calendar)) {
  30749. return Registry.getComponentMethod('calendars', 'DFLTRANGE')[calendar];
  30750. }
  30751. else {
  30752. return ['2000-01-01', '2001-01-01'];
  30753. }
  30754. };
  30755. // is an object a javascript date?
  30756. exports.isJSDate = function(v) {
  30757. return typeof v === 'object' && v !== null && typeof v.getTime === 'function';
  30758. };
  30759. // The absolute limits of our date-time system
  30760. // This is a little weird: we use MIN_MS and MAX_MS in dateTime2ms
  30761. // but we use dateTime2ms to calculate them (after defining it!)
  30762. var MIN_MS, MAX_MS;
  30763. /**
  30764. * dateTime2ms - turn a date object or string s into milliseconds
  30765. * (relative to 1970-01-01, per javascript standard)
  30766. * optional calendar (string) to use a non-gregorian calendar
  30767. *
  30768. * Returns BADNUM if it doesn't find a date
  30769. *
  30770. * strings should have the form:
  30771. *
  30772. * -?YYYY-mm-dd<sep>HH:MM:SS.sss<tzInfo>?
  30773. *
  30774. * <sep>: space (our normal standard) or T or t (ISO-8601)
  30775. * <tzInfo>: Z, z, or [+\-]HH:?MM and we THROW IT AWAY
  30776. * this format comes from https://tools.ietf.org/html/rfc3339#section-5.6
  30777. * but we allow it even with a space as the separator
  30778. *
  30779. * May truncate after any full field, and sss can be any length
  30780. * even >3 digits, though javascript dates truncate to milliseconds,
  30781. * we keep as much as javascript numeric precision can hold, but we only
  30782. * report back up to 100 microsecond precision, because most dates support
  30783. * this precision (close to 1970 support more, very far away support less)
  30784. *
  30785. * Expanded to support negative years to -9999 but you must always
  30786. * give 4 digits, except for 2-digit positive years which we assume are
  30787. * near the present time.
  30788. * Note that we follow ISO 8601:2004: there *is* a year 0, which
  30789. * is 1BC/BCE, and -1===2BC etc.
  30790. *
  30791. * World calendars: not all of these *have* agreed extensions to this full range,
  30792. * if you have another calendar system but want a date range outside its validity,
  30793. * you can use a gregorian date string prefixed with 'G' or 'g'.
  30794. *
  30795. * Where to cut off 2-digit years between 1900s and 2000s?
  30796. * from http://support.microsoft.com/kb/244664:
  30797. * 1930-2029 (the most retro of all...)
  30798. * but in my mac chrome from eg. d=new Date(Date.parse('8/19/50')):
  30799. * 1950-2049
  30800. * by Java, from http://stackoverflow.com/questions/2024273/:
  30801. * now-80 - now+19
  30802. * or FileMaker Pro, from
  30803. * http://www.filemaker.com/12help/html/add_view_data.4.21.html:
  30804. * now-70 - now+29
  30805. * but python strptime etc, via
  30806. * http://docs.python.org/py3k/library/time.html:
  30807. * 1969-2068 (super forward-looking, but static, not sliding!)
  30808. *
  30809. * lets go with now-70 to now+29, and if anyone runs into this problem
  30810. * they can learn the hard way not to use 2-digit years, as no choice we
  30811. * make now will cover all possibilities. mostly this will all be taken
  30812. * care of in initial parsing, should only be an issue for hand-entered data
  30813. * currently (2016) this range is:
  30814. * 1946-2045
  30815. */
  30816. exports.dateTime2ms = function(s, calendar) {
  30817. // first check if s is a date object
  30818. if(exports.isJSDate(s)) {
  30819. // Convert to the UTC milliseconds that give the same
  30820. // hours as this date has in the local timezone
  30821. var tzOffset = s.getTimezoneOffset() * ONEMIN;
  30822. var offsetTweak = (s.getUTCMinutes() - s.getMinutes()) * ONEMIN +
  30823. (s.getUTCSeconds() - s.getSeconds()) * ONESEC +
  30824. (s.getUTCMilliseconds() - s.getMilliseconds());
  30825. if(offsetTweak) {
  30826. var comb = 3 * ONEMIN;
  30827. tzOffset = tzOffset - comb / 2 + mod(offsetTweak - tzOffset + comb / 2, comb);
  30828. }
  30829. s = Number(s) - tzOffset;
  30830. if(s >= MIN_MS && s <= MAX_MS) return s;
  30831. return BADNUM;
  30832. }
  30833. // otherwise only accept strings and numbers
  30834. if(typeof s !== 'string' && typeof s !== 'number') return BADNUM;
  30835. s = String(s);
  30836. var isWorld = isWorldCalendar(calendar);
  30837. // to handle out-of-range dates in international calendars, accept
  30838. // 'G' as a prefix to force the built-in gregorian calendar.
  30839. var s0 = s.charAt(0);
  30840. if(isWorld && (s0 === 'G' || s0 === 'g')) {
  30841. s = s.substr(1);
  30842. calendar = '';
  30843. }
  30844. var isChinese = isWorld && calendar.substr(0, 7) === 'chinese';
  30845. var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP);
  30846. if(!match) return BADNUM;
  30847. var y = match[1];
  30848. var m = match[3] || '1';
  30849. var d = Number(match[5] || 1);
  30850. var H = Number(match[7] || 0);
  30851. var M = Number(match[9] || 0);
  30852. var S = Number(match[11] || 0);
  30853. if(isWorld) {
  30854. // disallow 2-digit years for world calendars
  30855. if(y.length === 2) return BADNUM;
  30856. y = Number(y);
  30857. var cDate;
  30858. try {
  30859. var calInstance = Registry.getComponentMethod('calendars', 'getCal')(calendar);
  30860. if(isChinese) {
  30861. var isIntercalary = m.charAt(m.length - 1) === 'i';
  30862. m = parseInt(m, 10);
  30863. cDate = calInstance.newDate(y, calInstance.toMonthIndex(y, m, isIntercalary), d);
  30864. }
  30865. else {
  30866. cDate = calInstance.newDate(y, Number(m), d);
  30867. }
  30868. }
  30869. catch(e) { return BADNUM; } // Invalid ... date
  30870. if(!cDate) return BADNUM;
  30871. return ((cDate.toJD() - EPOCHJD) * ONEDAY) +
  30872. (H * ONEHOUR) + (M * ONEMIN) + (S * ONESEC);
  30873. }
  30874. if(y.length === 2) {
  30875. y = (Number(y) + 2000 - YFIRST) % 100 + YFIRST;
  30876. }
  30877. else y = Number(y);
  30878. // new Date uses months from 0; subtract 1 here just so we
  30879. // don't have to do it again during the validity test below
  30880. m -= 1;
  30881. // javascript takes new Date(0..99,m,d) to mean 1900-1999, so
  30882. // to support years 0-99 we need to use setFullYear explicitly
  30883. // Note that 2000 is a leap year.
  30884. var date = new Date(Date.UTC(2000, m, d, H, M));
  30885. date.setUTCFullYear(y);
  30886. if(date.getUTCMonth() !== m) return BADNUM;
  30887. if(date.getUTCDate() !== d) return BADNUM;
  30888. return date.getTime() + S * ONESEC;
  30889. };
  30890. MIN_MS = exports.MIN_MS = exports.dateTime2ms('-9999');
  30891. MAX_MS = exports.MAX_MS = exports.dateTime2ms('9999-12-31 23:59:59.9999');
  30892. // is string s a date? (see above)
  30893. exports.isDateTime = function(s, calendar) {
  30894. return (exports.dateTime2ms(s, calendar) !== BADNUM);
  30895. };
  30896. // pad a number with zeroes, to given # of digits before the decimal point
  30897. function lpad(val, digits) {
  30898. return String(val + Math.pow(10, digits)).substr(1);
  30899. }
  30900. /**
  30901. * Turn ms into string of the form YYYY-mm-dd HH:MM:SS.ssss
  30902. * Crop any trailing zeros in time, except never stop right after hours
  30903. * (we could choose to crop '-01' from date too but for now we always
  30904. * show the whole date)
  30905. * Optional range r is the data range that applies, also in ms.
  30906. * If rng is big, the later parts of time will be omitted
  30907. */
  30908. var NINETYDAYS = 90 * ONEDAY;
  30909. var THREEHOURS = 3 * ONEHOUR;
  30910. var FIVEMIN = 5 * ONEMIN;
  30911. exports.ms2DateTime = function(ms, r, calendar) {
  30912. if(typeof ms !== 'number' || !(ms >= MIN_MS && ms <= MAX_MS)) return BADNUM;
  30913. if(!r) r = 0;
  30914. var msecTenths = Math.floor(mod(ms + 0.05, 1) * 10);
  30915. var msRounded = Math.round(ms - msecTenths / 10);
  30916. var dateStr, h, m, s, msec10, d;
  30917. if(isWorldCalendar(calendar)) {
  30918. var dateJD = Math.floor(msRounded / ONEDAY) + EPOCHJD;
  30919. var timeMs = Math.floor(mod(ms, ONEDAY));
  30920. try {
  30921. dateStr = Registry.getComponentMethod('calendars', 'getCal')(calendar)
  30922. .fromJD(dateJD).formatDate('yyyy-mm-dd');
  30923. } catch(e) {
  30924. // invalid date in this calendar - fall back to Gyyyy-mm-dd
  30925. dateStr = utcFormat('G%Y-%m-%d')(new Date(msRounded));
  30926. }
  30927. // yyyy does NOT guarantee 4-digit years. YYYY mostly does, but does
  30928. // other things for a few calendars, so we can't trust it. Just pad
  30929. // it manually (after the '-' if there is one)
  30930. if(dateStr.charAt(0) === '-') {
  30931. while(dateStr.length < 11) dateStr = '-0' + dateStr.substr(1);
  30932. } else {
  30933. while(dateStr.length < 10) dateStr = '0' + dateStr;
  30934. }
  30935. // TODO: if this is faster, we could use this block for extracting
  30936. // the time components of regular gregorian too
  30937. h = (r < NINETYDAYS) ? Math.floor(timeMs / ONEHOUR) : 0;
  30938. m = (r < NINETYDAYS) ? Math.floor((timeMs % ONEHOUR) / ONEMIN) : 0;
  30939. s = (r < THREEHOURS) ? Math.floor((timeMs % ONEMIN) / ONESEC) : 0;
  30940. msec10 = (r < FIVEMIN) ? (timeMs % ONESEC) * 10 + msecTenths : 0;
  30941. }
  30942. else {
  30943. d = new Date(msRounded);
  30944. dateStr = utcFormat('%Y-%m-%d')(d);
  30945. // <90 days: add hours and minutes - never *only* add hours
  30946. h = (r < NINETYDAYS) ? d.getUTCHours() : 0;
  30947. m = (r < NINETYDAYS) ? d.getUTCMinutes() : 0;
  30948. // <3 hours: add seconds
  30949. s = (r < THREEHOURS) ? d.getUTCSeconds() : 0;
  30950. // <5 minutes: add ms (plus one extra digit, this is msec*10)
  30951. msec10 = (r < FIVEMIN) ? d.getUTCMilliseconds() * 10 + msecTenths : 0;
  30952. }
  30953. return includeTime(dateStr, h, m, s, msec10);
  30954. };
  30955. // For converting old-style milliseconds to date strings,
  30956. // we use the local timezone rather than UTC like we use
  30957. // everywhere else, both for backward compatibility and
  30958. // because that's how people mostly use javasript date objects.
  30959. // Clip one extra day off our date range though so we can't get
  30960. // thrown beyond the range by the timezone shift.
  30961. exports.ms2DateTimeLocal = function(ms) {
  30962. if(!(ms >= MIN_MS + ONEDAY && ms <= MAX_MS - ONEDAY)) return BADNUM;
  30963. var msecTenths = Math.floor(mod(ms + 0.05, 1) * 10);
  30964. var d = new Date(Math.round(ms - msecTenths / 10));
  30965. var dateStr = d3.time.format('%Y-%m-%d')(d);
  30966. var h = d.getHours();
  30967. var m = d.getMinutes();
  30968. var s = d.getSeconds();
  30969. var msec10 = d.getUTCMilliseconds() * 10 + msecTenths;
  30970. return includeTime(dateStr, h, m, s, msec10);
  30971. };
  30972. function includeTime(dateStr, h, m, s, msec10) {
  30973. // include each part that has nonzero data in or after it
  30974. if(h || m || s || msec10) {
  30975. dateStr += ' ' + lpad(h, 2) + ':' + lpad(m, 2);
  30976. if(s || msec10) {
  30977. dateStr += ':' + lpad(s, 2);
  30978. if(msec10) {
  30979. var digits = 4;
  30980. while(msec10 % 10 === 0) {
  30981. digits -= 1;
  30982. msec10 /= 10;
  30983. }
  30984. dateStr += '.' + lpad(msec10, digits);
  30985. }
  30986. }
  30987. }
  30988. return dateStr;
  30989. }
  30990. // normalize date format to date string, in case it starts as
  30991. // a Date object or milliseconds
  30992. // optional dflt is the return value if cleaning fails
  30993. exports.cleanDate = function(v, dflt, calendar) {
  30994. // let us use cleanDate to provide a missing default without an error
  30995. if(v === BADNUM) return dflt;
  30996. if(exports.isJSDate(v) || (typeof v === 'number' && isFinite(v))) {
  30997. // do not allow milliseconds (old) or jsdate objects (inherently
  30998. // described as gregorian dates) with world calendars
  30999. if(isWorldCalendar(calendar)) {
  31000. Loggers.error('JS Dates and milliseconds are incompatible with world calendars', v);
  31001. return dflt;
  31002. }
  31003. // NOTE: if someone puts in a year as a number rather than a string,
  31004. // this will mistakenly convert it thinking it's milliseconds from 1970
  31005. // that is: '2012' -> Jan. 1, 2012, but 2012 -> 2012 epoch milliseconds
  31006. v = exports.ms2DateTimeLocal(+v);
  31007. if(!v && dflt !== undefined) return dflt;
  31008. }
  31009. else if(!exports.isDateTime(v, calendar)) {
  31010. Loggers.error('unrecognized date', v);
  31011. return dflt;
  31012. }
  31013. return v;
  31014. };
  31015. /*
  31016. * Date formatting for ticks and hovertext
  31017. */
  31018. /*
  31019. * modDateFormat: Support world calendars, and add one item to
  31020. * d3's vocabulary:
  31021. * %{n}f where n is the max number of digits of fractional seconds
  31022. */
  31023. var fracMatch = /%\d?f/g;
  31024. function modDateFormat(fmt, x, formatter, calendar) {
  31025. fmt = fmt.replace(fracMatch, function(match) {
  31026. var digits = Math.min(+(match.charAt(1)) || 6, 6);
  31027. var fracSecs = ((x / 1000 % 1) + 2)
  31028. .toFixed(digits)
  31029. .substr(2).replace(/0+$/, '') || '0';
  31030. return fracSecs;
  31031. });
  31032. var d = new Date(Math.floor(x + 0.05));
  31033. if(isWorldCalendar(calendar)) {
  31034. try {
  31035. fmt = Registry.getComponentMethod('calendars', 'worldCalFmt')(fmt, x, calendar);
  31036. }
  31037. catch(e) {
  31038. return 'Invalid';
  31039. }
  31040. }
  31041. return formatter(fmt)(d);
  31042. }
  31043. /*
  31044. * formatTime: create a time string from:
  31045. * x: milliseconds
  31046. * tr: tickround ('M', 'S', or # digits)
  31047. * only supports UTC times (where every day is 24 hours and 0 is at midnight)
  31048. */
  31049. var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999];
  31050. function formatTime(x, tr) {
  31051. var timePart = mod(x + 0.05, ONEDAY);
  31052. var timeStr = lpad(Math.floor(timePart / ONEHOUR), 2) + ':' +
  31053. lpad(mod(Math.floor(timePart / ONEMIN), 60), 2);
  31054. if(tr !== 'M') {
  31055. if(!isNumeric(tr)) tr = 0; // should only be 'S'
  31056. /*
  31057. * this is a weird one - and shouldn't come up unless people
  31058. * monkey with tick0 in weird ways, but we need to do something!
  31059. * IN PARTICULAR we had better not display garbage (see below)
  31060. * for numbers we always round to the nearest increment of the
  31061. * precision we're showing, and this seems like the right way to
  31062. * handle seconds and milliseconds, as they have a decimal point
  31063. * and people will interpret that to mean rounding like numbers.
  31064. * but for larger increments we floor the value: it's always
  31065. * 2013 until the ball drops on the new year. We could argue about
  31066. * which field it is where we start rounding (should 12:08:59
  31067. * round to 12:09 if we're stopping at minutes?) but for now I'll
  31068. * say we round seconds but floor everything else. BUT that means
  31069. * we need to never round up to 60 seconds, ie 23:59:60
  31070. */
  31071. var sec = Math.min(mod(x / ONESEC, 60), MAXSECONDS[tr]);
  31072. var secStr = (100 + sec).toFixed(tr).substr(1);
  31073. if(tr > 0) {
  31074. secStr = secStr.replace(/0+$/, '').replace(/[\.]$/, '');
  31075. }
  31076. timeStr += ':' + secStr;
  31077. }
  31078. return timeStr;
  31079. }
  31080. /*
  31081. * formatDate: turn a date into tick or hover label text.
  31082. *
  31083. * x: milliseconds, the value to convert
  31084. * fmt: optional, an explicit format string (d3 format, even for world calendars)
  31085. * tr: tickround ('y', 'm', 'd', 'M', 'S', or # digits)
  31086. * used if no explicit fmt is provided
  31087. * formatter: locale-aware d3 date formatter for standard gregorian calendars
  31088. * should be the result of exports.getD3DateFormat(gd)
  31089. * calendar: optional string, the world calendar system to use
  31090. *
  31091. * returns the date/time as a string, potentially with the leading portion
  31092. * on a separate line (after '\n')
  31093. * Note that this means if you provide an explicit format which includes '\n'
  31094. * the axis may choose to strip things after it when they don't change from
  31095. * one tick to the next (as it does with automatic formatting)
  31096. */
  31097. exports.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) {
  31098. calendar = isWorldCalendar(calendar) && calendar;
  31099. if(!fmt) {
  31100. if(tr === 'y') fmt = extraFormat.year;
  31101. else if(tr === 'm') fmt = extraFormat.month;
  31102. else if(tr === 'd') {
  31103. fmt = extraFormat.dayMonth + '\n' + extraFormat.year;
  31104. }
  31105. else {
  31106. return formatTime(x, tr) + '\n' + modDateFormat(extraFormat.dayMonthYear, x, formatter, calendar);
  31107. }
  31108. }
  31109. return modDateFormat(fmt, x, formatter, calendar);
  31110. };
  31111. /*
  31112. * incrementMonth: make a new milliseconds value from the given one,
  31113. * having changed the month
  31114. *
  31115. * special case for world calendars: multiples of 12 are treated as years,
  31116. * even for calendar systems that don't have (always or ever) 12 months/year
  31117. * TODO: perhaps we need a different code for year increments to support this?
  31118. *
  31119. * ms (number): the initial millisecond value
  31120. * dMonth (int): the (signed) number of months to shift
  31121. * calendar (string): the calendar system to use
  31122. *
  31123. * changing month does not (and CANNOT) always preserve day, since
  31124. * months have different lengths. The worst example of this is:
  31125. * d = new Date(1970,0,31); d.setMonth(1) -> Feb 31 turns into Mar 3
  31126. *
  31127. * But we want to be able to iterate over the last day of each month,
  31128. * regardless of what its number is.
  31129. * So shift 3 days forward, THEN set the new month, then unshift:
  31130. * 1/31 -> 2/28 (or 29) -> 3/31 -> 4/30 -> ...
  31131. *
  31132. * Note that odd behavior still exists if you start from the 26th-28th:
  31133. * 1/28 -> 2/28 -> 3/31
  31134. * but at least you can't shift any dates into the wrong month,
  31135. * and ticks on these days incrementing by month would be very unusual
  31136. */
  31137. var THREEDAYS = 3 * ONEDAY;
  31138. exports.incrementMonth = function(ms, dMonth, calendar) {
  31139. calendar = isWorldCalendar(calendar) && calendar;
  31140. // pull time out and operate on pure dates, then add time back at the end
  31141. // this gives maximum precision - not that we *normally* care if we're
  31142. // incrementing by month, but better to be safe!
  31143. var timeMs = mod(ms, ONEDAY);
  31144. ms = Math.round(ms - timeMs);
  31145. if(calendar) {
  31146. try {
  31147. var dateJD = Math.round(ms / ONEDAY) + EPOCHJD;
  31148. var calInstance = Registry.getComponentMethod('calendars', 'getCal')(calendar);
  31149. var cDate = calInstance.fromJD(dateJD);
  31150. if(dMonth % 12) calInstance.add(cDate, dMonth, 'm');
  31151. else calInstance.add(cDate, dMonth / 12, 'y');
  31152. return (cDate.toJD() - EPOCHJD) * ONEDAY + timeMs;
  31153. } catch(e) {
  31154. Loggers.error('invalid ms ' + ms + ' in calendar ' + calendar);
  31155. // then keep going in gregorian even though the result will be 'Invalid'
  31156. }
  31157. }
  31158. var y = new Date(ms + THREEDAYS);
  31159. return y.setUTCMonth(y.getUTCMonth() + dMonth) + timeMs - THREEDAYS;
  31160. };
  31161. /*
  31162. * findExactDates: what fraction of data is exact days, months, or years?
  31163. *
  31164. * data: array of millisecond values
  31165. * calendar (string) the calendar to test against
  31166. */
  31167. exports.findExactDates = function(data, calendar) {
  31168. var exactYears = 0;
  31169. var exactMonths = 0;
  31170. var exactDays = 0;
  31171. var blankCount = 0;
  31172. var d;
  31173. var di;
  31174. var calInstance = (
  31175. isWorldCalendar(calendar) &&
  31176. Registry.getComponentMethod('calendars', 'getCal')(calendar)
  31177. );
  31178. for(var i = 0; i < data.length; i++) {
  31179. di = data[i];
  31180. // not date data at all
  31181. if(!isNumeric(di)) {
  31182. blankCount ++;
  31183. continue;
  31184. }
  31185. // not an exact date
  31186. if(di % ONEDAY) continue;
  31187. if(calInstance) {
  31188. try {
  31189. d = calInstance.fromJD(di / ONEDAY + EPOCHJD);
  31190. if(d.day() === 1) {
  31191. if(d.month() === 1) exactYears++;
  31192. else exactMonths++;
  31193. }
  31194. else exactDays++;
  31195. }
  31196. catch(e) {
  31197. // invalid date in this calendar - ignore it here.
  31198. }
  31199. }
  31200. else {
  31201. d = new Date(di);
  31202. if(d.getUTCDate() === 1) {
  31203. if(d.getUTCMonth() === 0) exactYears++;
  31204. else exactMonths++;
  31205. }
  31206. else exactDays++;
  31207. }
  31208. }
  31209. exactMonths += exactYears;
  31210. exactDays += exactMonths;
  31211. var dataCount = data.length - blankCount;
  31212. return {
  31213. exactYears: exactYears / dataCount,
  31214. exactMonths: exactMonths / dataCount,
  31215. exactDays: exactDays / dataCount
  31216. };
  31217. };
  31218. },{"../constants/numerical":149,"../registry":257,"./loggers":172,"./mod":175,"d3":16,"fast-isnumeric":18}],161:[function(_dereq_,module,exports){
  31219. /**
  31220. * Copyright 2012-2019, Plotly, Inc.
  31221. * All rights reserved.
  31222. *
  31223. * This source code is licensed under the MIT license found in the
  31224. * LICENSE file in the root directory of this source tree.
  31225. */
  31226. 'use strict';
  31227. /* global jQuery:false */
  31228. var EventEmitter = _dereq_('events').EventEmitter;
  31229. var Events = {
  31230. init: function(plotObj) {
  31231. /*
  31232. * If we have already instantiated an emitter for this plot
  31233. * return early.
  31234. */
  31235. if(plotObj._ev instanceof EventEmitter) return plotObj;
  31236. var ev = new EventEmitter();
  31237. var internalEv = new EventEmitter();
  31238. /*
  31239. * Assign to plot._ev while we still live in a land
  31240. * where plot is a DOM element with stuff attached to it.
  31241. * In the future we can make plot the event emitter itself.
  31242. */
  31243. plotObj._ev = ev;
  31244. /*
  31245. * Create a second event handler that will manage events *internally*.
  31246. * This allows parts of plotly to respond to thing like relayout without
  31247. * having to use the user-facing event handler. They cannot peacefully
  31248. * coexist on the same handler because a user invoking
  31249. * plotObj.removeAllListeners() would detach internal events, breaking
  31250. * plotly.
  31251. */
  31252. plotObj._internalEv = internalEv;
  31253. /*
  31254. * Assign bound methods from the ev to the plot object. These methods
  31255. * will reference the 'this' of plot._ev even though they are methods
  31256. * of plot. This will keep the event machinery away from the plot object
  31257. * which currently is often a DOM element but presents an API that will
  31258. * continue to function when plot becomes an emitter. Not all EventEmitter
  31259. * methods have been bound to `plot` as some do not currently add value to
  31260. * the Plotly event API.
  31261. */
  31262. plotObj.on = ev.on.bind(ev);
  31263. plotObj.once = ev.once.bind(ev);
  31264. plotObj.removeListener = ev.removeListener.bind(ev);
  31265. plotObj.removeAllListeners = ev.removeAllListeners.bind(ev);
  31266. /*
  31267. * Create functions for managing internal events. These are *only* triggered
  31268. * by the mirroring of external events via the emit function.
  31269. */
  31270. plotObj._internalOn = internalEv.on.bind(internalEv);
  31271. plotObj._internalOnce = internalEv.once.bind(internalEv);
  31272. plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv);
  31273. plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv);
  31274. /*
  31275. * We must wrap emit to continue to support JQuery events. The idea
  31276. * is to check to see if the user is using JQuery events, if they are
  31277. * we emit JQuery events to trigger user handlers as well as the EventEmitter
  31278. * events.
  31279. */
  31280. plotObj.emit = function(event, data) {
  31281. if(typeof jQuery !== 'undefined') {
  31282. jQuery(plotObj).trigger(event, data);
  31283. }
  31284. ev.emit(event, data);
  31285. internalEv.emit(event, data);
  31286. };
  31287. return plotObj;
  31288. },
  31289. /*
  31290. * This function behaves like jQuery's triggerHandler. It calls
  31291. * all handlers for a particular event and returns the return value
  31292. * of the LAST handler. This function also triggers jQuery's
  31293. * triggerHandler for backwards compatibility.
  31294. */
  31295. triggerHandler: function(plotObj, event, data) {
  31296. var jQueryHandlerValue;
  31297. var nodeEventHandlerValue;
  31298. /*
  31299. * If jQuery exists run all its handlers for this event and
  31300. * collect the return value of the LAST handler function
  31301. */
  31302. if(typeof jQuery !== 'undefined') {
  31303. jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data);
  31304. }
  31305. /*
  31306. * Now run all the node style event handlers
  31307. */
  31308. var ev = plotObj._ev;
  31309. if(!ev) return jQueryHandlerValue;
  31310. var handlers = ev._events[event];
  31311. if(!handlers) return jQueryHandlerValue;
  31312. // making sure 'this' is the EventEmitter instance
  31313. function apply(handler) {
  31314. // The 'once' case, we can't just call handler() as we need
  31315. // the return value here. So,
  31316. // - remove handler
  31317. // - call listener and grab return value!
  31318. // - stash 'fired' key to not call handler twice
  31319. if(handler.listener) {
  31320. ev.removeListener(event, handler.listener);
  31321. if(!handler.fired) {
  31322. handler.fired = true;
  31323. return handler.listener.apply(ev, [data]);
  31324. }
  31325. } else {
  31326. return handler.apply(ev, [data]);
  31327. }
  31328. }
  31329. // handlers can be function or an array of functions
  31330. handlers = Array.isArray(handlers) ? handlers : [handlers];
  31331. var i;
  31332. for(i = 0; i < handlers.length - 1; i++) {
  31333. apply(handlers[i]);
  31334. }
  31335. // now call the final handler and collect its value
  31336. nodeEventHandlerValue = apply(handlers[i]);
  31337. /*
  31338. * Return either the jQuery handler value if it exists or the
  31339. * nodeEventHandler value. jQuery event value supersedes nodejs
  31340. * events for backwards compatibility reasons.
  31341. */
  31342. return jQueryHandlerValue !== undefined ?
  31343. jQueryHandlerValue :
  31344. nodeEventHandlerValue;
  31345. },
  31346. purge: function(plotObj) {
  31347. delete plotObj._ev;
  31348. delete plotObj.on;
  31349. delete plotObj.once;
  31350. delete plotObj.removeListener;
  31351. delete plotObj.removeAllListeners;
  31352. delete plotObj.emit;
  31353. delete plotObj._ev;
  31354. delete plotObj._internalEv;
  31355. delete plotObj._internalOn;
  31356. delete plotObj._internalOnce;
  31357. delete plotObj._removeInternalListener;
  31358. delete plotObj._removeAllInternalListeners;
  31359. return plotObj;
  31360. }
  31361. };
  31362. module.exports = Events;
  31363. },{"events":15}],162:[function(_dereq_,module,exports){
  31364. /**
  31365. * Copyright 2012-2019, Plotly, Inc.
  31366. * All rights reserved.
  31367. *
  31368. * This source code is licensed under the MIT license found in the
  31369. * LICENSE file in the root directory of this source tree.
  31370. */
  31371. 'use strict';
  31372. var isPlainObject = _dereq_('./is_plain_object.js');
  31373. var isArray = Array.isArray;
  31374. function primitivesLoopSplice(source, target) {
  31375. var i, value;
  31376. for(i = 0; i < source.length; i++) {
  31377. value = source[i];
  31378. if(value !== null && typeof(value) === 'object') {
  31379. return false;
  31380. }
  31381. if(value !== void(0)) {
  31382. target[i] = value;
  31383. }
  31384. }
  31385. return true;
  31386. }
  31387. exports.extendFlat = function() {
  31388. return _extend(arguments, false, false, false);
  31389. };
  31390. exports.extendDeep = function() {
  31391. return _extend(arguments, true, false, false);
  31392. };
  31393. exports.extendDeepAll = function() {
  31394. return _extend(arguments, true, true, false);
  31395. };
  31396. exports.extendDeepNoArrays = function() {
  31397. return _extend(arguments, true, false, true);
  31398. };
  31399. /*
  31400. * Inspired by https://github.com/justmoon/node-extend/blob/master/index.js
  31401. * All credit to the jQuery authors for perfecting this amazing utility.
  31402. *
  31403. * API difference with jQuery version:
  31404. * - No optional boolean (true -> deep extend) first argument,
  31405. * use `extendFlat` for first-level only extend and
  31406. * use `extendDeep` for a deep extend.
  31407. *
  31408. * Other differences with jQuery version:
  31409. * - Uses a modern (and faster) isPlainObject routine.
  31410. * - Expected to work with object {} and array [] arguments only.
  31411. * - Does not check for circular structure.
  31412. * FYI: jQuery only does a check across one level.
  31413. * Warning: this might result in infinite loops.
  31414. *
  31415. */
  31416. function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) {
  31417. var target = inputs[0];
  31418. var length = inputs.length;
  31419. var input, key, src, copy, copyIsArray, clone, allPrimitives;
  31420. // TODO does this do the right thing for typed arrays?
  31421. if(length === 2 && isArray(target) && isArray(inputs[1]) && target.length === 0) {
  31422. allPrimitives = primitivesLoopSplice(inputs[1], target);
  31423. if(allPrimitives) {
  31424. return target;
  31425. } else {
  31426. target.splice(0, target.length); // reset target and continue to next block
  31427. }
  31428. }
  31429. for(var i = 1; i < length; i++) {
  31430. input = inputs[i];
  31431. for(key in input) {
  31432. src = target[key];
  31433. copy = input[key];
  31434. // Stop early and just transfer the array if array copies are disallowed:
  31435. if(noArrayCopies && isArray(copy)) {
  31436. target[key] = copy;
  31437. }
  31438. // recurse if we're merging plain objects or arrays
  31439. else if(isDeep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
  31440. if(copyIsArray) {
  31441. copyIsArray = false;
  31442. clone = src && isArray(src) ? src : [];
  31443. } else {
  31444. clone = src && isPlainObject(src) ? src : {};
  31445. }
  31446. // never move original objects, clone them
  31447. target[key] = _extend([clone, copy], isDeep, keepAllKeys, noArrayCopies);
  31448. }
  31449. // don't bring in undefined values, except for extendDeepAll
  31450. else if(typeof copy !== 'undefined' || keepAllKeys) {
  31451. target[key] = copy;
  31452. }
  31453. }
  31454. }
  31455. return target;
  31456. }
  31457. },{"./is_plain_object.js":169}],163:[function(_dereq_,module,exports){
  31458. /**
  31459. * Copyright 2012-2019, Plotly, Inc.
  31460. * All rights reserved.
  31461. *
  31462. * This source code is licensed under the MIT license found in the
  31463. * LICENSE file in the root directory of this source tree.
  31464. */
  31465. 'use strict';
  31466. /**
  31467. * Return news array containing only the unique items
  31468. * found in input array.
  31469. *
  31470. * IMPORTANT: Note that items are considered unique
  31471. * if `String({})` is unique. For example;
  31472. *
  31473. * Lib.filterUnique([ { a: 1 }, { b: 2 } ])
  31474. *
  31475. * returns [{ a: 1 }]
  31476. *
  31477. * and
  31478. *
  31479. * Lib.filterUnique([ '1', 1 ])
  31480. *
  31481. * returns ['1']
  31482. *
  31483. *
  31484. * @param {array} array base array
  31485. * @return {array} new filtered array
  31486. */
  31487. module.exports = function filterUnique(array) {
  31488. var seen = {};
  31489. var out = [];
  31490. var j = 0;
  31491. for(var i = 0; i < array.length; i++) {
  31492. var item = array[i];
  31493. if(seen[item] !== 1) {
  31494. seen[item] = 1;
  31495. out[j++] = item;
  31496. }
  31497. }
  31498. return out;
  31499. };
  31500. },{}],164:[function(_dereq_,module,exports){
  31501. /**
  31502. * Copyright 2012-2019, Plotly, Inc.
  31503. * All rights reserved.
  31504. *
  31505. * This source code is licensed under the MIT license found in the
  31506. * LICENSE file in the root directory of this source tree.
  31507. */
  31508. 'use strict';
  31509. /** Filter out object items with visible !== true
  31510. * insider array container.
  31511. *
  31512. * @param {array of objects} container
  31513. * @return {array of objects} of length <= container
  31514. *
  31515. */
  31516. module.exports = function filterVisible(container) {
  31517. var filterFn = isCalcData(container) ? calcDataFilter : baseFilter;
  31518. var out = [];
  31519. for(var i = 0; i < container.length; i++) {
  31520. var item = container[i];
  31521. if(filterFn(item)) out.push(item);
  31522. }
  31523. return out;
  31524. };
  31525. function baseFilter(item) {
  31526. return item.visible === true;
  31527. }
  31528. function calcDataFilter(item) {
  31529. return item[0].trace.visible === true;
  31530. }
  31531. function isCalcData(cont) {
  31532. return (
  31533. Array.isArray(cont) &&
  31534. Array.isArray(cont[0]) &&
  31535. cont[0][0] &&
  31536. cont[0][0].trace
  31537. );
  31538. }
  31539. },{}],165:[function(_dereq_,module,exports){
  31540. /**
  31541. * Copyright 2012-2019, Plotly, Inc.
  31542. * All rights reserved.
  31543. *
  31544. * This source code is licensed under the MIT license found in the
  31545. * LICENSE file in the root directory of this source tree.
  31546. */
  31547. 'use strict';
  31548. var mod = _dereq_('./mod').mod;
  31549. /*
  31550. * look for intersection of two line segments
  31551. * (1->2 and 3->4) - returns array [x,y] if they do, null if not
  31552. */
  31553. exports.segmentsIntersect = segmentsIntersect;
  31554. function segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4) {
  31555. var a = x2 - x1;
  31556. var b = x3 - x1;
  31557. var c = x4 - x3;
  31558. var d = y2 - y1;
  31559. var e = y3 - y1;
  31560. var f = y4 - y3;
  31561. var det = a * f - c * d;
  31562. // parallel lines? intersection is undefined
  31563. // ignore the case where they are colinear
  31564. if(det === 0) return null;
  31565. var t = (b * f - c * e) / det;
  31566. var u = (b * d - a * e) / det;
  31567. // segments do not intersect?
  31568. if(u < 0 || u > 1 || t < 0 || t > 1) return null;
  31569. return {x: x1 + a * t, y: y1 + d * t};
  31570. }
  31571. /*
  31572. * find the minimum distance between two line segments (1->2 and 3->4)
  31573. */
  31574. exports.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) {
  31575. if(segmentsIntersect(x1, y1, x2, y2, x3, y3, x4, y4)) return 0;
  31576. // the two segments and their lengths squared
  31577. var x12 = x2 - x1;
  31578. var y12 = y2 - y1;
  31579. var x34 = x4 - x3;
  31580. var y34 = y4 - y3;
  31581. var ll12 = x12 * x12 + y12 * y12;
  31582. var ll34 = x34 * x34 + y34 * y34;
  31583. // calculate distance squared, then take the sqrt at the very end
  31584. var dist2 = Math.min(
  31585. perpDistance2(x12, y12, ll12, x3 - x1, y3 - y1),
  31586. perpDistance2(x12, y12, ll12, x4 - x1, y4 - y1),
  31587. perpDistance2(x34, y34, ll34, x1 - x3, y1 - y3),
  31588. perpDistance2(x34, y34, ll34, x2 - x3, y2 - y3)
  31589. );
  31590. return Math.sqrt(dist2);
  31591. };
  31592. /*
  31593. * distance squared from segment ab to point c
  31594. * [xab, yab] is the vector b-a
  31595. * [xac, yac] is the vector c-a
  31596. * llab is the length squared of (b-a), just to simplify calculation
  31597. */
  31598. function perpDistance2(xab, yab, llab, xac, yac) {
  31599. var fcAB = (xac * xab + yac * yab);
  31600. if(fcAB < 0) {
  31601. // point c is closer to point a
  31602. return xac * xac + yac * yac;
  31603. }
  31604. else if(fcAB > llab) {
  31605. // point c is closer to point b
  31606. var xbc = xac - xab;
  31607. var ybc = yac - yab;
  31608. return xbc * xbc + ybc * ybc;
  31609. }
  31610. else {
  31611. // perpendicular distance is the shortest
  31612. var crossProduct = xac * yab - yac * xab;
  31613. return crossProduct * crossProduct / llab;
  31614. }
  31615. }
  31616. // a very short-term cache for getTextLocation, just because
  31617. // we're often looping over the same locations multiple times
  31618. // invalidated as soon as we look at a different path
  31619. var locationCache, workingPath, workingTextWidth;
  31620. // turn a path and position along it into x, y, and angle for the given text
  31621. exports.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) {
  31622. if(path !== workingPath || textWidth !== workingTextWidth) {
  31623. locationCache = {};
  31624. workingPath = path;
  31625. workingTextWidth = textWidth;
  31626. }
  31627. if(locationCache[positionOnPath]) {
  31628. return locationCache[positionOnPath];
  31629. }
  31630. // for the angle, use points on the path separated by the text width
  31631. // even though due to curvature, the text will cover a bit more than that
  31632. var p0 = path.getPointAtLength(mod(positionOnPath - textWidth / 2, totalPathLen));
  31633. var p1 = path.getPointAtLength(mod(positionOnPath + textWidth / 2, totalPathLen));
  31634. // note: atan handles 1/0 nicely
  31635. var theta = Math.atan((p1.y - p0.y) / (p1.x - p0.x));
  31636. // center the text at 2/3 of the center position plus 1/3 the p0/p1 midpoint
  31637. // that's the average position of this segment, assuming it's roughly quadratic
  31638. var pCenter = path.getPointAtLength(mod(positionOnPath, totalPathLen));
  31639. var x = (pCenter.x * 4 + p0.x + p1.x) / 6;
  31640. var y = (pCenter.y * 4 + p0.y + p1.y) / 6;
  31641. var out = {x: x, y: y, theta: theta};
  31642. locationCache[positionOnPath] = out;
  31643. return out;
  31644. };
  31645. exports.clearLocationCache = function() {
  31646. workingPath = null;
  31647. };
  31648. /*
  31649. * Find the segment of `path` that's within the visible area
  31650. * given by `bounds` {left, right, top, bottom}, to within a
  31651. * precision of `buffer` px
  31652. *
  31653. * returns: undefined if nothing is visible, else object:
  31654. * {
  31655. * min: position where the path first enters bounds, or 0 if it
  31656. * starts within bounds
  31657. * max: position where the path last exits bounds, or the path length
  31658. * if it finishes within bounds
  31659. * len: max - min, ie the length of visible path
  31660. * total: the total path length - just included so the caller doesn't
  31661. * need to call path.getTotalLength() again
  31662. * isClosed: true iff the start and end points of the path are both visible
  31663. * and are at the same point
  31664. * }
  31665. *
  31666. * Works by starting from either end and repeatedly finding the distance from
  31667. * that point to the plot area, and if it's outside the plot, moving along the
  31668. * path by that distance (because the plot must be at least that far away on
  31669. * the path). Note that if a path enters, exits, and re-enters the plot, we
  31670. * will not capture this behavior.
  31671. */
  31672. exports.getVisibleSegment = function getVisibleSegment(path, bounds, buffer) {
  31673. var left = bounds.left;
  31674. var right = bounds.right;
  31675. var top = bounds.top;
  31676. var bottom = bounds.bottom;
  31677. var pMin = 0;
  31678. var pTotal = path.getTotalLength();
  31679. var pMax = pTotal;
  31680. var pt0, ptTotal;
  31681. function getDistToPlot(len) {
  31682. var pt = path.getPointAtLength(len);
  31683. // hold on to the start and end points for `closed`
  31684. if(len === 0) pt0 = pt;
  31685. else if(len === pTotal) ptTotal = pt;
  31686. var dx = (pt.x < left) ? left - pt.x : (pt.x > right ? pt.x - right : 0);
  31687. var dy = (pt.y < top) ? top - pt.y : (pt.y > bottom ? pt.y - bottom : 0);
  31688. return Math.sqrt(dx * dx + dy * dy);
  31689. }
  31690. var distToPlot = getDistToPlot(pMin);
  31691. while(distToPlot) {
  31692. pMin += distToPlot + buffer;
  31693. if(pMin > pMax) return;
  31694. distToPlot = getDistToPlot(pMin);
  31695. }
  31696. distToPlot = getDistToPlot(pMax);
  31697. while(distToPlot) {
  31698. pMax -= distToPlot + buffer;
  31699. if(pMin > pMax) return;
  31700. distToPlot = getDistToPlot(pMax);
  31701. }
  31702. return {
  31703. min: pMin,
  31704. max: pMax,
  31705. len: pMax - pMin,
  31706. total: pTotal,
  31707. isClosed: pMin === 0 && pMax === pTotal &&
  31708. Math.abs(pt0.x - ptTotal.x) < 0.1 &&
  31709. Math.abs(pt0.y - ptTotal.y) < 0.1
  31710. };
  31711. };
  31712. /**
  31713. * Find point on SVG path corresponding to a given constraint coordinate
  31714. *
  31715. * @param {SVGPathElement} path
  31716. * @param {Number} val : constraint coordinate value
  31717. * @param {String} coord : 'x' or 'y' the constraint coordinate
  31718. * @param {Object} opts :
  31719. * - {Number} pathLength : supply total path length before hand
  31720. * - {Number} tolerance
  31721. * - {Number} iterationLimit
  31722. * @return {SVGPoint}
  31723. */
  31724. exports.findPointOnPath = function findPointOnPath(path, val, coord, opts) {
  31725. opts = opts || {};
  31726. var pathLength = opts.pathLength || path.getTotalLength();
  31727. var tolerance = opts.tolerance || 1e-3;
  31728. var iterationLimit = opts.iterationLimit || 30;
  31729. // if path starts at a val greater than the path tail (like on vertical violins),
  31730. // we must flip the sign of the computed diff.
  31731. var mul = path.getPointAtLength(0)[coord] > path.getPointAtLength(pathLength)[coord] ? -1 : 1;
  31732. var i = 0;
  31733. var b0 = 0;
  31734. var b1 = pathLength;
  31735. var mid;
  31736. var pt;
  31737. var diff;
  31738. while(i < iterationLimit) {
  31739. mid = (b0 + b1) / 2;
  31740. pt = path.getPointAtLength(mid);
  31741. diff = pt[coord] - val;
  31742. if(Math.abs(diff) < tolerance) {
  31743. return pt;
  31744. } else {
  31745. if(mul * diff > 0) {
  31746. b1 = mid;
  31747. } else {
  31748. b0 = mid;
  31749. }
  31750. i++;
  31751. }
  31752. }
  31753. return pt;
  31754. };
  31755. },{"./mod":175}],166:[function(_dereq_,module,exports){
  31756. /**
  31757. * Copyright 2012-2019, Plotly, Inc.
  31758. * All rights reserved.
  31759. *
  31760. * This source code is licensed under the MIT license found in the
  31761. * LICENSE file in the root directory of this source tree.
  31762. */
  31763. 'use strict';
  31764. /**
  31765. * Allow referencing a graph DOM element either directly
  31766. * or by its id string
  31767. *
  31768. * @param {HTMLDivElement|string} gd: a graph element or its id
  31769. *
  31770. * @returns {HTMLDivElement} the DOM element of the graph
  31771. */
  31772. module.exports = function(gd) {
  31773. var gdElement;
  31774. if(typeof gd === 'string') {
  31775. gdElement = document.getElementById(gd);
  31776. if(gdElement === null) {
  31777. throw new Error('No DOM element with id \'' + gd + '\' exists on the page.');
  31778. }
  31779. return gdElement;
  31780. }
  31781. else if(gd === null || gd === undefined) {
  31782. throw new Error('DOM element provided is null or undefined');
  31783. }
  31784. return gd; // otherwise assume that gd is a DOM element
  31785. };
  31786. },{}],167:[function(_dereq_,module,exports){
  31787. /**
  31788. * Copyright 2012-2019, Plotly, Inc.
  31789. * All rights reserved.
  31790. *
  31791. * This source code is licensed under the MIT license found in the
  31792. * LICENSE file in the root directory of this source tree.
  31793. */
  31794. 'use strict';
  31795. // Simple helper functions
  31796. // none of these need any external deps
  31797. module.exports = function identity(d) { return d; };
  31798. },{}],168:[function(_dereq_,module,exports){
  31799. /**
  31800. * Copyright 2012-2019, Plotly, Inc.
  31801. * All rights reserved.
  31802. *
  31803. * This source code is licensed under the MIT license found in the
  31804. * LICENSE file in the root directory of this source tree.
  31805. */
  31806. 'use strict';
  31807. var d3 = _dereq_('d3');
  31808. var isNumeric = _dereq_('fast-isnumeric');
  31809. var numConstants = _dereq_('../constants/numerical');
  31810. var FP_SAFE = numConstants.FP_SAFE;
  31811. var BADNUM = numConstants.BADNUM;
  31812. var lib = module.exports = {};
  31813. lib.nestedProperty = _dereq_('./nested_property');
  31814. lib.keyedContainer = _dereq_('./keyed_container');
  31815. lib.relativeAttr = _dereq_('./relative_attr');
  31816. lib.isPlainObject = _dereq_('./is_plain_object');
  31817. lib.toLogRange = _dereq_('./to_log_range');
  31818. lib.relinkPrivateKeys = _dereq_('./relink_private');
  31819. var arrayModule = _dereq_('./array');
  31820. lib.isTypedArray = arrayModule.isTypedArray;
  31821. lib.isArrayOrTypedArray = arrayModule.isArrayOrTypedArray;
  31822. lib.isArray1D = arrayModule.isArray1D;
  31823. lib.ensureArray = arrayModule.ensureArray;
  31824. lib.concat = arrayModule.concat;
  31825. lib.maxRowLength = arrayModule.maxRowLength;
  31826. lib.minRowLength = arrayModule.minRowLength;
  31827. var modModule = _dereq_('./mod');
  31828. lib.mod = modModule.mod;
  31829. lib.modHalf = modModule.modHalf;
  31830. var coerceModule = _dereq_('./coerce');
  31831. lib.valObjectMeta = coerceModule.valObjectMeta;
  31832. lib.coerce = coerceModule.coerce;
  31833. lib.coerce2 = coerceModule.coerce2;
  31834. lib.coerceFont = coerceModule.coerceFont;
  31835. lib.coerceHoverinfo = coerceModule.coerceHoverinfo;
  31836. lib.coerceSelectionMarkerOpacity = coerceModule.coerceSelectionMarkerOpacity;
  31837. lib.validate = coerceModule.validate;
  31838. var datesModule = _dereq_('./dates');
  31839. lib.dateTime2ms = datesModule.dateTime2ms;
  31840. lib.isDateTime = datesModule.isDateTime;
  31841. lib.ms2DateTime = datesModule.ms2DateTime;
  31842. lib.ms2DateTimeLocal = datesModule.ms2DateTimeLocal;
  31843. lib.cleanDate = datesModule.cleanDate;
  31844. lib.isJSDate = datesModule.isJSDate;
  31845. lib.formatDate = datesModule.formatDate;
  31846. lib.incrementMonth = datesModule.incrementMonth;
  31847. lib.dateTick0 = datesModule.dateTick0;
  31848. lib.dfltRange = datesModule.dfltRange;
  31849. lib.findExactDates = datesModule.findExactDates;
  31850. lib.MIN_MS = datesModule.MIN_MS;
  31851. lib.MAX_MS = datesModule.MAX_MS;
  31852. var searchModule = _dereq_('./search');
  31853. lib.findBin = searchModule.findBin;
  31854. lib.sorterAsc = searchModule.sorterAsc;
  31855. lib.sorterDes = searchModule.sorterDes;
  31856. lib.distinctVals = searchModule.distinctVals;
  31857. lib.roundUp = searchModule.roundUp;
  31858. lib.sort = searchModule.sort;
  31859. lib.findIndexOfMin = searchModule.findIndexOfMin;
  31860. var statsModule = _dereq_('./stats');
  31861. lib.aggNums = statsModule.aggNums;
  31862. lib.len = statsModule.len;
  31863. lib.mean = statsModule.mean;
  31864. lib.midRange = statsModule.midRange;
  31865. lib.variance = statsModule.variance;
  31866. lib.stdev = statsModule.stdev;
  31867. lib.interp = statsModule.interp;
  31868. var matrixModule = _dereq_('./matrix');
  31869. lib.init2dArray = matrixModule.init2dArray;
  31870. lib.transposeRagged = matrixModule.transposeRagged;
  31871. lib.dot = matrixModule.dot;
  31872. lib.translationMatrix = matrixModule.translationMatrix;
  31873. lib.rotationMatrix = matrixModule.rotationMatrix;
  31874. lib.rotationXYMatrix = matrixModule.rotationXYMatrix;
  31875. lib.apply2DTransform = matrixModule.apply2DTransform;
  31876. lib.apply2DTransform2 = matrixModule.apply2DTransform2;
  31877. var anglesModule = _dereq_('./angles');
  31878. lib.deg2rad = anglesModule.deg2rad;
  31879. lib.rad2deg = anglesModule.rad2deg;
  31880. lib.angleDelta = anglesModule.angleDelta;
  31881. lib.angleDist = anglesModule.angleDist;
  31882. lib.isFullCircle = anglesModule.isFullCircle;
  31883. lib.isAngleInsideSector = anglesModule.isAngleInsideSector;
  31884. lib.isPtInsideSector = anglesModule.isPtInsideSector;
  31885. lib.pathArc = anglesModule.pathArc;
  31886. lib.pathSector = anglesModule.pathSector;
  31887. lib.pathAnnulus = anglesModule.pathAnnulus;
  31888. var anchorUtils = _dereq_('./anchor_utils');
  31889. lib.isLeftAnchor = anchorUtils.isLeftAnchor;
  31890. lib.isCenterAnchor = anchorUtils.isCenterAnchor;
  31891. lib.isRightAnchor = anchorUtils.isRightAnchor;
  31892. lib.isTopAnchor = anchorUtils.isTopAnchor;
  31893. lib.isMiddleAnchor = anchorUtils.isMiddleAnchor;
  31894. lib.isBottomAnchor = anchorUtils.isBottomAnchor;
  31895. var geom2dModule = _dereq_('./geometry2d');
  31896. lib.segmentsIntersect = geom2dModule.segmentsIntersect;
  31897. lib.segmentDistance = geom2dModule.segmentDistance;
  31898. lib.getTextLocation = geom2dModule.getTextLocation;
  31899. lib.clearLocationCache = geom2dModule.clearLocationCache;
  31900. lib.getVisibleSegment = geom2dModule.getVisibleSegment;
  31901. lib.findPointOnPath = geom2dModule.findPointOnPath;
  31902. var extendModule = _dereq_('./extend');
  31903. lib.extendFlat = extendModule.extendFlat;
  31904. lib.extendDeep = extendModule.extendDeep;
  31905. lib.extendDeepAll = extendModule.extendDeepAll;
  31906. lib.extendDeepNoArrays = extendModule.extendDeepNoArrays;
  31907. var loggersModule = _dereq_('./loggers');
  31908. lib.log = loggersModule.log;
  31909. lib.warn = loggersModule.warn;
  31910. lib.error = loggersModule.error;
  31911. var regexModule = _dereq_('./regex');
  31912. lib.counterRegex = regexModule.counter;
  31913. var throttleModule = _dereq_('./throttle');
  31914. lib.throttle = throttleModule.throttle;
  31915. lib.throttleDone = throttleModule.done;
  31916. lib.clearThrottle = throttleModule.clear;
  31917. lib.getGraphDiv = _dereq_('./get_graph_div');
  31918. lib.clearResponsive = _dereq_('./clear_responsive');
  31919. lib.makeTraceGroups = _dereq_('./make_trace_groups');
  31920. lib._ = _dereq_('./localize');
  31921. lib.notifier = _dereq_('./notifier');
  31922. lib.filterUnique = _dereq_('./filter_unique');
  31923. lib.filterVisible = _dereq_('./filter_visible');
  31924. lib.pushUnique = _dereq_('./push_unique');
  31925. lib.cleanNumber = _dereq_('./clean_number');
  31926. lib.ensureNumber = function num(v) {
  31927. if(!isNumeric(v)) return BADNUM;
  31928. v = Number(v);
  31929. if(v < -FP_SAFE || v > FP_SAFE) return BADNUM;
  31930. return isNumeric(v) ? Number(v) : BADNUM;
  31931. };
  31932. /**
  31933. * Is v a valid array index? Accepts numeric strings as well as numbers.
  31934. *
  31935. * @param {any} v: the value to test
  31936. * @param {Optional[integer]} len: the array length we are indexing
  31937. *
  31938. * @return {bool}: v is a valid array index
  31939. */
  31940. lib.isIndex = function(v, len) {
  31941. if(len !== undefined && v >= len) return false;
  31942. return isNumeric(v) && (v >= 0) && (v % 1 === 0);
  31943. };
  31944. lib.noop = _dereq_('./noop');
  31945. lib.identity = _dereq_('./identity');
  31946. /**
  31947. * create an array of length 'cnt' filled with 'v' at all indices
  31948. *
  31949. * @param {any} v
  31950. * @param {number} cnt
  31951. * @return {array}
  31952. */
  31953. lib.repeat = function(v, cnt) {
  31954. var out = new Array(cnt);
  31955. for(var i = 0; i < cnt; i++) {
  31956. out[i] = v;
  31957. }
  31958. return out;
  31959. };
  31960. /**
  31961. * swap x and y of the same attribute in container cont
  31962. * specify attr with a ? in place of x/y
  31963. * you can also swap other things than x/y by providing part1 and part2
  31964. */
  31965. lib.swapAttrs = function(cont, attrList, part1, part2) {
  31966. if(!part1) part1 = 'x';
  31967. if(!part2) part2 = 'y';
  31968. for(var i = 0; i < attrList.length; i++) {
  31969. var attr = attrList[i];
  31970. var xp = lib.nestedProperty(cont, attr.replace('?', part1));
  31971. var yp = lib.nestedProperty(cont, attr.replace('?', part2));
  31972. var temp = xp.get();
  31973. xp.set(yp.get());
  31974. yp.set(temp);
  31975. }
  31976. };
  31977. /**
  31978. * SVG painter's algo worked around with reinsertion
  31979. */
  31980. lib.raiseToTop = function raiseToTop(elem) {
  31981. elem.parentNode.appendChild(elem);
  31982. };
  31983. /**
  31984. * cancel a possibly pending transition; returned selection may be used by caller
  31985. */
  31986. lib.cancelTransition = function(selection) {
  31987. return selection.transition().duration(0);
  31988. };
  31989. // constrain - restrict a number v to be between v0 and v1
  31990. lib.constrain = function(v, v0, v1) {
  31991. if(v0 > v1) return Math.max(v1, Math.min(v0, v));
  31992. return Math.max(v0, Math.min(v1, v));
  31993. };
  31994. /**
  31995. * do two bounding boxes from getBoundingClientRect,
  31996. * ie {left,right,top,bottom,width,height}, overlap?
  31997. * takes optional padding pixels
  31998. */
  31999. lib.bBoxIntersect = function(a, b, pad) {
  32000. pad = pad || 0;
  32001. return (a.left <= b.right + pad &&
  32002. b.left <= a.right + pad &&
  32003. a.top <= b.bottom + pad &&
  32004. b.top <= a.bottom + pad);
  32005. };
  32006. /*
  32007. * simpleMap: alternative to Array.map that only
  32008. * passes on the element and up to 2 extra args you
  32009. * provide (but not the array index or the whole array)
  32010. *
  32011. * array: the array to map it to
  32012. * func: the function to apply
  32013. * x1, x2: optional extra args
  32014. */
  32015. lib.simpleMap = function(array, func, x1, x2) {
  32016. var len = array.length;
  32017. var out = new Array(len);
  32018. for(var i = 0; i < len; i++) out[i] = func(array[i], x1, x2);
  32019. return out;
  32020. };
  32021. /**
  32022. * Random string generator
  32023. *
  32024. * @param {object} existing
  32025. * pass in strings to avoid as keys with truthy values
  32026. * @param {int} bits
  32027. * bits of information in the output string, default 24
  32028. * @param {int} base
  32029. * base of string representation, default 16. Should be a power of 2.
  32030. */
  32031. lib.randstr = function randstr(existing, bits, base, _recursion) {
  32032. if(!base) base = 16;
  32033. if(bits === undefined) bits = 24;
  32034. if(bits <= 0) return '0';
  32035. var digits = Math.log(Math.pow(2, bits)) / Math.log(base);
  32036. var res = '';
  32037. var i, b, x;
  32038. for(i = 2; digits === Infinity; i *= 2) {
  32039. digits = Math.log(Math.pow(2, bits / i)) / Math.log(base) * i;
  32040. }
  32041. var rem = digits - Math.floor(digits);
  32042. for(i = 0; i < Math.floor(digits); i++) {
  32043. x = Math.floor(Math.random() * base).toString(base);
  32044. res = x + res;
  32045. }
  32046. if(rem) {
  32047. b = Math.pow(base, rem);
  32048. x = Math.floor(Math.random() * b).toString(base);
  32049. res = x + res;
  32050. }
  32051. var parsed = parseInt(res, base);
  32052. if((existing && existing[res]) ||
  32053. (parsed !== Infinity && parsed >= Math.pow(2, bits))) {
  32054. if(_recursion > 10) {
  32055. lib.warn('randstr failed uniqueness');
  32056. return res;
  32057. }
  32058. return randstr(existing, bits, base, (_recursion || 0) + 1);
  32059. }
  32060. else return res;
  32061. };
  32062. lib.OptionControl = function(opt, optname) {
  32063. /*
  32064. * An environment to contain all option setters and
  32065. * getters that collectively modify opts.
  32066. *
  32067. * You can call up opts from any function in new object
  32068. * as this.optname || this.opt
  32069. *
  32070. * See FitOpts for example of usage
  32071. */
  32072. if(!opt) opt = {};
  32073. if(!optname) optname = 'opt';
  32074. var self = {};
  32075. self.optionList = [];
  32076. self._newoption = function(optObj) {
  32077. optObj[optname] = opt;
  32078. self[optObj.name] = optObj;
  32079. self.optionList.push(optObj);
  32080. };
  32081. self['_' + optname] = opt;
  32082. return self;
  32083. };
  32084. /**
  32085. * lib.smooth: smooth arrayIn by convolving with
  32086. * a hann window with given full width at half max
  32087. * bounce the ends in, so the output has the same length as the input
  32088. */
  32089. lib.smooth = function(arrayIn, FWHM) {
  32090. FWHM = Math.round(FWHM) || 0; // only makes sense for integers
  32091. if(FWHM < 2) return arrayIn;
  32092. var alen = arrayIn.length;
  32093. var alen2 = 2 * alen;
  32094. var wlen = 2 * FWHM - 1;
  32095. var w = new Array(wlen);
  32096. var arrayOut = new Array(alen);
  32097. var i;
  32098. var j;
  32099. var k;
  32100. var v;
  32101. // first make the window array
  32102. for(i = 0; i < wlen; i++) {
  32103. w[i] = (1 - Math.cos(Math.PI * (i + 1) / FWHM)) / (2 * FWHM);
  32104. }
  32105. // now do the convolution
  32106. for(i = 0; i < alen; i++) {
  32107. v = 0;
  32108. for(j = 0; j < wlen; j++) {
  32109. k = i + j + 1 - FWHM;
  32110. // multibounce
  32111. if(k < -alen) k -= alen2 * Math.round(k / alen2);
  32112. else if(k >= alen2) k -= alen2 * Math.floor(k / alen2);
  32113. // single bounce
  32114. if(k < 0) k = - 1 - k;
  32115. else if(k >= alen) k = alen2 - 1 - k;
  32116. v += arrayIn[k] * w[j];
  32117. }
  32118. arrayOut[i] = v;
  32119. }
  32120. return arrayOut;
  32121. };
  32122. /**
  32123. * syncOrAsync: run a sequence of functions synchronously
  32124. * as long as its returns are not promises (ie have no .then)
  32125. * includes one argument arg to send to all functions...
  32126. * this is mainly just to prevent us having to make wrapper functions
  32127. * when the only purpose of the wrapper is to reference gd
  32128. * and a final step to be executed at the end
  32129. * TODO: if there's an error and everything is sync,
  32130. * this doesn't happen yet because we want to make sure
  32131. * that it gets reported
  32132. */
  32133. lib.syncOrAsync = function(sequence, arg, finalStep) {
  32134. var ret, fni;
  32135. function continueAsync() {
  32136. return lib.syncOrAsync(sequence, arg, finalStep);
  32137. }
  32138. while(sequence.length) {
  32139. fni = sequence.splice(0, 1)[0];
  32140. ret = fni(arg);
  32141. if(ret && ret.then) {
  32142. return ret.then(continueAsync)
  32143. .then(undefined, lib.promiseError);
  32144. }
  32145. }
  32146. return finalStep && finalStep(arg);
  32147. };
  32148. /**
  32149. * Helper to strip trailing slash, from
  32150. * http://stackoverflow.com/questions/6680825/return-string-without-trailing-slash
  32151. */
  32152. lib.stripTrailingSlash = function(str) {
  32153. if(str.substr(-1) === '/') return str.substr(0, str.length - 1);
  32154. return str;
  32155. };
  32156. lib.noneOrAll = function(containerIn, containerOut, attrList) {
  32157. /**
  32158. * some attributes come together, so if you have one of them
  32159. * in the input, you should copy the default values of the others
  32160. * to the input as well.
  32161. */
  32162. if(!containerIn) return;
  32163. var hasAny = false;
  32164. var hasAll = true;
  32165. var i;
  32166. var val;
  32167. for(i = 0; i < attrList.length; i++) {
  32168. val = containerIn[attrList[i]];
  32169. if(val !== undefined && val !== null) hasAny = true;
  32170. else hasAll = false;
  32171. }
  32172. if(hasAny && !hasAll) {
  32173. for(i = 0; i < attrList.length; i++) {
  32174. containerIn[attrList[i]] = containerOut[attrList[i]];
  32175. }
  32176. }
  32177. };
  32178. /** merges calcdata field (given by cdAttr) with traceAttr values
  32179. *
  32180. * N.B. Loop over minimum of cd.length and traceAttr.length
  32181. * i.e. it does not try to fill in beyond traceAttr.length-1
  32182. *
  32183. * @param {array} traceAttr : trace attribute
  32184. * @param {object} cd : calcdata trace
  32185. * @param {string} cdAttr : calcdata key
  32186. */
  32187. lib.mergeArray = function(traceAttr, cd, cdAttr) {
  32188. if(lib.isArrayOrTypedArray(traceAttr)) {
  32189. var imax = Math.min(traceAttr.length, cd.length);
  32190. for(var i = 0; i < imax; i++) cd[i][cdAttr] = traceAttr[i];
  32191. }
  32192. };
  32193. /** fills calcdata field (given by cdAttr) with traceAttr values
  32194. * or function of traceAttr values (e.g. some fallback)
  32195. *
  32196. * N.B. Loops over all cd items.
  32197. *
  32198. * @param {array} traceAttr : trace attribute
  32199. * @param {object} cd : calcdata trace
  32200. * @param {string} cdAttr : calcdata key
  32201. * @param {function} [fn] : optional function to apply to each array item
  32202. */
  32203. lib.fillArray = function(traceAttr, cd, cdAttr, fn) {
  32204. fn = fn || lib.identity;
  32205. if(lib.isArrayOrTypedArray(traceAttr)) {
  32206. for(var i = 0; i < cd.length; i++) {
  32207. cd[i][cdAttr] = fn(traceAttr[i]);
  32208. }
  32209. }
  32210. };
  32211. /** Handler for trace-wide vs per-point options
  32212. *
  32213. * @param {object} trace : (full) trace object
  32214. * @param {number} ptNumber : index of the point in question
  32215. * @param {string} astr : attribute string
  32216. * @param {function} [fn] : optional function to apply to each array item
  32217. *
  32218. * @return {any}
  32219. */
  32220. lib.castOption = function(trace, ptNumber, astr, fn) {
  32221. fn = fn || lib.identity;
  32222. var val = lib.nestedProperty(trace, astr).get();
  32223. if(lib.isArrayOrTypedArray(val)) {
  32224. if(Array.isArray(ptNumber) && lib.isArrayOrTypedArray(val[ptNumber[0]])) {
  32225. return fn(val[ptNumber[0]][ptNumber[1]]);
  32226. } else {
  32227. return fn(val[ptNumber]);
  32228. }
  32229. } else {
  32230. return val;
  32231. }
  32232. };
  32233. /** Extract option from calcdata item, correctly falling back to
  32234. * trace value if not found.
  32235. *
  32236. * @param {object} calcPt : calcdata[i][j] item
  32237. * @param {object} trace : (full) trace object
  32238. * @param {string} calcKey : calcdata key
  32239. * @param {string} traceKey : aka trace attribute string
  32240. * @return {any}
  32241. */
  32242. lib.extractOption = function(calcPt, trace, calcKey, traceKey) {
  32243. if(calcKey in calcPt) return calcPt[calcKey];
  32244. // fallback to trace value,
  32245. // must check if value isn't itself an array
  32246. // which means the trace attribute has a corresponding
  32247. // calcdata key, but its value is falsy
  32248. var traceVal = lib.nestedProperty(trace, traceKey).get();
  32249. if(!Array.isArray(traceVal)) return traceVal;
  32250. };
  32251. function makePtIndex2PtNumber(indexToPoints) {
  32252. var ptIndex2ptNumber = {};
  32253. for(var k in indexToPoints) {
  32254. var pts = indexToPoints[k];
  32255. for(var j = 0; j < pts.length; j++) {
  32256. ptIndex2ptNumber[pts[j]] = +k;
  32257. }
  32258. }
  32259. return ptIndex2ptNumber;
  32260. }
  32261. /** Tag selected calcdata items
  32262. *
  32263. * N.B. note that point 'index' corresponds to input data array index
  32264. * whereas 'number' is its post-transform version.
  32265. *
  32266. * @param {array} calcTrace
  32267. * @param {object} trace
  32268. * - selectedpoints {array}
  32269. * - _indexToPoints {object}
  32270. * @param {ptNumber2cdIndex} ptNumber2cdIndex (optional)
  32271. * optional map object for trace types that do not have 1-to-1 point number to
  32272. * calcdata item index correspondence (e.g. histogram)
  32273. */
  32274. lib.tagSelected = function(calcTrace, trace, ptNumber2cdIndex) {
  32275. var selectedpoints = trace.selectedpoints;
  32276. var indexToPoints = trace._indexToPoints;
  32277. var ptIndex2ptNumber;
  32278. // make pt index-to-number map object, which takes care of transformed traces
  32279. if(indexToPoints) {
  32280. ptIndex2ptNumber = makePtIndex2PtNumber(indexToPoints);
  32281. }
  32282. function isCdIndexValid(v) {
  32283. return v !== undefined && v < calcTrace.length;
  32284. }
  32285. for(var i = 0; i < selectedpoints.length; i++) {
  32286. var ptIndex = selectedpoints[i];
  32287. if(lib.isIndex(ptIndex)) {
  32288. var ptNumber = ptIndex2ptNumber ? ptIndex2ptNumber[ptIndex] : ptIndex;
  32289. var cdIndex = ptNumber2cdIndex ? ptNumber2cdIndex[ptNumber] : ptNumber;
  32290. if(isCdIndexValid(cdIndex)) {
  32291. calcTrace[cdIndex].selected = 1;
  32292. }
  32293. }
  32294. }
  32295. };
  32296. lib.selIndices2selPoints = function(trace) {
  32297. var selectedpoints = trace.selectedpoints;
  32298. var indexToPoints = trace._indexToPoints;
  32299. if(indexToPoints) {
  32300. var ptIndex2ptNumber = makePtIndex2PtNumber(indexToPoints);
  32301. var out = [];
  32302. for(var i = 0; i < selectedpoints.length; i++) {
  32303. var ptIndex = selectedpoints[i];
  32304. if(lib.isIndex(ptIndex)) {
  32305. var ptNumber = ptIndex2ptNumber[ptIndex];
  32306. if(lib.isIndex(ptNumber)) {
  32307. out.push(ptNumber);
  32308. }
  32309. }
  32310. }
  32311. return out;
  32312. } else {
  32313. return selectedpoints;
  32314. }
  32315. };
  32316. /** Returns target as set by 'target' transform attribute
  32317. *
  32318. * @param {object} trace : full trace object
  32319. * @param {object} transformOpts : transform option object
  32320. * - target (string} :
  32321. * either an attribute string referencing an array in the trace object, or
  32322. * a set array.
  32323. *
  32324. * @return {array or false} : the target array (NOT a copy!!) or false if invalid
  32325. */
  32326. lib.getTargetArray = function(trace, transformOpts) {
  32327. var target = transformOpts.target;
  32328. if(typeof target === 'string' && target) {
  32329. var array = lib.nestedProperty(trace, target).get();
  32330. return Array.isArray(array) ? array : false;
  32331. } else if(Array.isArray(target)) {
  32332. return target;
  32333. }
  32334. return false;
  32335. };
  32336. /**
  32337. * modified version of jQuery's extend to strip out private objs and functions,
  32338. * and cut arrays down to first <arraylen> or 1 elements
  32339. * because extend-like algorithms are hella slow
  32340. * obj2 is assumed to already be clean of these things (including no arrays)
  32341. */
  32342. lib.minExtend = function(obj1, obj2) {
  32343. var objOut = {};
  32344. if(typeof obj2 !== 'object') obj2 = {};
  32345. var arrayLen = 3;
  32346. var keys = Object.keys(obj1);
  32347. var i, k, v;
  32348. for(i = 0; i < keys.length; i++) {
  32349. k = keys[i];
  32350. v = obj1[k];
  32351. if(k.charAt(0) === '_' || typeof v === 'function') continue;
  32352. else if(k === 'module') objOut[k] = v;
  32353. else if(Array.isArray(v)) {
  32354. if(k === 'colorscale') {
  32355. objOut[k] = v.slice();
  32356. } else {
  32357. objOut[k] = v.slice(0, arrayLen);
  32358. }
  32359. }
  32360. else if(v && (typeof v === 'object')) objOut[k] = lib.minExtend(obj1[k], obj2[k]);
  32361. else objOut[k] = v;
  32362. }
  32363. keys = Object.keys(obj2);
  32364. for(i = 0; i < keys.length; i++) {
  32365. k = keys[i];
  32366. v = obj2[k];
  32367. if(typeof v !== 'object' || !(k in objOut) || typeof objOut[k] !== 'object') {
  32368. objOut[k] = v;
  32369. }
  32370. }
  32371. return objOut;
  32372. };
  32373. lib.titleCase = function(s) {
  32374. return s.charAt(0).toUpperCase() + s.substr(1);
  32375. };
  32376. lib.containsAny = function(s, fragments) {
  32377. for(var i = 0; i < fragments.length; i++) {
  32378. if(s.indexOf(fragments[i]) !== -1) return true;
  32379. }
  32380. return false;
  32381. };
  32382. lib.isPlotDiv = function(el) {
  32383. var el3 = d3.select(el);
  32384. return el3.node() instanceof HTMLElement &&
  32385. el3.size() &&
  32386. el3.classed('js-plotly-plot');
  32387. };
  32388. lib.removeElement = function(el) {
  32389. var elParent = el && el.parentNode;
  32390. if(elParent) elParent.removeChild(el);
  32391. };
  32392. /**
  32393. * for dynamically adding style rules
  32394. * makes one stylesheet that contains all rules added
  32395. * by all calls to this function
  32396. */
  32397. lib.addStyleRule = function(selector, styleString) {
  32398. lib.addRelatedStyleRule('global', selector, styleString);
  32399. };
  32400. /**
  32401. * for dynamically adding style rules
  32402. * to a stylesheet uniquely identified by a uid
  32403. */
  32404. lib.addRelatedStyleRule = function(uid, selector, styleString) {
  32405. var id = 'plotly.js-style-' + uid;
  32406. var style = document.getElementById(id);
  32407. if(!style) {
  32408. style = document.createElement('style');
  32409. style.setAttribute('id', id);
  32410. // WebKit hack :(
  32411. style.appendChild(document.createTextNode(''));
  32412. document.head.appendChild(style);
  32413. }
  32414. var styleSheet = style.sheet;
  32415. if(styleSheet.insertRule) {
  32416. styleSheet.insertRule(selector + '{' + styleString + '}', 0);
  32417. }
  32418. else if(styleSheet.addRule) {
  32419. styleSheet.addRule(selector, styleString, 0);
  32420. }
  32421. else lib.warn('addStyleRule failed');
  32422. };
  32423. /**
  32424. * to remove from the page a stylesheet identified by a given uid
  32425. */
  32426. lib.deleteRelatedStyleRule = function(uid) {
  32427. var id = 'plotly.js-style-' + uid;
  32428. var style = document.getElementById(id);
  32429. if(style) lib.removeElement(style);
  32430. };
  32431. lib.isIE = function() {
  32432. return typeof window.navigator.msSaveBlob !== 'undefined';
  32433. };
  32434. /**
  32435. * Duck typing to recognize a d3 selection, mostly for IE9's benefit
  32436. * because it doesn't handle instanceof like modern browsers
  32437. */
  32438. lib.isD3Selection = function(obj) {
  32439. return obj && (typeof obj.classed === 'function');
  32440. };
  32441. /**
  32442. * Append element to DOM only if not present.
  32443. *
  32444. * @param {d3 selection} parent : parent selection of the element in question
  32445. * @param {string} nodeType : node type of element to append
  32446. * @param {string} className (optional) : class name of element in question
  32447. * @param {fn} enterFn (optional) : optional fn applied to entering elements only
  32448. * @return {d3 selection} selection of new layer
  32449. *
  32450. * Previously, we were using the following pattern:
  32451. *
  32452. * ```
  32453. * var sel = parent.selectAll('.' + className)
  32454. * .data([0]);
  32455. *
  32456. * sel.enter().append(nodeType)
  32457. * .classed(className, true);
  32458. *
  32459. * return sel;
  32460. * ```
  32461. *
  32462. * in numerous places in our codebase to achieve the same behavior.
  32463. *
  32464. * The logic below performs much better, mostly as we are using
  32465. * `.select` instead `.selectAll` that is `querySelector` instead of
  32466. * `querySelectorAll`.
  32467. *
  32468. */
  32469. lib.ensureSingle = function(parent, nodeType, className, enterFn) {
  32470. var sel = parent.select(nodeType + (className ? '.' + className : ''));
  32471. if(sel.size()) return sel;
  32472. var layer = parent.append(nodeType);
  32473. if(className) layer.classed(className, true);
  32474. if(enterFn) layer.call(enterFn);
  32475. return layer;
  32476. };
  32477. /**
  32478. * Same as Lib.ensureSingle, but using id as selector.
  32479. * This version is mostly used for clipPath nodes.
  32480. *
  32481. * @param {d3 selection} parent : parent selection of the element in question
  32482. * @param {string} nodeType : node type of element to append
  32483. * @param {string} id : id of element in question
  32484. * @param {fn} enterFn (optional) : optional fn applied to entering elements only
  32485. * @return {d3 selection} selection of new layer
  32486. */
  32487. lib.ensureSingleById = function(parent, nodeType, id, enterFn) {
  32488. var sel = parent.select(nodeType + '#' + id);
  32489. if(sel.size()) return sel;
  32490. var layer = parent.append(nodeType).attr('id', id);
  32491. if(enterFn) layer.call(enterFn);
  32492. return layer;
  32493. };
  32494. /**
  32495. * Converts a string path to an object.
  32496. *
  32497. * When given a string containing an array element, it will create a `null`
  32498. * filled array of the given size.
  32499. *
  32500. * @example
  32501. * lib.objectFromPath('nested.test[2].path', 'value');
  32502. * // returns { nested: { test: [null, null, { path: 'value' }]}
  32503. *
  32504. * @param {string} path to nested value
  32505. * @param {*} any value to be set
  32506. *
  32507. * @return {Object} the constructed object with a full nested path
  32508. */
  32509. lib.objectFromPath = function(path, value) {
  32510. var keys = path.split('.');
  32511. var tmpObj;
  32512. var obj = tmpObj = {};
  32513. for(var i = 0; i < keys.length; i++) {
  32514. var key = keys[i];
  32515. var el = null;
  32516. var parts = keys[i].match(/(.*)\[([0-9]+)\]/);
  32517. if(parts) {
  32518. key = parts[1];
  32519. el = parts[2];
  32520. tmpObj = tmpObj[key] = [];
  32521. if(i === keys.length - 1) {
  32522. tmpObj[el] = value;
  32523. } else {
  32524. tmpObj[el] = {};
  32525. }
  32526. tmpObj = tmpObj[el];
  32527. } else {
  32528. if(i === keys.length - 1) {
  32529. tmpObj[key] = value;
  32530. } else {
  32531. tmpObj[key] = {};
  32532. }
  32533. tmpObj = tmpObj[key];
  32534. }
  32535. }
  32536. return obj;
  32537. };
  32538. /**
  32539. * Iterate through an object in-place, converting dotted properties to objects.
  32540. *
  32541. * Examples:
  32542. *
  32543. * lib.expandObjectPaths({'nested.test.path': 'value'});
  32544. * => { nested: { test: {path: 'value'}}}
  32545. *
  32546. * It also handles array notation, e.g.:
  32547. *
  32548. * lib.expandObjectPaths({'foo[1].bar': 'value'});
  32549. * => { foo: [null, {bar: value}] }
  32550. *
  32551. * It handles merges the results when two properties are specified in parallel:
  32552. *
  32553. * lib.expandObjectPaths({'foo[1].bar': 10, 'foo[0].bar': 20});
  32554. * => { foo: [{bar: 10}, {bar: 20}] }
  32555. *
  32556. * It does NOT, however, merge mulitple mutliply-nested arrays::
  32557. *
  32558. * lib.expandObjectPaths({'marker[1].range[1]': 5, 'marker[1].range[0]': 4})
  32559. * => { marker: [null, {range: 4}] }
  32560. */
  32561. // Store this to avoid recompiling regex on *every* prop since this may happen many
  32562. // many times for animations. Could maybe be inside the function. Not sure about
  32563. // scoping vs. recompilation tradeoff, but at least it's not just inlining it into
  32564. // the inner loop.
  32565. var dottedPropertyRegex = /^([^\[\.]+)\.(.+)?/;
  32566. var indexedPropertyRegex = /^([^\.]+)\[([0-9]+)\](\.)?(.+)?/;
  32567. lib.expandObjectPaths = function(data) {
  32568. var match, key, prop, datum, idx, dest, trailingPath;
  32569. if(typeof data === 'object' && !Array.isArray(data)) {
  32570. for(key in data) {
  32571. if(data.hasOwnProperty(key)) {
  32572. if((match = key.match(dottedPropertyRegex))) {
  32573. datum = data[key];
  32574. prop = match[1];
  32575. delete data[key];
  32576. data[prop] = lib.extendDeepNoArrays(data[prop] || {}, lib.objectFromPath(key, lib.expandObjectPaths(datum))[prop]);
  32577. } else if((match = key.match(indexedPropertyRegex))) {
  32578. datum = data[key];
  32579. prop = match[1];
  32580. idx = parseInt(match[2]);
  32581. delete data[key];
  32582. data[prop] = data[prop] || [];
  32583. if(match[3] === '.') {
  32584. // This is the case where theere are subsequent properties into which
  32585. // we must recurse, e.g. transforms[0].value
  32586. trailingPath = match[4];
  32587. dest = data[prop][idx] = data[prop][idx] || {};
  32588. // NB: Extend deep no arrays prevents this from working on multiple
  32589. // nested properties in the same object, e.g.
  32590. //
  32591. // {
  32592. // foo[0].bar[1].range
  32593. // foo[0].bar[0].range
  32594. // }
  32595. //
  32596. // In this case, the extendDeepNoArrays will overwrite one array with
  32597. // the other, so that both properties *will not* be present in the
  32598. // result. Fixing this would require a more intelligent tracking
  32599. // of changes and merging than extendDeepNoArrays currently accomplishes.
  32600. lib.extendDeepNoArrays(dest, lib.objectFromPath(trailingPath, lib.expandObjectPaths(datum)));
  32601. } else {
  32602. // This is the case where this property is the end of the line,
  32603. // e.g. xaxis.range[0]
  32604. data[prop][idx] = lib.expandObjectPaths(datum);
  32605. }
  32606. } else {
  32607. data[key] = lib.expandObjectPaths(data[key]);
  32608. }
  32609. }
  32610. }
  32611. }
  32612. return data;
  32613. };
  32614. /**
  32615. * Converts value to string separated by the provided separators.
  32616. *
  32617. * @example
  32618. * lib.numSeparate(2016, '.,');
  32619. * // returns '2016'
  32620. *
  32621. * @example
  32622. * lib.numSeparate(3000, '.,', true);
  32623. * // returns '3,000'
  32624. *
  32625. * @example
  32626. * lib.numSeparate(1234.56, '|,')
  32627. * // returns '1,234|56'
  32628. *
  32629. * @param {string|number} value the value to be converted
  32630. * @param {string} separators string of decimal, then thousands separators
  32631. * @param {boolean} separatethousands boolean, 4-digit integers are separated if true
  32632. *
  32633. * @return {string} the value that has been separated
  32634. */
  32635. lib.numSeparate = function(value, separators, separatethousands) {
  32636. if(!separatethousands) separatethousands = false;
  32637. if(typeof separators !== 'string' || separators.length === 0) {
  32638. throw new Error('Separator string required for formatting!');
  32639. }
  32640. if(typeof value === 'number') {
  32641. value = String(value);
  32642. }
  32643. var thousandsRe = /(\d+)(\d{3})/;
  32644. var decimalSep = separators.charAt(0);
  32645. var thouSep = separators.charAt(1);
  32646. var x = value.split('.');
  32647. var x1 = x[0];
  32648. var x2 = x.length > 1 ? decimalSep + x[1] : '';
  32649. // Years are ignored for thousands separators
  32650. if(thouSep && (x.length > 1 || x1.length > 4 || separatethousands)) {
  32651. while(thousandsRe.test(x1)) {
  32652. x1 = x1.replace(thousandsRe, '$1' + thouSep + '$2');
  32653. }
  32654. }
  32655. return x1 + x2;
  32656. };
  32657. var TEMPLATE_STRING_REGEX = /%{([^\s%{}:]*)(:[^}]*)?}/g;
  32658. var SIMPLE_PROPERTY_REGEX = /^\w*$/;
  32659. /**
  32660. * Substitute values from an object into a string
  32661. *
  32662. * Examples:
  32663. * Lib.templateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
  32664. * Lib.templateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
  32665. *
  32666. * @param {string} input string containing %{...} template strings
  32667. * @param {obj} data object containing substitution values
  32668. *
  32669. * @return {string} templated string
  32670. */
  32671. lib.templateString = function(string, obj) {
  32672. // Not all that useful, but cache nestedProperty instantiation
  32673. // just in case it speeds things up *slightly*:
  32674. var getterCache = {};
  32675. return string.replace(TEMPLATE_STRING_REGEX, function(dummy, key) {
  32676. if(SIMPLE_PROPERTY_REGEX.test(key)) {
  32677. return obj[key] || '';
  32678. }
  32679. getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get;
  32680. return getterCache[key]() || '';
  32681. });
  32682. };
  32683. var TEMPLATE_STRING_FORMAT_SEPARATOR = /^:/;
  32684. var numberOfHoverTemplateWarnings = 0;
  32685. var maximumNumberOfHoverTemplateWarnings = 10;
  32686. /**
  32687. * Substitute values from an object into a string and optionally formats them using d3-format,
  32688. * or fallback to associated labels.
  32689. *
  32690. * Examples:
  32691. * Lib.templateString('name: %{trace}', {trace: 'asdf'}) --> 'name: asdf'
  32692. * Lib.templateString('name: %{trace[0].name}', {trace: [{name: 'asdf'}]}) --> 'name: asdf'
  32693. * Lib.templateString('price: %{y:$.2f}', {y: 1}) --> 'price: $1.00'
  32694. *
  32695. * @param {string} input string containing %{...:...} template strings
  32696. * @param {obj} data object containing fallback text when no formatting is specified, ex.: {yLabel: 'formattedYValue'}
  32697. * @param {obj} data objects containing substitution values
  32698. *
  32699. * @return {string} templated string
  32700. */
  32701. lib.hovertemplateString = function(string, labels) {
  32702. var args = arguments;
  32703. // Not all that useful, but cache nestedProperty instantiation
  32704. // just in case it speeds things up *slightly*:
  32705. var getterCache = {};
  32706. return string.replace(TEMPLATE_STRING_REGEX, function(match, key, format) {
  32707. var obj, value, i;
  32708. for(i = 2; i < args.length; i++) {
  32709. obj = args[i];
  32710. if(obj.hasOwnProperty(key)) {
  32711. value = obj[key];
  32712. break;
  32713. }
  32714. if(!SIMPLE_PROPERTY_REGEX.test(key)) {
  32715. value = getterCache[key] || lib.nestedProperty(obj, key).get();
  32716. if(value) getterCache[key] = value;
  32717. }
  32718. if(value !== undefined) break;
  32719. }
  32720. if(value === undefined) {
  32721. if(numberOfHoverTemplateWarnings < maximumNumberOfHoverTemplateWarnings) {
  32722. lib.warn('Variable \'' + key + '\' in hovertemplate could not be found!');
  32723. value = match;
  32724. }
  32725. if(numberOfHoverTemplateWarnings === maximumNumberOfHoverTemplateWarnings) {
  32726. lib.warn('Too many hovertemplate warnings - additional warnings will be suppressed');
  32727. }
  32728. numberOfHoverTemplateWarnings++;
  32729. }
  32730. if(format) {
  32731. value = d3.format(format.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ''))(value);
  32732. } else {
  32733. if(labels.hasOwnProperty(key + 'Label')) value = labels[key + 'Label'];
  32734. }
  32735. return value;
  32736. });
  32737. };
  32738. /*
  32739. * alphanumeric string sort, tailored for subplot IDs like scene2, scene10, x10y13 etc
  32740. */
  32741. var char0 = 48;
  32742. var char9 = 57;
  32743. lib.subplotSort = function(a, b) {
  32744. var l = Math.min(a.length, b.length) + 1;
  32745. var numA = 0;
  32746. var numB = 0;
  32747. for(var i = 0; i < l; i++) {
  32748. var charA = a.charCodeAt(i) || 0;
  32749. var charB = b.charCodeAt(i) || 0;
  32750. var isNumA = charA >= char0 && charA <= char9;
  32751. var isNumB = charB >= char0 && charB <= char9;
  32752. if(isNumA) numA = 10 * numA + charA - char0;
  32753. if(isNumB) numB = 10 * numB + charB - char0;
  32754. if(!isNumA || !isNumB) {
  32755. if(numA !== numB) return numA - numB;
  32756. if(charA !== charB) return charA - charB;
  32757. }
  32758. }
  32759. return numB - numA;
  32760. };
  32761. // repeatable pseudorandom generator
  32762. var randSeed = 2000000000;
  32763. lib.seedPseudoRandom = function() {
  32764. randSeed = 2000000000;
  32765. };
  32766. lib.pseudoRandom = function() {
  32767. var lastVal = randSeed;
  32768. randSeed = (69069 * randSeed + 1) % 4294967296;
  32769. // don't let consecutive vals be too close together
  32770. // gets away from really trying to be random, in favor of better local uniformity
  32771. if(Math.abs(randSeed - lastVal) < 429496729) return lib.pseudoRandom();
  32772. return randSeed / 4294967296;
  32773. };
  32774. },{"../constants/numerical":149,"./anchor_utils":153,"./angles":154,"./array":155,"./clean_number":156,"./clear_responsive":158,"./coerce":159,"./dates":160,"./extend":162,"./filter_unique":163,"./filter_visible":164,"./geometry2d":165,"./get_graph_div":166,"./identity":167,"./is_plain_object":169,"./keyed_container":170,"./localize":171,"./loggers":172,"./make_trace_groups":173,"./matrix":174,"./mod":175,"./nested_property":176,"./noop":177,"./notifier":178,"./push_unique":181,"./regex":183,"./relative_attr":184,"./relink_private":185,"./search":186,"./stats":188,"./throttle":190,"./to_log_range":191,"d3":16,"fast-isnumeric":18}],169:[function(_dereq_,module,exports){
  32775. /**
  32776. * Copyright 2012-2019, Plotly, Inc.
  32777. * All rights reserved.
  32778. *
  32779. * This source code is licensed under the MIT license found in the
  32780. * LICENSE file in the root directory of this source tree.
  32781. */
  32782. 'use strict';
  32783. // more info: http://stackoverflow.com/questions/18531624/isplainobject-thing
  32784. module.exports = function isPlainObject(obj) {
  32785. // We need to be a little less strict in the `imagetest` container because
  32786. // of how async image requests are handled.
  32787. //
  32788. // N.B. isPlainObject(new Constructor()) will return true in `imagetest`
  32789. if(window && window.process && window.process.versions) {
  32790. return Object.prototype.toString.call(obj) === '[object Object]';
  32791. }
  32792. return (
  32793. Object.prototype.toString.call(obj) === '[object Object]' &&
  32794. Object.getPrototypeOf(obj) === Object.prototype
  32795. );
  32796. };
  32797. },{}],170:[function(_dereq_,module,exports){
  32798. /**
  32799. * Copyright 2012-2019, Plotly, Inc.
  32800. * All rights reserved.
  32801. *
  32802. * This source code is licensed under the MIT license found in the
  32803. * LICENSE file in the root directory of this source tree.
  32804. */
  32805. 'use strict';
  32806. var nestedProperty = _dereq_('./nested_property');
  32807. var SIMPLE_PROPERTY_REGEX = /^\w*$/;
  32808. // bitmask for deciding what's updated. Sometimes the name needs to be updated,
  32809. // sometimes the value needs to be updated, and sometimes both do. This is just
  32810. // a simple way to track what's updated such that it's a simple OR operation to
  32811. // assimilate new updates.
  32812. //
  32813. // The only exception is the UNSET bit that tracks when we need to explicitly
  32814. // unset and remove the property. This concrn arises because of the special
  32815. // way in which nestedProperty handles null/undefined. When you specify `null`,
  32816. // it prunes any unused items in the tree. I ran into some issues with it getting
  32817. // null vs undefined confused, so UNSET is just a bit that forces the property
  32818. // update to send `null`, removing the property explicitly rather than setting
  32819. // it to undefined.
  32820. var NONE = 0;
  32821. var NAME = 1;
  32822. var VALUE = 2;
  32823. var BOTH = 3;
  32824. var UNSET = 4;
  32825. module.exports = function keyedContainer(baseObj, path, keyName, valueName) {
  32826. keyName = keyName || 'name';
  32827. valueName = valueName || 'value';
  32828. var i, arr, baseProp;
  32829. var changeTypes = {};
  32830. if(path && path.length) {
  32831. baseProp = nestedProperty(baseObj, path);
  32832. arr = baseProp.get();
  32833. } else {
  32834. arr = baseObj;
  32835. }
  32836. path = path || '';
  32837. // Construct an index:
  32838. var indexLookup = {};
  32839. if(arr) {
  32840. for(i = 0; i < arr.length; i++) {
  32841. indexLookup[arr[i][keyName]] = i;
  32842. }
  32843. }
  32844. var isSimpleValueProp = SIMPLE_PROPERTY_REGEX.test(valueName);
  32845. var obj = {
  32846. set: function(name, value) {
  32847. var changeType = value === null ? UNSET : NONE;
  32848. // create the base array if necessary
  32849. if(!arr) {
  32850. if(!baseProp || changeType === UNSET) return;
  32851. arr = [];
  32852. baseProp.set(arr);
  32853. }
  32854. var idx = indexLookup[name];
  32855. if(idx === undefined) {
  32856. if(changeType === UNSET) return;
  32857. changeType = changeType | BOTH;
  32858. idx = arr.length;
  32859. indexLookup[name] = idx;
  32860. } else if(value !== (isSimpleValueProp ? arr[idx][valueName] : nestedProperty(arr[idx], valueName).get())) {
  32861. changeType = changeType | VALUE;
  32862. }
  32863. var newValue = arr[idx] = arr[idx] || {};
  32864. newValue[keyName] = name;
  32865. if(isSimpleValueProp) {
  32866. newValue[valueName] = value;
  32867. } else {
  32868. nestedProperty(newValue, valueName).set(value);
  32869. }
  32870. // If it's not an unset, force that bit to be unset. This is all related to the fact
  32871. // that undefined and null are a bit specially implemented in nestedProperties.
  32872. if(value !== null) {
  32873. changeType = changeType & ~UNSET;
  32874. }
  32875. changeTypes[idx] = changeTypes[idx] | changeType;
  32876. return obj;
  32877. },
  32878. get: function(name) {
  32879. if(!arr) return;
  32880. var idx = indexLookup[name];
  32881. if(idx === undefined) {
  32882. return undefined;
  32883. } else if(isSimpleValueProp) {
  32884. return arr[idx][valueName];
  32885. } else {
  32886. return nestedProperty(arr[idx], valueName).get();
  32887. }
  32888. },
  32889. rename: function(name, newName) {
  32890. var idx = indexLookup[name];
  32891. if(idx === undefined) return obj;
  32892. changeTypes[idx] = changeTypes[idx] | NAME;
  32893. indexLookup[newName] = idx;
  32894. delete indexLookup[name];
  32895. arr[idx][keyName] = newName;
  32896. return obj;
  32897. },
  32898. remove: function(name) {
  32899. var idx = indexLookup[name];
  32900. if(idx === undefined) return obj;
  32901. var object = arr[idx];
  32902. if(Object.keys(object).length > 2) {
  32903. // This object contains more than just the key/value, so unset
  32904. // the value without modifying the entry otherwise:
  32905. changeTypes[idx] = changeTypes[idx] | VALUE;
  32906. return obj.set(name, null);
  32907. }
  32908. if(isSimpleValueProp) {
  32909. for(i = idx; i < arr.length; i++) {
  32910. changeTypes[i] = changeTypes[i] | BOTH;
  32911. }
  32912. for(i = idx; i < arr.length; i++) {
  32913. indexLookup[arr[i][keyName]]--;
  32914. }
  32915. arr.splice(idx, 1);
  32916. delete(indexLookup[name]);
  32917. } else {
  32918. // Perform this update *strictly* so we can check whether the result's
  32919. // been pruned. If so, it's a removal. If not, it's a value unset only.
  32920. nestedProperty(object, valueName).set(null);
  32921. // Now check if the top level nested property has any keys left. If so,
  32922. // the object still has values so we only want to unset the key. If not,
  32923. // the entire object can be removed since there's no other data.
  32924. // var topLevelKeys = Object.keys(object[valueName.split('.')[0]] || []);
  32925. changeTypes[idx] = changeTypes[idx] | VALUE | UNSET;
  32926. }
  32927. return obj;
  32928. },
  32929. constructUpdate: function() {
  32930. var astr, idx;
  32931. var update = {};
  32932. var changed = Object.keys(changeTypes);
  32933. for(var i = 0; i < changed.length; i++) {
  32934. idx = changed[i];
  32935. astr = path + '[' + idx + ']';
  32936. if(arr[idx]) {
  32937. if(changeTypes[idx] & NAME) {
  32938. update[astr + '.' + keyName] = arr[idx][keyName];
  32939. }
  32940. if(changeTypes[idx] & VALUE) {
  32941. if(isSimpleValueProp) {
  32942. update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : arr[idx][valueName];
  32943. } else {
  32944. update[astr + '.' + valueName] = (changeTypes[idx] & UNSET) ? null : nestedProperty(arr[idx], valueName).get();
  32945. }
  32946. }
  32947. } else {
  32948. update[astr] = null;
  32949. }
  32950. }
  32951. return update;
  32952. }
  32953. };
  32954. return obj;
  32955. };
  32956. },{"./nested_property":176}],171:[function(_dereq_,module,exports){
  32957. /**
  32958. * Copyright 2012-2019, Plotly, Inc.
  32959. * All rights reserved.
  32960. *
  32961. * This source code is licensed under the MIT license found in the
  32962. * LICENSE file in the root directory of this source tree.
  32963. */
  32964. 'use strict';
  32965. var Registry = _dereq_('../registry');
  32966. /**
  32967. * localize: translate a string for the current locale
  32968. *
  32969. * @param {object} gd: the graphDiv for context
  32970. * gd._context.locale determines the language (& optional region/country)
  32971. * the dictionary for each locale may either be supplied in
  32972. * gd._context.locales or globally via Plotly.register
  32973. * @param {string} s: the string to translate
  32974. */
  32975. module.exports = function localize(gd, s) {
  32976. var locale = gd._context.locale;
  32977. /*
  32978. * Priority of lookup:
  32979. * contextDicts[locale],
  32980. * registeredDicts[locale],
  32981. * contextDicts[baseLocale], (if baseLocale is distinct)
  32982. * registeredDicts[baseLocale]
  32983. * Return the first translation we find.
  32984. * This way if you have a regionalization you are allowed to specify
  32985. * only what's different from the base locale, everything else will
  32986. * fall back on the base.
  32987. */
  32988. for(var i = 0; i < 2; i++) {
  32989. var locales = gd._context.locales;
  32990. for(var j = 0; j < 2; j++) {
  32991. var dict = (locales[locale] || {}).dictionary;
  32992. if(dict) {
  32993. var out = dict[s];
  32994. if(out) return out;
  32995. }
  32996. locales = Registry.localeRegistry;
  32997. }
  32998. var baseLocale = locale.split('-')[0];
  32999. if(baseLocale === locale) break;
  33000. locale = baseLocale;
  33001. }
  33002. return s;
  33003. };
  33004. },{"../registry":257}],172:[function(_dereq_,module,exports){
  33005. /**
  33006. * Copyright 2012-2019, Plotly, Inc.
  33007. * All rights reserved.
  33008. *
  33009. * This source code is licensed under the MIT license found in the
  33010. * LICENSE file in the root directory of this source tree.
  33011. */
  33012. 'use strict';
  33013. /* eslint-disable no-console */
  33014. var dfltConfig = _dereq_('../plot_api/plot_config').dfltConfig;
  33015. var loggers = module.exports = {};
  33016. /**
  33017. * ------------------------------------------
  33018. * debugging tools
  33019. * ------------------------------------------
  33020. */
  33021. loggers.log = function() {
  33022. if(dfltConfig.logging > 1) {
  33023. var messages = ['LOG:'];
  33024. for(var i = 0; i < arguments.length; i++) {
  33025. messages.push(arguments[i]);
  33026. }
  33027. apply(console.trace || console.log, messages);
  33028. }
  33029. };
  33030. loggers.warn = function() {
  33031. if(dfltConfig.logging > 0) {
  33032. var messages = ['WARN:'];
  33033. for(var i = 0; i < arguments.length; i++) {
  33034. messages.push(arguments[i]);
  33035. }
  33036. apply(console.trace || console.log, messages);
  33037. }
  33038. };
  33039. loggers.error = function() {
  33040. if(dfltConfig.logging > 0) {
  33041. var messages = ['ERROR:'];
  33042. for(var i = 0; i < arguments.length; i++) {
  33043. messages.push(arguments[i]);
  33044. }
  33045. apply(console.error, messages);
  33046. }
  33047. };
  33048. /*
  33049. * Robust apply, for IE9 where console.log doesn't support
  33050. * apply like other functions do
  33051. */
  33052. function apply(f, args) {
  33053. if(f && f.apply) {
  33054. try {
  33055. // `this` should always be console, since here we're always
  33056. // applying a method of the console object.
  33057. f.apply(console, args);
  33058. return;
  33059. }
  33060. catch(e) { /* in case apply failed, fall back on the code below */ }
  33061. }
  33062. // no apply - just try calling the function on each arg independently
  33063. for(var i = 0; i < args.length; i++) {
  33064. try {
  33065. f(args[i]);
  33066. }
  33067. catch(e) {
  33068. // still fails - last resort simple console.log
  33069. console.log(args[i]);
  33070. }
  33071. }
  33072. }
  33073. },{"../plot_api/plot_config":200}],173:[function(_dereq_,module,exports){
  33074. /**
  33075. * Copyright 2012-2019, Plotly, Inc.
  33076. * All rights reserved.
  33077. *
  33078. * This source code is licensed under the MIT license found in the
  33079. * LICENSE file in the root directory of this source tree.
  33080. */
  33081. 'use strict';
  33082. /**
  33083. * General helper to manage trace groups based on calcdata
  33084. *
  33085. * @param {d3.selection} traceLayer: a selection containing a single group
  33086. * to draw these traces into
  33087. * @param {array} cdModule: array of calcdata items for this
  33088. * module and subplot combination. Assumes the calcdata item for each
  33089. * trace is an array with the fullData trace attached to the first item.
  33090. * @param {string} cls: the class attribute to give each trace group
  33091. * so you can give multiple classes separated by spaces
  33092. */
  33093. module.exports = function makeTraceGroups(traceLayer, cdModule, cls) {
  33094. var traces = traceLayer.selectAll('g.' + cls.replace(/\s/g, '.'))
  33095. .data(cdModule, function(cd) { return cd[0].trace.uid; });
  33096. traces.exit().remove();
  33097. traces.enter().append('g')
  33098. .attr('class', cls);
  33099. traces.order();
  33100. return traces;
  33101. };
  33102. },{}],174:[function(_dereq_,module,exports){
  33103. /**
  33104. * Copyright 2012-2019, Plotly, Inc.
  33105. * All rights reserved.
  33106. *
  33107. * This source code is licensed under the MIT license found in the
  33108. * LICENSE file in the root directory of this source tree.
  33109. */
  33110. 'use strict';
  33111. exports.init2dArray = function(rowLength, colLength) {
  33112. var array = new Array(rowLength);
  33113. for(var i = 0; i < rowLength; i++) array[i] = new Array(colLength);
  33114. return array;
  33115. };
  33116. /**
  33117. * transpose a (possibly ragged) 2d array z. inspired by
  33118. * http://stackoverflow.com/questions/17428587/
  33119. * transposing-a-2d-array-in-javascript
  33120. */
  33121. exports.transposeRagged = function(z) {
  33122. var maxlen = 0;
  33123. var zlen = z.length;
  33124. var i, j;
  33125. // Maximum row length:
  33126. for(i = 0; i < zlen; i++) maxlen = Math.max(maxlen, z[i].length);
  33127. var t = new Array(maxlen);
  33128. for(i = 0; i < maxlen; i++) {
  33129. t[i] = new Array(zlen);
  33130. for(j = 0; j < zlen; j++) t[i][j] = z[j][i];
  33131. }
  33132. return t;
  33133. };
  33134. // our own dot function so that we don't need to include numeric
  33135. exports.dot = function(x, y) {
  33136. if(!(x.length && y.length) || x.length !== y.length) return null;
  33137. var len = x.length;
  33138. var out;
  33139. var i;
  33140. if(x[0].length) {
  33141. // mat-vec or mat-mat
  33142. out = new Array(len);
  33143. for(i = 0; i < len; i++) out[i] = exports.dot(x[i], y);
  33144. }
  33145. else if(y[0].length) {
  33146. // vec-mat
  33147. var yTranspose = exports.transposeRagged(y);
  33148. out = new Array(yTranspose.length);
  33149. for(i = 0; i < yTranspose.length; i++) out[i] = exports.dot(x, yTranspose[i]);
  33150. }
  33151. else {
  33152. // vec-vec
  33153. out = 0;
  33154. for(i = 0; i < len; i++) out += x[i] * y[i];
  33155. }
  33156. return out;
  33157. };
  33158. // translate by (x,y)
  33159. exports.translationMatrix = function(x, y) {
  33160. return [[1, 0, x], [0, 1, y], [0, 0, 1]];
  33161. };
  33162. // rotate by alpha around (0,0)
  33163. exports.rotationMatrix = function(alpha) {
  33164. var a = alpha * Math.PI / 180;
  33165. return [[Math.cos(a), -Math.sin(a), 0],
  33166. [Math.sin(a), Math.cos(a), 0],
  33167. [0, 0, 1]];
  33168. };
  33169. // rotate by alpha around (x,y)
  33170. exports.rotationXYMatrix = function(a, x, y) {
  33171. return exports.dot(
  33172. exports.dot(exports.translationMatrix(x, y),
  33173. exports.rotationMatrix(a)),
  33174. exports.translationMatrix(-x, -y));
  33175. };
  33176. // applies a 2D transformation matrix to either x and y params or an [x,y] array
  33177. exports.apply2DTransform = function(transform) {
  33178. return function() {
  33179. var args = arguments;
  33180. if(args.length === 3) {
  33181. args = args[0];
  33182. }// from map
  33183. var xy = arguments.length === 1 ? args[0] : [args[0], args[1]];
  33184. return exports.dot(transform, [xy[0], xy[1], 1]).slice(0, 2);
  33185. };
  33186. };
  33187. // applies a 2D transformation matrix to an [x1,y1,x2,y2] array (to transform a segment)
  33188. exports.apply2DTransform2 = function(transform) {
  33189. var at = exports.apply2DTransform(transform);
  33190. return function(xys) {
  33191. return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4)));
  33192. };
  33193. };
  33194. },{}],175:[function(_dereq_,module,exports){
  33195. /**
  33196. * Copyright 2012-2019, Plotly, Inc.
  33197. * All rights reserved.
  33198. *
  33199. * This source code is licensed under the MIT license found in the
  33200. * LICENSE file in the root directory of this source tree.
  33201. */
  33202. 'use strict';
  33203. /**
  33204. * sanitized modulus function that always returns in the range [0, d)
  33205. * rather than (-d, 0] if v is negative
  33206. */
  33207. function mod(v, d) {
  33208. var out = v % d;
  33209. return out < 0 ? out + d : out;
  33210. }
  33211. /**
  33212. * sanitized modulus function that always returns in the range [-d/2, d/2]
  33213. * rather than (-d, 0] if v is negative
  33214. */
  33215. function modHalf(v, d) {
  33216. return Math.abs(v) > (d / 2) ?
  33217. v - Math.round(v / d) * d :
  33218. v;
  33219. }
  33220. module.exports = {
  33221. mod: mod,
  33222. modHalf: modHalf
  33223. };
  33224. },{}],176:[function(_dereq_,module,exports){
  33225. /**
  33226. * Copyright 2012-2019, Plotly, Inc.
  33227. * All rights reserved.
  33228. *
  33229. * This source code is licensed under the MIT license found in the
  33230. * LICENSE file in the root directory of this source tree.
  33231. */
  33232. 'use strict';
  33233. var isNumeric = _dereq_('fast-isnumeric');
  33234. var isArrayOrTypedArray = _dereq_('./array').isArrayOrTypedArray;
  33235. /**
  33236. * convert a string s (such as 'xaxis.range[0]')
  33237. * representing a property of nested object into set and get methods
  33238. * also return the string and object so we don't have to keep track of them
  33239. * allows [-1] for an array index, to set a property inside all elements
  33240. * of an array
  33241. * eg if obj = {arr: [{a: 1}, {a: 2}]}
  33242. * you can do p = nestedProperty(obj, 'arr[-1].a')
  33243. * but you cannot set the array itself this way, to do that
  33244. * just set the whole array.
  33245. * eg if obj = {arr: [1, 2, 3]}
  33246. * you can't do nestedProperty(obj, 'arr[-1]').set(5)
  33247. * but you can do nestedProperty(obj, 'arr').set([5, 5, 5])
  33248. */
  33249. module.exports = function nestedProperty(container, propStr) {
  33250. if(isNumeric(propStr)) propStr = String(propStr);
  33251. else if(typeof propStr !== 'string' ||
  33252. propStr.substr(propStr.length - 4) === '[-1]') {
  33253. throw 'bad property string';
  33254. }
  33255. var j = 0;
  33256. var propParts = propStr.split('.');
  33257. var indexed;
  33258. var indices;
  33259. var i;
  33260. // check for parts of the nesting hierarchy that are numbers (ie array elements)
  33261. while(j < propParts.length) {
  33262. // look for non-bracket chars, then any number of [##] blocks
  33263. indexed = String(propParts[j]).match(/^([^\[\]]*)((\[\-?[0-9]*\])+)$/);
  33264. if(indexed) {
  33265. if(indexed[1]) propParts[j] = indexed[1];
  33266. // allow propStr to start with bracketed array indices
  33267. else if(j === 0) propParts.splice(0, 1);
  33268. else throw 'bad property string';
  33269. indices = indexed[2]
  33270. .substr(1, indexed[2].length - 2)
  33271. .split('][');
  33272. for(i = 0; i < indices.length; i++) {
  33273. j++;
  33274. propParts.splice(j, 0, Number(indices[i]));
  33275. }
  33276. }
  33277. j++;
  33278. }
  33279. if(typeof container !== 'object') {
  33280. return badContainer(container, propStr, propParts);
  33281. }
  33282. return {
  33283. set: npSet(container, propParts, propStr),
  33284. get: npGet(container, propParts),
  33285. astr: propStr,
  33286. parts: propParts,
  33287. obj: container
  33288. };
  33289. };
  33290. function npGet(cont, parts) {
  33291. return function() {
  33292. var curCont = cont;
  33293. var curPart;
  33294. var allSame;
  33295. var out;
  33296. var i;
  33297. var j;
  33298. for(i = 0; i < parts.length - 1; i++) {
  33299. curPart = parts[i];
  33300. if(curPart === -1) {
  33301. allSame = true;
  33302. out = [];
  33303. for(j = 0; j < curCont.length; j++) {
  33304. out[j] = npGet(curCont[j], parts.slice(i + 1))();
  33305. if(out[j] !== out[0]) allSame = false;
  33306. }
  33307. return allSame ? out[0] : out;
  33308. }
  33309. if(typeof curPart === 'number' && !isArrayOrTypedArray(curCont)) {
  33310. return undefined;
  33311. }
  33312. curCont = curCont[curPart];
  33313. if(typeof curCont !== 'object' || curCont === null) {
  33314. return undefined;
  33315. }
  33316. }
  33317. // only hit this if parts.length === 1
  33318. if(typeof curCont !== 'object' || curCont === null) return undefined;
  33319. out = curCont[parts[i]];
  33320. if(out === null) return undefined;
  33321. return out;
  33322. };
  33323. }
  33324. /*
  33325. * Can this value be deleted? We can delete `undefined`, and `null` except INSIDE an
  33326. * *args* array.
  33327. *
  33328. * Previously we also deleted some `{}` and `[]`, in order to try and make set/unset
  33329. * a net noop; but this causes far more complication than it's worth, and still had
  33330. * lots of exceptions. See https://github.com/plotly/plotly.js/issues/1410
  33331. *
  33332. * *args* arrays get passed directly to API methods and we should respect null if
  33333. * the user put it there, but otherwise null is deleted as we use it as code
  33334. * in restyle/relayout/update for "delete this value" whereas undefined means
  33335. * "ignore this edit"
  33336. */
  33337. var ARGS_PATTERN = /(^|\.)args\[/;
  33338. function isDeletable(val, propStr) {
  33339. return (val === undefined) || (val === null && !propStr.match(ARGS_PATTERN));
  33340. }
  33341. function npSet(cont, parts, propStr) {
  33342. return function(val) {
  33343. var curCont = cont;
  33344. var propPart = '';
  33345. var containerLevels = [[cont, propPart]];
  33346. var toDelete = isDeletable(val, propStr);
  33347. var curPart;
  33348. var i;
  33349. for(i = 0; i < parts.length - 1; i++) {
  33350. curPart = parts[i];
  33351. if(typeof curPart === 'number' && !isArrayOrTypedArray(curCont)) {
  33352. throw 'array index but container is not an array';
  33353. }
  33354. // handle special -1 array index
  33355. if(curPart === -1) {
  33356. toDelete = !setArrayAll(curCont, parts.slice(i + 1), val, propStr);
  33357. if(toDelete) break;
  33358. else return;
  33359. }
  33360. if(!checkNewContainer(curCont, curPart, parts[i + 1], toDelete)) {
  33361. break;
  33362. }
  33363. curCont = curCont[curPart];
  33364. if(typeof curCont !== 'object' || curCont === null) {
  33365. throw 'container is not an object';
  33366. }
  33367. propPart = joinPropStr(propPart, curPart);
  33368. containerLevels.push([curCont, propPart]);
  33369. }
  33370. if(toDelete) {
  33371. if(i === parts.length - 1) {
  33372. delete curCont[parts[i]];
  33373. // The one bit of pruning we still do: drop `undefined` from the end of arrays.
  33374. // In case someone has already unset previous items, continue until we hit a
  33375. // non-undefined value.
  33376. if(Array.isArray(curCont) && +parts[i] === curCont.length - 1) {
  33377. while(curCont.length && curCont[curCont.length - 1] === undefined) {
  33378. curCont.pop();
  33379. }
  33380. }
  33381. }
  33382. }
  33383. else curCont[parts[i]] = val;
  33384. };
  33385. }
  33386. function joinPropStr(propStr, newPart) {
  33387. var toAdd = newPart;
  33388. if(isNumeric(newPart)) toAdd = '[' + newPart + ']';
  33389. else if(propStr) toAdd = '.' + newPart;
  33390. return propStr + toAdd;
  33391. }
  33392. // handle special -1 array index
  33393. function setArrayAll(containerArray, innerParts, val, propStr) {
  33394. var arrayVal = isArrayOrTypedArray(val);
  33395. var allSet = true;
  33396. var thisVal = val;
  33397. var thisPropStr = propStr.replace('-1', 0);
  33398. var deleteThis = arrayVal ? false : isDeletable(val, thisPropStr);
  33399. var firstPart = innerParts[0];
  33400. var i;
  33401. for(i = 0; i < containerArray.length; i++) {
  33402. thisPropStr = propStr.replace('-1', i);
  33403. if(arrayVal) {
  33404. thisVal = val[i % val.length];
  33405. deleteThis = isDeletable(thisVal, thisPropStr);
  33406. }
  33407. if(deleteThis) allSet = false;
  33408. if(!checkNewContainer(containerArray, i, firstPart, deleteThis)) {
  33409. continue;
  33410. }
  33411. npSet(containerArray[i], innerParts, propStr.replace('-1', i))(thisVal);
  33412. }
  33413. return allSet;
  33414. }
  33415. /**
  33416. * make new sub-container as needed.
  33417. * returns false if there's no container and none is needed
  33418. * because we're only deleting an attribute
  33419. */
  33420. function checkNewContainer(container, part, nextPart, toDelete) {
  33421. if(container[part] === undefined) {
  33422. if(toDelete) return false;
  33423. if(typeof nextPart === 'number') container[part] = [];
  33424. else container[part] = {};
  33425. }
  33426. return true;
  33427. }
  33428. function badContainer(container, propStr, propParts) {
  33429. return {
  33430. set: function() { throw 'bad container'; },
  33431. get: function() {},
  33432. astr: propStr,
  33433. parts: propParts,
  33434. obj: container
  33435. };
  33436. }
  33437. },{"./array":155,"fast-isnumeric":18}],177:[function(_dereq_,module,exports){
  33438. /**
  33439. * Copyright 2012-2019, Plotly, Inc.
  33440. * All rights reserved.
  33441. *
  33442. * This source code is licensed under the MIT license found in the
  33443. * LICENSE file in the root directory of this source tree.
  33444. */
  33445. 'use strict';
  33446. // Simple helper functions
  33447. // none of these need any external deps
  33448. module.exports = function noop() {};
  33449. },{}],178:[function(_dereq_,module,exports){
  33450. /**
  33451. * Copyright 2012-2019, Plotly, Inc.
  33452. * All rights reserved.
  33453. *
  33454. * This source code is licensed under the MIT license found in the
  33455. * LICENSE file in the root directory of this source tree.
  33456. */
  33457. 'use strict';
  33458. var d3 = _dereq_('d3');
  33459. var isNumeric = _dereq_('fast-isnumeric');
  33460. var NOTEDATA = [];
  33461. /**
  33462. * notifier
  33463. * @param {String} text The person's user name
  33464. * @param {Number} [delay=1000] The delay time in milliseconds
  33465. * or 'long' which provides 2000 ms delay time.
  33466. * @return {undefined} this function does not return a value
  33467. */
  33468. module.exports = function(text, displayLength) {
  33469. if(NOTEDATA.indexOf(text) !== -1) return;
  33470. NOTEDATA.push(text);
  33471. var ts = 1000;
  33472. if(isNumeric(displayLength)) ts = displayLength;
  33473. else if(displayLength === 'long') ts = 3000;
  33474. var notifierContainer = d3.select('body')
  33475. .selectAll('.plotly-notifier')
  33476. .data([0]);
  33477. notifierContainer.enter()
  33478. .append('div')
  33479. .classed('plotly-notifier', true);
  33480. var notes = notifierContainer.selectAll('.notifier-note').data(NOTEDATA);
  33481. function killNote(transition) {
  33482. transition
  33483. .duration(700)
  33484. .style('opacity', 0)
  33485. .each('end', function(thisText) {
  33486. var thisIndex = NOTEDATA.indexOf(thisText);
  33487. if(thisIndex !== -1) NOTEDATA.splice(thisIndex, 1);
  33488. d3.select(this).remove();
  33489. });
  33490. }
  33491. notes.enter().append('div')
  33492. .classed('notifier-note', true)
  33493. .style('opacity', 0)
  33494. .each(function(thisText) {
  33495. var note = d3.select(this);
  33496. note.append('button')
  33497. .classed('notifier-close', true)
  33498. .html('&times;')
  33499. .on('click', function() {
  33500. note.transition().call(killNote);
  33501. });
  33502. var p = note.append('p');
  33503. var lines = thisText.split(/<br\s*\/?>/g);
  33504. for(var i = 0; i < lines.length; i++) {
  33505. if(i) p.append('br');
  33506. p.append('span').text(lines[i]);
  33507. }
  33508. note.transition()
  33509. .duration(700)
  33510. .style('opacity', 1)
  33511. .transition()
  33512. .delay(ts)
  33513. .call(killNote);
  33514. });
  33515. };
  33516. },{"d3":16,"fast-isnumeric":18}],179:[function(_dereq_,module,exports){
  33517. /**
  33518. * Copyright 2012-2019, Plotly, Inc.
  33519. * All rights reserved.
  33520. *
  33521. * This source code is licensed under the MIT license found in the
  33522. * LICENSE file in the root directory of this source tree.
  33523. */
  33524. 'use strict';
  33525. var setCursor = _dereq_('./setcursor');
  33526. var STASHATTR = 'data-savedcursor';
  33527. var NO_CURSOR = '!!';
  33528. /*
  33529. * works with our CSS cursor classes (see css/_cursor.scss)
  33530. * to override a previous cursor set on d3 single-element selections,
  33531. * by moving the name of the original cursor to the data-savedcursor attr.
  33532. * omit cursor to revert to the previously set value.
  33533. */
  33534. module.exports = function overrideCursor(el3, csr) {
  33535. var savedCursor = el3.attr(STASHATTR);
  33536. if(csr) {
  33537. if(!savedCursor) {
  33538. var classes = (el3.attr('class') || '').split(' ');
  33539. for(var i = 0; i < classes.length; i++) {
  33540. var cls = classes[i];
  33541. if(cls.indexOf('cursor-') === 0) {
  33542. el3.attr(STASHATTR, cls.substr(7))
  33543. .classed(cls, false);
  33544. }
  33545. }
  33546. if(!el3.attr(STASHATTR)) {
  33547. el3.attr(STASHATTR, NO_CURSOR);
  33548. }
  33549. }
  33550. setCursor(el3, csr);
  33551. }
  33552. else if(savedCursor) {
  33553. el3.attr(STASHATTR, null);
  33554. if(savedCursor === NO_CURSOR) setCursor(el3);
  33555. else setCursor(el3, savedCursor);
  33556. }
  33557. };
  33558. },{"./setcursor":187}],180:[function(_dereq_,module,exports){
  33559. /**
  33560. * Copyright 2012-2019, Plotly, Inc.
  33561. * All rights reserved.
  33562. *
  33563. * This source code is licensed under the MIT license found in the
  33564. * LICENSE file in the root directory of this source tree.
  33565. */
  33566. 'use strict';
  33567. var dot = _dereq_('./matrix').dot;
  33568. var BADNUM = _dereq_('../constants/numerical').BADNUM;
  33569. var polygon = module.exports = {};
  33570. /**
  33571. * Turn an array of [x, y] pairs into a polygon object
  33572. * that can test if points are inside it
  33573. *
  33574. * @param ptsIn Array of [x, y] pairs
  33575. *
  33576. * @returns polygon Object {xmin, xmax, ymin, ymax, pts, contains}
  33577. * (x|y)(min|max) are the bounding rect of the polygon
  33578. * pts is the original array, with the first pair repeated at the end
  33579. * contains is a function: (pt, omitFirstEdge)
  33580. * pt is the [x, y] pair to test
  33581. * omitFirstEdge truthy means points exactly on the first edge don't
  33582. * count. This is for use adding one polygon to another so we
  33583. * don't double-count the edge where they meet.
  33584. * returns boolean: is pt inside the polygon (including on its edges)
  33585. */
  33586. polygon.tester = function tester(ptsIn) {
  33587. var pts = ptsIn.slice();
  33588. var xmin = pts[0][0];
  33589. var xmax = xmin;
  33590. var ymin = pts[0][1];
  33591. var ymax = ymin;
  33592. var i;
  33593. pts.push(pts[0]);
  33594. for(i = 1; i < pts.length; i++) {
  33595. xmin = Math.min(xmin, pts[i][0]);
  33596. xmax = Math.max(xmax, pts[i][0]);
  33597. ymin = Math.min(ymin, pts[i][1]);
  33598. ymax = Math.max(ymax, pts[i][1]);
  33599. }
  33600. // do we have a rectangle? Handle this here, so we can use the same
  33601. // tester for the rectangular case without sacrificing speed
  33602. var isRect = false;
  33603. var rectFirstEdgeTest;
  33604. if(pts.length === 5) {
  33605. if(pts[0][0] === pts[1][0]) { // vert, horz, vert, horz
  33606. if(pts[2][0] === pts[3][0] &&
  33607. pts[0][1] === pts[3][1] &&
  33608. pts[1][1] === pts[2][1]) {
  33609. isRect = true;
  33610. rectFirstEdgeTest = function(pt) { return pt[0] === pts[0][0]; };
  33611. }
  33612. }
  33613. else if(pts[0][1] === pts[1][1]) { // horz, vert, horz, vert
  33614. if(pts[2][1] === pts[3][1] &&
  33615. pts[0][0] === pts[3][0] &&
  33616. pts[1][0] === pts[2][0]) {
  33617. isRect = true;
  33618. rectFirstEdgeTest = function(pt) { return pt[1] === pts[0][1]; };
  33619. }
  33620. }
  33621. }
  33622. function rectContains(pt, omitFirstEdge) {
  33623. var x = pt[0];
  33624. var y = pt[1];
  33625. if(x === BADNUM || x < xmin || x > xmax || y === BADNUM || y < ymin || y > ymax) {
  33626. // pt is outside the bounding box of polygon
  33627. return false;
  33628. }
  33629. if(omitFirstEdge && rectFirstEdgeTest(pt)) return false;
  33630. return true;
  33631. }
  33632. function contains(pt, omitFirstEdge) {
  33633. var x = pt[0];
  33634. var y = pt[1];
  33635. if(x === BADNUM || x < xmin || x > xmax || y === BADNUM || y < ymin || y > ymax) {
  33636. // pt is outside the bounding box of polygon
  33637. return false;
  33638. }
  33639. var imax = pts.length;
  33640. var x1 = pts[0][0];
  33641. var y1 = pts[0][1];
  33642. var crossings = 0;
  33643. var i;
  33644. var x0;
  33645. var y0;
  33646. var xmini;
  33647. var ycross;
  33648. for(i = 1; i < imax; i++) {
  33649. // find all crossings of a vertical line upward from pt with
  33650. // polygon segments
  33651. // crossings exactly at xmax don't count, unless the point is
  33652. // exactly on the segment, then it counts as inside.
  33653. x0 = x1;
  33654. y0 = y1;
  33655. x1 = pts[i][0];
  33656. y1 = pts[i][1];
  33657. xmini = Math.min(x0, x1);
  33658. // outside the bounding box of this segment, it's only a crossing
  33659. // if it's below the box.
  33660. if(x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) {
  33661. continue;
  33662. }
  33663. else if(y < Math.min(y0, y1)) {
  33664. // don't count the left-most point of the segment as a crossing
  33665. // because we don't want to double-count adjacent crossings
  33666. // UNLESS the polygon turns past vertical at exactly this x
  33667. // Note that this is repeated below, but we can't factor it out
  33668. // because
  33669. if(x !== xmini) crossings++;
  33670. }
  33671. // inside the bounding box, check the actual line intercept
  33672. else {
  33673. // vertical segment - we know already that the point is exactly
  33674. // on the segment, so mark the crossing as exactly at the point.
  33675. if(x1 === x0) ycross = y;
  33676. // any other angle
  33677. else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0);
  33678. // exactly on the edge: counts as inside the polygon, unless it's the
  33679. // first edge and we're omitting it.
  33680. if(y === ycross) {
  33681. if(i === 1 && omitFirstEdge) return false;
  33682. return true;
  33683. }
  33684. if(y <= ycross && x !== xmini) crossings++;
  33685. }
  33686. }
  33687. // if we've gotten this far, odd crossings means inside, even is outside
  33688. return crossings % 2 === 1;
  33689. }
  33690. // detect if poly is degenerate
  33691. var degenerate = true;
  33692. var lastPt = pts[0];
  33693. for(i = 1; i < pts.length; i++) {
  33694. if(lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) {
  33695. degenerate = false;
  33696. break;
  33697. }
  33698. }
  33699. return {
  33700. xmin: xmin,
  33701. xmax: xmax,
  33702. ymin: ymin,
  33703. ymax: ymax,
  33704. pts: pts,
  33705. contains: isRect ? rectContains : contains,
  33706. isRect: isRect,
  33707. degenerate: degenerate
  33708. };
  33709. };
  33710. /**
  33711. * Test if a segment of a points array is bent or straight
  33712. *
  33713. * @param pts Array of [x, y] pairs
  33714. * @param start the index of the proposed start of the straight section
  33715. * @param end the index of the proposed end point
  33716. * @param tolerance the max distance off the line connecting start and end
  33717. * before the line counts as bent
  33718. * @returns boolean: true means this segment is bent, false means straight
  33719. */
  33720. var isBent = polygon.isSegmentBent = function isBent(pts, start, end, tolerance) {
  33721. var startPt = pts[start];
  33722. var segment = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]];
  33723. var segmentSquared = dot(segment, segment);
  33724. var segmentLen = Math.sqrt(segmentSquared);
  33725. var unitPerp = [-segment[1] / segmentLen, segment[0] / segmentLen];
  33726. var i;
  33727. var part;
  33728. var partParallel;
  33729. for(i = start + 1; i < end; i++) {
  33730. part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]];
  33731. partParallel = dot(part, segment);
  33732. if(partParallel < 0 || partParallel > segmentSquared ||
  33733. Math.abs(dot(part, unitPerp)) > tolerance) return true;
  33734. }
  33735. return false;
  33736. };
  33737. /**
  33738. * Make a filtering polygon, to minimize the number of segments
  33739. *
  33740. * @param pts Array of [x, y] pairs (must start with at least 1 pair)
  33741. * @param tolerance the maximum deviation from straight allowed for
  33742. * removing points to simplify the polygon
  33743. *
  33744. * @returns Object {addPt, raw, filtered}
  33745. * addPt is a function(pt: [x, y] pair) to add a raw point and
  33746. * continue filtering
  33747. * raw is all the input points
  33748. * filtered is the resulting filtered Array of [x, y] pairs
  33749. */
  33750. polygon.filter = function filter(pts, tolerance) {
  33751. var ptsFiltered = [pts[0]];
  33752. var doneRawIndex = 0;
  33753. var doneFilteredIndex = 0;
  33754. function addPt(pt) {
  33755. pts.push(pt);
  33756. var prevFilterLen = ptsFiltered.length;
  33757. var iLast = doneRawIndex;
  33758. ptsFiltered.splice(doneFilteredIndex + 1);
  33759. for(var i = iLast + 1; i < pts.length; i++) {
  33760. if(i === pts.length - 1 || isBent(pts, iLast, i + 1, tolerance)) {
  33761. ptsFiltered.push(pts[i]);
  33762. if(ptsFiltered.length < prevFilterLen - 2) {
  33763. doneRawIndex = i;
  33764. doneFilteredIndex = ptsFiltered.length - 1;
  33765. }
  33766. iLast = i;
  33767. }
  33768. }
  33769. }
  33770. if(pts.length > 1) {
  33771. var lastPt = pts.pop();
  33772. addPt(lastPt);
  33773. }
  33774. return {
  33775. addPt: addPt,
  33776. raw: pts,
  33777. filtered: ptsFiltered
  33778. };
  33779. };
  33780. },{"../constants/numerical":149,"./matrix":174}],181:[function(_dereq_,module,exports){
  33781. /**
  33782. * Copyright 2012-2019, Plotly, Inc.
  33783. * All rights reserved.
  33784. *
  33785. * This source code is licensed under the MIT license found in the
  33786. * LICENSE file in the root directory of this source tree.
  33787. */
  33788. 'use strict';
  33789. /**
  33790. * Push array with unique items
  33791. *
  33792. * Ignores falsy items, except 0 so we can use it to construct arrays of indices.
  33793. *
  33794. * @param {array} array
  33795. * array to be filled
  33796. * @param {any} item
  33797. * item to be or not to be inserted
  33798. * @return {array}
  33799. * ref to array (now possibly containing one more item)
  33800. *
  33801. */
  33802. module.exports = function pushUnique(array, item) {
  33803. if(item instanceof RegExp) {
  33804. var itemStr = item.toString();
  33805. for(var i = 0; i < array.length; i++) {
  33806. if(array[i] instanceof RegExp && array[i].toString() === itemStr) {
  33807. return array;
  33808. }
  33809. }
  33810. array.push(item);
  33811. }
  33812. else if((item || item === 0) && array.indexOf(item) === -1) array.push(item);
  33813. return array;
  33814. };
  33815. },{}],182:[function(_dereq_,module,exports){
  33816. /**
  33817. * Copyright 2012-2019, Plotly, Inc.
  33818. * All rights reserved.
  33819. *
  33820. * This source code is licensed under the MIT license found in the
  33821. * LICENSE file in the root directory of this source tree.
  33822. */
  33823. 'use strict';
  33824. var Lib = _dereq_('../lib');
  33825. var dfltConfig = _dereq_('../plot_api/plot_config').dfltConfig;
  33826. /**
  33827. * Copy arg array *without* removing `undefined` values from objects.
  33828. *
  33829. * @param gd
  33830. * @param args
  33831. * @returns {Array}
  33832. */
  33833. function copyArgArray(gd, args) {
  33834. var copy = [];
  33835. var arg;
  33836. for(var i = 0; i < args.length; i++) {
  33837. arg = args[i];
  33838. if(arg === gd) copy[i] = arg;
  33839. else if(typeof arg === 'object') {
  33840. copy[i] = Array.isArray(arg) ?
  33841. Lib.extendDeep([], arg) :
  33842. Lib.extendDeepAll({}, arg);
  33843. }
  33844. else copy[i] = arg;
  33845. }
  33846. return copy;
  33847. }
  33848. // -----------------------------------------------------
  33849. // Undo/Redo queue for plots
  33850. // -----------------------------------------------------
  33851. var queue = {};
  33852. // TODO: disable/enable undo and redo buttons appropriately
  33853. /**
  33854. * Add an item to the undoQueue for a graphDiv
  33855. *
  33856. * @param gd
  33857. * @param undoFunc Function undo this operation
  33858. * @param undoArgs Args to supply undoFunc with
  33859. * @param redoFunc Function to redo this operation
  33860. * @param redoArgs Args to supply redoFunc with
  33861. */
  33862. queue.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) {
  33863. var queueObj,
  33864. queueIndex;
  33865. // make sure we have the queue and our position in it
  33866. gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false};
  33867. queueIndex = gd.undoQueue.index;
  33868. // if we're already playing an undo or redo, or if this is an auto operation
  33869. // (like pane resize... any others?) then we don't save this to the undo queue
  33870. if(gd.autoplay) {
  33871. if(!gd.undoQueue.inSequence) gd.autoplay = false;
  33872. return;
  33873. }
  33874. // if we're not in a sequence or are just starting, we need a new queue item
  33875. if(!gd.undoQueue.sequence || gd.undoQueue.beginSequence) {
  33876. queueObj = {undo: {calls: [], args: []}, redo: {calls: [], args: []}};
  33877. gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj);
  33878. gd.undoQueue.index += 1;
  33879. } else {
  33880. queueObj = gd.undoQueue.queue[queueIndex - 1];
  33881. }
  33882. gd.undoQueue.beginSequence = false;
  33883. // we unshift to handle calls for undo in a forward for loop later
  33884. if(queueObj) {
  33885. queueObj.undo.calls.unshift(undoFunc);
  33886. queueObj.undo.args.unshift(undoArgs);
  33887. queueObj.redo.calls.push(redoFunc);
  33888. queueObj.redo.args.push(redoArgs);
  33889. }
  33890. if(gd.undoQueue.queue.length > dfltConfig.queueLength) {
  33891. gd.undoQueue.queue.shift();
  33892. gd.undoQueue.index--;
  33893. }
  33894. };
  33895. /**
  33896. * Begin a sequence of undoQueue changes
  33897. *
  33898. * @param gd
  33899. */
  33900. queue.startSequence = function(gd) {
  33901. gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false};
  33902. gd.undoQueue.sequence = true;
  33903. gd.undoQueue.beginSequence = true;
  33904. };
  33905. /**
  33906. * Stop a sequence of undoQueue changes
  33907. *
  33908. * Call this *after* you're sure your undo chain has ended
  33909. *
  33910. * @param gd
  33911. */
  33912. queue.stopSequence = function(gd) {
  33913. gd.undoQueue = gd.undoQueue || {index: 0, queue: [], sequence: false};
  33914. gd.undoQueue.sequence = false;
  33915. gd.undoQueue.beginSequence = false;
  33916. };
  33917. /**
  33918. * Move one step back in the undo queue, and undo the object there.
  33919. *
  33920. * @param gd
  33921. */
  33922. queue.undo = function undo(gd) {
  33923. var queueObj, i;
  33924. if(gd.framework && gd.framework.isPolar) {
  33925. gd.framework.undo();
  33926. return;
  33927. }
  33928. if(gd.undoQueue === undefined ||
  33929. isNaN(gd.undoQueue.index) ||
  33930. gd.undoQueue.index <= 0) {
  33931. return;
  33932. }
  33933. // index is pointing to next *forward* queueObj, point to the one we're undoing
  33934. gd.undoQueue.index--;
  33935. // get the queueObj for instructions on how to undo
  33936. queueObj = gd.undoQueue.queue[gd.undoQueue.index];
  33937. // this sequence keeps things from adding to the queue during undo/redo
  33938. gd.undoQueue.inSequence = true;
  33939. for(i = 0; i < queueObj.undo.calls.length; i++) {
  33940. queue.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]);
  33941. }
  33942. gd.undoQueue.inSequence = false;
  33943. gd.autoplay = false;
  33944. };
  33945. /**
  33946. * Redo the current object in the undo, then move forward in the queue.
  33947. *
  33948. * @param gd
  33949. */
  33950. queue.redo = function redo(gd) {
  33951. var queueObj, i;
  33952. if(gd.framework && gd.framework.isPolar) {
  33953. gd.framework.redo();
  33954. return;
  33955. }
  33956. if(gd.undoQueue === undefined ||
  33957. isNaN(gd.undoQueue.index) ||
  33958. gd.undoQueue.index >= gd.undoQueue.queue.length) {
  33959. return;
  33960. }
  33961. // get the queueObj for instructions on how to undo
  33962. queueObj = gd.undoQueue.queue[gd.undoQueue.index];
  33963. // this sequence keeps things from adding to the queue during undo/redo
  33964. gd.undoQueue.inSequence = true;
  33965. for(i = 0; i < queueObj.redo.calls.length; i++) {
  33966. queue.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]);
  33967. }
  33968. gd.undoQueue.inSequence = false;
  33969. gd.autoplay = false;
  33970. // index is pointing to the thing we just redid, move it
  33971. gd.undoQueue.index++;
  33972. };
  33973. /**
  33974. * Called by undo/redo to make the actual changes.
  33975. *
  33976. * Not meant to be called publically, but included for mocking out in tests.
  33977. *
  33978. * @param gd
  33979. * @param func
  33980. * @param args
  33981. */
  33982. queue.plotDo = function(gd, func, args) {
  33983. gd.autoplay = true;
  33984. // this *won't* copy gd and it preserves `undefined` properties!
  33985. args = copyArgArray(gd, args);
  33986. // call the supplied function
  33987. func.apply(null, args);
  33988. };
  33989. module.exports = queue;
  33990. },{"../lib":168,"../plot_api/plot_config":200}],183:[function(_dereq_,module,exports){
  33991. /**
  33992. * Copyright 2012-2019, Plotly, Inc.
  33993. * All rights reserved.
  33994. *
  33995. * This source code is licensed under the MIT license found in the
  33996. * LICENSE file in the root directory of this source tree.
  33997. */
  33998. 'use strict';
  33999. /*
  34000. * make a regex for matching counter ids/names ie xaxis, xaxis2, xaxis10...
  34001. *
  34002. * @param {string} head: the head of the pattern, eg 'x' matches 'x', 'x2', 'x10' etc.
  34003. * 'xy' is a special case for cartesian subplots: it matches 'x2y3' etc
  34004. * @param {Optional(string)} tail: a fixed piece after the id
  34005. * eg counterRegex('scene', '.annotations') for scene2.annotations etc.
  34006. * @param {boolean} openEnded: if true, the string may continue past the match.
  34007. * @param {boolean} matchBeginning: if false, the string may start before the match.
  34008. */
  34009. exports.counter = function(head, tail, openEnded, matchBeginning) {
  34010. var fullTail = (tail || '') + (openEnded ? '' : '$');
  34011. var startWithPrefix = matchBeginning === false ? '' : '^';
  34012. if(head === 'xy') {
  34013. return new RegExp(startWithPrefix + 'x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?' + fullTail);
  34014. }
  34015. return new RegExp(startWithPrefix + head + '([2-9]|[1-9][0-9]+)?' + fullTail);
  34016. };
  34017. },{}],184:[function(_dereq_,module,exports){
  34018. /**
  34019. * Copyright 2012-2019, Plotly, Inc.
  34020. * All rights reserved.
  34021. *
  34022. * This source code is licensed under the MIT license found in the
  34023. * LICENSE file in the root directory of this source tree.
  34024. */
  34025. 'use strict';
  34026. // ASCEND: chop off the last nesting level - either [<n>] or .<key> - to ascend
  34027. // the attribute tree. the remaining attrString is in match[1]
  34028. var ASCEND = /^(.*)(\.[^\.\[\]]+|\[\d\])$/;
  34029. // SIMPLEATTR: is this an un-nested attribute? (no dots or brackets)
  34030. var SIMPLEATTR = /^[^\.\[\]]+$/;
  34031. /*
  34032. * calculate a relative attribute string, similar to a relative path
  34033. *
  34034. * @param {string} baseAttr:
  34035. * an attribute string, such as 'annotations[3].x'. The "current location"
  34036. * is the attribute string minus the last component ('annotations[3]')
  34037. * @param {string} relativeAttr:
  34038. * a route to the desired attribute string, using '^' to ascend
  34039. *
  34040. * @return {string} attrString:
  34041. * for example:
  34042. * relativeAttr('annotations[3].x', 'y') = 'annotations[3].y'
  34043. * relativeAttr('annotations[3].x', '^[2].z') = 'annotations[2].z'
  34044. * relativeAttr('annotations[3].x', '^^margin') = 'margin'
  34045. * relativeAttr('annotations[3].x', '^^margin.r') = 'margin.r'
  34046. */
  34047. module.exports = function(baseAttr, relativeAttr) {
  34048. while(relativeAttr) {
  34049. var match = baseAttr.match(ASCEND);
  34050. if(match) baseAttr = match[1];
  34051. else if(baseAttr.match(SIMPLEATTR)) baseAttr = '';
  34052. else throw new Error('bad relativeAttr call:' + [baseAttr, relativeAttr]);
  34053. if(relativeAttr.charAt(0) === '^') relativeAttr = relativeAttr.slice(1);
  34054. else break;
  34055. }
  34056. if(baseAttr && relativeAttr.charAt(0) !== '[') {
  34057. return baseAttr + '.' + relativeAttr;
  34058. }
  34059. return baseAttr + relativeAttr;
  34060. };
  34061. },{}],185:[function(_dereq_,module,exports){
  34062. /**
  34063. * Copyright 2012-2019, Plotly, Inc.
  34064. * All rights reserved.
  34065. *
  34066. * This source code is licensed under the MIT license found in the
  34067. * LICENSE file in the root directory of this source tree.
  34068. */
  34069. 'use strict';
  34070. var isArrayOrTypedArray = _dereq_('./array').isArrayOrTypedArray;
  34071. var isPlainObject = _dereq_('./is_plain_object');
  34072. /**
  34073. * Relink private _keys and keys with a function value from one container
  34074. * to the new container.
  34075. * Relink means copying if object is pass-by-value and adding a reference
  34076. * if object is pass-by-ref.
  34077. * This prevents deepCopying massive structures like a webgl context.
  34078. */
  34079. module.exports = function relinkPrivateKeys(toContainer, fromContainer) {
  34080. for(var k in fromContainer) {
  34081. var fromVal = fromContainer[k];
  34082. var toVal = toContainer[k];
  34083. if(toVal === fromVal) {
  34084. continue;
  34085. }
  34086. if(k.charAt(0) === '_' || typeof fromVal === 'function') {
  34087. // if it already exists at this point, it's something
  34088. // that we recreate each time around, so ignore it
  34089. if(k in toContainer) continue;
  34090. toContainer[k] = fromVal;
  34091. }
  34092. else if(isArrayOrTypedArray(fromVal) && isArrayOrTypedArray(toVal) && isPlainObject(fromVal[0])) {
  34093. // filter out data_array items that can contain user objects
  34094. // most of the time the toVal === fromVal check will catch these early
  34095. // but if the user makes new ones we also don't want to recurse in.
  34096. if(k === 'customdata' || k === 'ids') continue;
  34097. // recurse into arrays containers
  34098. var minLen = Math.min(fromVal.length, toVal.length);
  34099. for(var j = 0; j < minLen; j++) {
  34100. if((toVal[j] !== fromVal[j]) && isPlainObject(fromVal[j]) && isPlainObject(toVal[j])) {
  34101. relinkPrivateKeys(toVal[j], fromVal[j]);
  34102. }
  34103. }
  34104. }
  34105. else if(isPlainObject(fromVal) && isPlainObject(toVal)) {
  34106. // recurse into objects, but only if they still exist
  34107. relinkPrivateKeys(toVal, fromVal);
  34108. if(!Object.keys(toVal).length) delete toContainer[k];
  34109. }
  34110. }
  34111. };
  34112. },{"./array":155,"./is_plain_object":169}],186:[function(_dereq_,module,exports){
  34113. /**
  34114. * Copyright 2012-2019, Plotly, Inc.
  34115. * All rights reserved.
  34116. *
  34117. * This source code is licensed under the MIT license found in the
  34118. * LICENSE file in the root directory of this source tree.
  34119. */
  34120. 'use strict';
  34121. var isNumeric = _dereq_('fast-isnumeric');
  34122. var loggers = _dereq_('./loggers');
  34123. var identity = _dereq_('./identity');
  34124. // don't trust floating point equality - fraction of bin size to call
  34125. // "on the line" and ensure that they go the right way specified by
  34126. // linelow
  34127. var roundingError = 1e-9;
  34128. /**
  34129. * findBin - find the bin for val - note that it can return outside the
  34130. * bin range any pos. or neg. integer for linear bins, or -1 or
  34131. * bins.length-1 for explicit.
  34132. * bins is either an object {start,size,end} or an array length #bins+1
  34133. * bins can be either increasing or decreasing but must be monotonic
  34134. * for linear bins, we can just calculate. For listed bins, run a binary
  34135. * search linelow (truthy) says the bin boundary should be attributed to
  34136. * the lower bin rather than the default upper bin
  34137. */
  34138. exports.findBin = function(val, bins, linelow) {
  34139. if(isNumeric(bins.start)) {
  34140. return linelow ?
  34141. Math.ceil((val - bins.start) / bins.size - roundingError) - 1 :
  34142. Math.floor((val - bins.start) / bins.size + roundingError);
  34143. }
  34144. else {
  34145. var n1 = 0;
  34146. var n2 = bins.length;
  34147. var c = 0;
  34148. var binSize = (n2 > 1) ? (bins[n2 - 1] - bins[0]) / (n2 - 1) : 1;
  34149. var n, test;
  34150. if(binSize >= 0) {
  34151. test = linelow ? lessThan : lessOrEqual;
  34152. } else {
  34153. test = linelow ? greaterOrEqual : greaterThan;
  34154. }
  34155. val += binSize * roundingError * (linelow ? -1 : 1) * (binSize >= 0 ? 1 : -1);
  34156. // c is just to avoid infinite loops if there's an error
  34157. while(n1 < n2 && c++ < 100) {
  34158. n = Math.floor((n1 + n2) / 2);
  34159. if(test(bins[n], val)) n1 = n + 1;
  34160. else n2 = n;
  34161. }
  34162. if(c > 90) loggers.log('Long binary search...');
  34163. return n1 - 1;
  34164. }
  34165. };
  34166. function lessThan(a, b) { return a < b; }
  34167. function lessOrEqual(a, b) { return a <= b; }
  34168. function greaterThan(a, b) { return a > b; }
  34169. function greaterOrEqual(a, b) { return a >= b; }
  34170. exports.sorterAsc = function(a, b) { return a - b; };
  34171. exports.sorterDes = function(a, b) { return b - a; };
  34172. /**
  34173. * find distinct values in an array, lumping together ones that appear to
  34174. * just be off by a rounding error
  34175. * return the distinct values and the minimum difference between any two
  34176. */
  34177. exports.distinctVals = function(valsIn) {
  34178. var vals = valsIn.slice(); // otherwise we sort the original array...
  34179. vals.sort(exports.sorterAsc);
  34180. var l = vals.length - 1;
  34181. var minDiff = (vals[l] - vals[0]) || 1;
  34182. var errDiff = minDiff / (l || 1) / 10000;
  34183. var v2 = [vals[0]];
  34184. for(var i = 0; i < l; i++) {
  34185. // make sure values aren't just off by a rounding error
  34186. if(vals[i + 1] > vals[i] + errDiff) {
  34187. minDiff = Math.min(minDiff, vals[i + 1] - vals[i]);
  34188. v2.push(vals[i + 1]);
  34189. }
  34190. }
  34191. return {vals: v2, minDiff: minDiff};
  34192. };
  34193. /**
  34194. * return the smallest element from (sorted) array arrayIn that's bigger than val,
  34195. * or (reverse) the largest element smaller than val
  34196. * used to find the best tick given the minimum (non-rounded) tick
  34197. * particularly useful for date/time where things are not powers of 10
  34198. * binary search is probably overkill here...
  34199. */
  34200. exports.roundUp = function(val, arrayIn, reverse) {
  34201. var low = 0;
  34202. var high = arrayIn.length - 1;
  34203. var mid;
  34204. var c = 0;
  34205. var dlow = reverse ? 0 : 1;
  34206. var dhigh = reverse ? 1 : 0;
  34207. var rounded = reverse ? Math.ceil : Math.floor;
  34208. // c is just to avoid infinite loops if there's an error
  34209. while(low < high && c++ < 100) {
  34210. mid = rounded((low + high) / 2);
  34211. if(arrayIn[mid] <= val) low = mid + dlow;
  34212. else high = mid - dhigh;
  34213. }
  34214. return arrayIn[low];
  34215. };
  34216. /**
  34217. * Tweak to Array.sort(sortFn) that improves performance for pre-sorted arrays
  34218. *
  34219. * Note that newer browsers (such as Chrome v70+) are starting to pick up
  34220. * on pre-sorted arrays which may render the following optimization unnecessary
  34221. * in the future.
  34222. *
  34223. * Motivation: sometimes we need to sort arrays but the input is likely to
  34224. * already be sorted. Browsers don't seem to pick up on pre-sorted arrays,
  34225. * and in fact Chrome is actually *slower* sorting pre-sorted arrays than purely
  34226. * random arrays. FF is at least faster if the array is pre-sorted, but still
  34227. * not as fast as it could be.
  34228. * Here's how this plays out sorting a length-1e6 array:
  34229. *
  34230. * Calls to Sort FN | Chrome bare | FF bare | Chrome tweak | FF tweak
  34231. * | v68.0 Mac | v61.0 Mac| |
  34232. * ------------------+---------------+-----------+----------------+------------
  34233. * ordered | 30.4e6 | 10.1e6 | 1e6 | 1e6
  34234. * reversed | 29.4e6 | 9.9e6 | 1e6 + reverse | 1e6 + reverse
  34235. * random | ~21e6 | ~18.7e6 | ~21e6 | ~18.7e6
  34236. *
  34237. * So this is a substantial win for pre-sorted (ordered or exactly reversed)
  34238. * arrays. Including this wrapper on an unsorted array adds a penalty that will
  34239. * in general be only a few calls to the sort function. The only case this
  34240. * penalty will be significant is if the array is mostly sorted but there are
  34241. * a few unsorted items near the end, but the penalty is still at most N calls
  34242. * out of (for N=1e6) ~20N total calls
  34243. *
  34244. * @param {Array} array: the array, to be sorted in place
  34245. * @param {function} sortFn: As in Array.sort, function(a, b) that puts
  34246. * item a before item b if the return is negative, a after b if positive,
  34247. * and no change if zero.
  34248. * @return {Array}: the original array, sorted in place.
  34249. */
  34250. exports.sort = function(array, sortFn) {
  34251. var notOrdered = 0;
  34252. var notReversed = 0;
  34253. for(var i = 1; i < array.length; i++) {
  34254. var pairOrder = sortFn(array[i], array[i - 1]);
  34255. if(pairOrder < 0) notOrdered = 1;
  34256. else if(pairOrder > 0) notReversed = 1;
  34257. if(notOrdered && notReversed) return array.sort(sortFn);
  34258. }
  34259. return notReversed ? array : array.reverse();
  34260. };
  34261. /**
  34262. * find index in array 'arr' that minimizes 'fn'
  34263. *
  34264. * @param {array} arr : array where to search
  34265. * @param {fn (optional)} fn : function to minimize,
  34266. * if not given, fn is the identity function
  34267. * @return {integer}
  34268. */
  34269. exports.findIndexOfMin = function(arr, fn) {
  34270. fn = fn || identity;
  34271. var min = Infinity;
  34272. var ind;
  34273. for(var i = 0; i < arr.length; i++) {
  34274. var v = fn(arr[i]);
  34275. if(v < min) {
  34276. min = v;
  34277. ind = i;
  34278. }
  34279. }
  34280. return ind;
  34281. };
  34282. },{"./identity":167,"./loggers":172,"fast-isnumeric":18}],187:[function(_dereq_,module,exports){
  34283. /**
  34284. * Copyright 2012-2019, Plotly, Inc.
  34285. * All rights reserved.
  34286. *
  34287. * This source code is licensed under the MIT license found in the
  34288. * LICENSE file in the root directory of this source tree.
  34289. */
  34290. 'use strict';
  34291. // works with our CSS cursor classes (see css/_cursor.scss)
  34292. // to apply cursors to d3 single-element selections.
  34293. // omit cursor to revert to the default.
  34294. module.exports = function setCursor(el3, csr) {
  34295. (el3.attr('class') || '').split(' ').forEach(function(cls) {
  34296. if(cls.indexOf('cursor-') === 0) el3.classed(cls, false);
  34297. });
  34298. if(csr) el3.classed('cursor-' + csr, true);
  34299. };
  34300. },{}],188:[function(_dereq_,module,exports){
  34301. /**
  34302. * Copyright 2012-2019, Plotly, Inc.
  34303. * All rights reserved.
  34304. *
  34305. * This source code is licensed under the MIT license found in the
  34306. * LICENSE file in the root directory of this source tree.
  34307. */
  34308. 'use strict';
  34309. var isNumeric = _dereq_('fast-isnumeric');
  34310. var isArrayOrTypedArray = _dereq_('./array').isArrayOrTypedArray;
  34311. /**
  34312. * aggNums() returns the result of an aggregate function applied to an array of
  34313. * values, where non-numerical values have been tossed out.
  34314. *
  34315. * @param {function} f - aggregation function (e.g., Math.min)
  34316. * @param {Number} v - initial value (continuing from previous calls)
  34317. * if there's no continuing value, use null for selector-type
  34318. * functions (max,min), or 0 for summations
  34319. * @param {Array} a - array to aggregate (may be nested, we will recurse,
  34320. * but all elements must have the same dimension)
  34321. * @param {Number} len - maximum length of a to aggregate
  34322. * @return {Number} - result of f applied to a starting from v
  34323. */
  34324. exports.aggNums = function(f, v, a, len) {
  34325. var i,
  34326. b;
  34327. if(!len || len > a.length) len = a.length;
  34328. if(!isNumeric(v)) v = false;
  34329. if(isArrayOrTypedArray(a[0])) {
  34330. b = new Array(len);
  34331. for(i = 0; i < len; i++) b[i] = exports.aggNums(f, v, a[i]);
  34332. a = b;
  34333. }
  34334. for(i = 0; i < len; i++) {
  34335. if(!isNumeric(v)) v = a[i];
  34336. else if(isNumeric(a[i])) v = f(+v, +a[i]);
  34337. }
  34338. return v;
  34339. };
  34340. /**
  34341. * mean & std dev functions using aggNums, so it handles non-numerics nicely
  34342. * even need to use aggNums instead of .length, to toss out non-numerics
  34343. */
  34344. exports.len = function(data) {
  34345. return exports.aggNums(function(a) { return a + 1; }, 0, data);
  34346. };
  34347. exports.mean = function(data, len) {
  34348. if(!len) len = exports.len(data);
  34349. return exports.aggNums(function(a, b) { return a + b; }, 0, data) / len;
  34350. };
  34351. exports.midRange = function(numArr) {
  34352. if(numArr === undefined || numArr.length === 0) return undefined;
  34353. return (exports.aggNums(Math.max, null, numArr) + exports.aggNums(Math.min, null, numArr)) / 2;
  34354. };
  34355. exports.variance = function(data, len, mean) {
  34356. if(!len) len = exports.len(data);
  34357. if(!isNumeric(mean)) mean = exports.mean(data, len);
  34358. return exports.aggNums(function(a, b) {
  34359. return a + Math.pow(b - mean, 2);
  34360. }, 0, data) / len;
  34361. };
  34362. exports.stdev = function(data, len, mean) {
  34363. return Math.sqrt(exports.variance(data, len, mean));
  34364. };
  34365. /**
  34366. * interp() computes a percentile (quantile) for a given distribution.
  34367. * We interpolate the distribution (to compute quantiles, we follow method #10 here:
  34368. * http://www.amstat.org/publications/jse/v14n3/langford.html).
  34369. * Typically the index or rank (n * arr.length) may be non-integer.
  34370. * For reference: ends are clipped to the extreme values in the array;
  34371. * For box plots: index you get is half a point too high (see
  34372. * http://en.wikipedia.org/wiki/Percentile#Nearest_rank) but note that this definition
  34373. * indexes from 1 rather than 0, so we subtract 1/2 (instead of add).
  34374. *
  34375. * @param {Array} arr - This array contains the values that make up the distribution.
  34376. * @param {Number} n - Between 0 and 1, n = p/100 is such that we compute the p^th percentile.
  34377. * For example, the 50th percentile (or median) corresponds to n = 0.5
  34378. * @return {Number} - percentile
  34379. */
  34380. exports.interp = function(arr, n) {
  34381. if(!isNumeric(n)) throw 'n should be a finite number';
  34382. n = n * arr.length - 0.5;
  34383. if(n < 0) return arr[0];
  34384. if(n > arr.length - 1) return arr[arr.length - 1];
  34385. var frac = n % 1;
  34386. return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)];
  34387. };
  34388. },{"./array":155,"fast-isnumeric":18}],189:[function(_dereq_,module,exports){
  34389. /**
  34390. * Copyright 2012-2019, Plotly, Inc.
  34391. * All rights reserved.
  34392. *
  34393. * This source code is licensed under the MIT license found in the
  34394. * LICENSE file in the root directory of this source tree.
  34395. */
  34396. 'use strict';
  34397. /* global MathJax:false */
  34398. var d3 = _dereq_('d3');
  34399. var Lib = _dereq_('../lib');
  34400. var xmlnsNamespaces = _dereq_('../constants/xmlns_namespaces');
  34401. var LINE_SPACING = _dereq_('../constants/alignment').LINE_SPACING;
  34402. // text converter
  34403. function getSize(_selection, _dimension) {
  34404. return _selection.node().getBoundingClientRect()[_dimension];
  34405. }
  34406. var FIND_TEX = /([^$]*)([$]+[^$]*[$]+)([^$]*)/;
  34407. exports.convertToTspans = function(_context, gd, _callback) {
  34408. var str = _context.text();
  34409. // Until we get tex integrated more fully (so it can be used along with non-tex)
  34410. // allow some elements to prohibit it by attaching 'data-notex' to the original
  34411. var tex = (!_context.attr('data-notex')) &&
  34412. (typeof MathJax !== 'undefined') &&
  34413. str.match(FIND_TEX);
  34414. var parent = d3.select(_context.node().parentNode);
  34415. if(parent.empty()) return;
  34416. var svgClass = (_context.attr('class')) ? _context.attr('class').split(' ')[0] : 'text';
  34417. svgClass += '-math';
  34418. parent.selectAll('svg.' + svgClass).remove();
  34419. parent.selectAll('g.' + svgClass + '-group').remove();
  34420. _context.style('display', null)
  34421. .attr({
  34422. // some callers use data-unformatted *from the <text> element* in 'cancel'
  34423. // so we need it here even if we're going to turn it into math
  34424. // these two (plus style and text-anchor attributes) form the key we're
  34425. // going to use for Drawing.bBox
  34426. 'data-unformatted': str,
  34427. 'data-math': 'N'
  34428. });
  34429. function showText() {
  34430. if(!parent.empty()) {
  34431. svgClass = _context.attr('class') + '-math';
  34432. parent.select('svg.' + svgClass).remove();
  34433. }
  34434. _context.text('')
  34435. .style('white-space', 'pre');
  34436. var hasLink = buildSVGText(_context.node(), str);
  34437. if(hasLink) {
  34438. // at least in Chrome, pointer-events does not seem
  34439. // to be honored in children of <text> elements
  34440. // so if we have an anchor, we have to make the
  34441. // whole element respond
  34442. _context.style('pointer-events', 'all');
  34443. }
  34444. exports.positionText(_context);
  34445. if(_callback) _callback.call(_context);
  34446. }
  34447. if(tex) {
  34448. ((gd && gd._promises) || []).push(new Promise(function(resolve) {
  34449. _context.style('display', 'none');
  34450. var fontSize = parseInt(_context.node().style.fontSize, 10);
  34451. var config = {fontSize: fontSize};
  34452. texToSVG(tex[2], config, function(_svgEl, _glyphDefs, _svgBBox) {
  34453. parent.selectAll('svg.' + svgClass).remove();
  34454. parent.selectAll('g.' + svgClass + '-group').remove();
  34455. var newSvg = _svgEl && _svgEl.select('svg');
  34456. if(!newSvg || !newSvg.node()) {
  34457. showText();
  34458. resolve();
  34459. return;
  34460. }
  34461. var mathjaxGroup = parent.append('g')
  34462. .classed(svgClass + '-group', true)
  34463. .attr({
  34464. 'pointer-events': 'none',
  34465. 'data-unformatted': str,
  34466. 'data-math': 'Y'
  34467. });
  34468. mathjaxGroup.node().appendChild(newSvg.node());
  34469. // stitch the glyph defs
  34470. if(_glyphDefs && _glyphDefs.node()) {
  34471. newSvg.node().insertBefore(_glyphDefs.node().cloneNode(true),
  34472. newSvg.node().firstChild);
  34473. }
  34474. newSvg.attr({
  34475. 'class': svgClass,
  34476. height: _svgBBox.height,
  34477. preserveAspectRatio: 'xMinYMin meet'
  34478. })
  34479. .style({overflow: 'visible', 'pointer-events': 'none'});
  34480. var fill = _context.node().style.fill || 'black';
  34481. newSvg.select('g').attr({fill: fill, stroke: fill});
  34482. var newSvgW = getSize(newSvg, 'width');
  34483. var newSvgH = getSize(newSvg, 'height');
  34484. var newX = +_context.attr('x') - newSvgW *
  34485. {start: 0, middle: 0.5, end: 1}[_context.attr('text-anchor') || 'start'];
  34486. // font baseline is about 1/4 fontSize below centerline
  34487. var textHeight = fontSize || getSize(_context, 'height');
  34488. var dy = -textHeight / 4;
  34489. if(svgClass[0] === 'y') {
  34490. mathjaxGroup.attr({
  34491. transform: 'rotate(' + [-90, +_context.attr('x'), +_context.attr('y')] +
  34492. ') translate(' + [-newSvgW / 2, dy - newSvgH / 2] + ')'
  34493. });
  34494. newSvg.attr({x: +_context.attr('x'), y: +_context.attr('y')});
  34495. }
  34496. else if(svgClass[0] === 'l') {
  34497. newSvg.attr({x: _context.attr('x'), y: dy - (newSvgH / 2)});
  34498. }
  34499. else if(svgClass[0] === 'a' && svgClass.indexOf('atitle') !== 0) {
  34500. newSvg.attr({x: 0, y: dy});
  34501. }
  34502. else {
  34503. newSvg.attr({x: newX, y: (+_context.attr('y') + dy - newSvgH / 2)});
  34504. }
  34505. if(_callback) _callback.call(_context, mathjaxGroup);
  34506. resolve(mathjaxGroup);
  34507. });
  34508. }));
  34509. }
  34510. else showText();
  34511. return _context;
  34512. };
  34513. // MathJax
  34514. var LT_MATCH = /(<|&lt;|&#60;)/g;
  34515. var GT_MATCH = /(>|&gt;|&#62;)/g;
  34516. function cleanEscapesForTex(s) {
  34517. return s.replace(LT_MATCH, '\\lt ')
  34518. .replace(GT_MATCH, '\\gt ');
  34519. }
  34520. function texToSVG(_texString, _config, _callback) {
  34521. var originalRenderer,
  34522. originalConfig,
  34523. originalProcessSectionDelay,
  34524. tmpDiv;
  34525. MathJax.Hub.Queue(
  34526. function() {
  34527. originalConfig = Lib.extendDeepAll({}, MathJax.Hub.config);
  34528. originalProcessSectionDelay = MathJax.Hub.processSectionDelay;
  34529. if(MathJax.Hub.processSectionDelay !== undefined) {
  34530. // MathJax 2.5+
  34531. MathJax.Hub.processSectionDelay = 0;
  34532. }
  34533. return MathJax.Hub.Config({
  34534. messageStyle: 'none',
  34535. tex2jax: {
  34536. inlineMath: [['$', '$'], ['\\(', '\\)']]
  34537. },
  34538. displayAlign: 'left',
  34539. });
  34540. },
  34541. function() {
  34542. // Get original renderer
  34543. originalRenderer = MathJax.Hub.config.menuSettings.renderer;
  34544. if(originalRenderer !== 'SVG') {
  34545. return MathJax.Hub.setRenderer('SVG');
  34546. }
  34547. },
  34548. function() {
  34549. var randomID = 'math-output-' + Lib.randstr({}, 64);
  34550. tmpDiv = d3.select('body').append('div')
  34551. .attr({id: randomID})
  34552. .style({visibility: 'hidden', position: 'absolute'})
  34553. .style({'font-size': _config.fontSize + 'px'})
  34554. .text(cleanEscapesForTex(_texString));
  34555. return MathJax.Hub.Typeset(tmpDiv.node());
  34556. },
  34557. function() {
  34558. var glyphDefs = d3.select('body').select('#MathJax_SVG_glyphs');
  34559. if(tmpDiv.select('.MathJax_SVG').empty() || !tmpDiv.select('svg').node()) {
  34560. Lib.log('There was an error in the tex syntax.', _texString);
  34561. _callback();
  34562. }
  34563. else {
  34564. var svgBBox = tmpDiv.select('svg').node().getBoundingClientRect();
  34565. _callback(tmpDiv.select('.MathJax_SVG'), glyphDefs, svgBBox);
  34566. }
  34567. tmpDiv.remove();
  34568. if(originalRenderer !== 'SVG') {
  34569. return MathJax.Hub.setRenderer(originalRenderer);
  34570. }
  34571. },
  34572. function() {
  34573. if(originalProcessSectionDelay !== undefined) {
  34574. MathJax.Hub.processSectionDelay = originalProcessSectionDelay;
  34575. }
  34576. return MathJax.Hub.Config(originalConfig);
  34577. });
  34578. }
  34579. var TAG_STYLES = {
  34580. // would like to use baseline-shift for sub/sup but FF doesn't support it
  34581. // so we need to use dy along with the uber hacky shift-back-to
  34582. // baseline below
  34583. sup: 'font-size:70%',
  34584. sub: 'font-size:70%',
  34585. b: 'font-weight:bold',
  34586. i: 'font-style:italic',
  34587. a: 'cursor:pointer',
  34588. span: '',
  34589. em: 'font-style:italic;font-weight:bold'
  34590. };
  34591. // baseline shifts for sub and sup
  34592. var SHIFT_DY = {
  34593. sub: '0.3em',
  34594. sup: '-0.6em'
  34595. };
  34596. // reset baseline by adding a tspan (empty except for a zero-width space)
  34597. // with dy of -70% * SHIFT_DY (because font-size=70%)
  34598. var RESET_DY = {
  34599. sub: '-0.21em',
  34600. sup: '0.42em'
  34601. };
  34602. var ZERO_WIDTH_SPACE = '\u200b';
  34603. /*
  34604. * Whitelist of protocols in user-supplied urls. Mostly we want to avoid javascript
  34605. * and related attack vectors. The empty items are there for IE, that in various
  34606. * versions treats relative paths as having different flavors of no protocol, while
  34607. * other browsers have these explicitly inherit the protocol of the page they're in.
  34608. */
  34609. var PROTOCOLS = ['http:', 'https:', 'mailto:', '', undefined, ':'];
  34610. var NEWLINES = /(\r\n?|\n)/g;
  34611. var SPLIT_TAGS = /(<[^<>]*>)/;
  34612. var ONE_TAG = /<(\/?)([^ >]*)(\s+(.*))?>/i;
  34613. var BR_TAG = /<br(\s+.*)?>/i;
  34614. /*
  34615. * style and href: pull them out of either single or double quotes. Also
  34616. * - target: (_blank|_self|_parent|_top|framename)
  34617. * note that you can't use target to get a popup but if you use popup,
  34618. * a `framename` will be passed along as the name of the popup window.
  34619. * per the spec, cannot contain whitespace.
  34620. * for backward compatibility we default to '_blank'
  34621. * - popup: a custom one for us to enable popup (new window) links. String
  34622. * for window.open -> strWindowFeatures, like 'menubar=yes,width=500,height=550'
  34623. * note that at least in Chrome, you need to give at least one property
  34624. * in this string or the page will open in a new tab anyway. We follow this
  34625. * convention and will not make a popup if this string is empty.
  34626. * per the spec, cannot contain whitespace.
  34627. *
  34628. * Because we hack in other attributes with style (sub & sup), drop any trailing
  34629. * semicolon in user-supplied styles so we can consistently append the tag-dependent style
  34630. *
  34631. * These are for tag attributes; Chrome anyway will convert entities in
  34632. * attribute values, but not in attribute names
  34633. * you can test this by for example:
  34634. * > p = document.createElement('p')
  34635. * > p.innerHTML = '<span styl&#x65;="font-color:r&#x65;d;">Hi</span>'
  34636. * > p.innerHTML
  34637. * <- '<span styl&#x65;="font-color:red;">Hi</span>'
  34638. */
  34639. var STYLEMATCH = /(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i;
  34640. var HREFMATCH = /(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i;
  34641. var TARGETMATCH = /(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i;
  34642. var POPUPMATCH = /(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i;
  34643. // dedicated matcher for these quoted regexes, that can return their results
  34644. // in two different places
  34645. function getQuotedMatch(_str, re) {
  34646. if(!_str) return null;
  34647. var match = _str.match(re);
  34648. var result = match && (match[3] || match[4]);
  34649. return result && convertEntities(result);
  34650. }
  34651. var COLORMATCH = /(^|;)\s*color:/;
  34652. /**
  34653. * Strip string of tags
  34654. *
  34655. * @param {string} _str : input string
  34656. * @param {object} opts :
  34657. * - maxLen {number} max length of output string
  34658. * - allowedTags {array} list of pseudo-html tags to NOT strip
  34659. * @return {string}
  34660. */
  34661. exports.plainText = function(_str, opts) {
  34662. opts = opts || {};
  34663. var len = (opts.len !== undefined && opts.len !== -1) ? opts.len : Infinity;
  34664. var allowedTags = opts.allowedTags !== undefined ? opts.allowedTags : ['br'];
  34665. var ellipsis = '...';
  34666. var eLen = ellipsis.length;
  34667. var oldParts = _str.split(SPLIT_TAGS);
  34668. var newParts = [];
  34669. var prevTag = '';
  34670. var l = 0;
  34671. for(var i = 0; i < oldParts.length; i++) {
  34672. var p = oldParts[i];
  34673. var match = p.match(ONE_TAG);
  34674. var tagType = match && match[2].toLowerCase();
  34675. if(tagType) {
  34676. // N.B. tags do not count towards string length
  34677. if(allowedTags.indexOf(tagType) !== -1) {
  34678. newParts.push(p);
  34679. prevTag = tagType;
  34680. }
  34681. } else {
  34682. var pLen = p.length;
  34683. if((l + pLen) < len) {
  34684. newParts.push(p);
  34685. l += pLen;
  34686. } else if(l < len) {
  34687. var pLen2 = len - l;
  34688. if(prevTag && (prevTag !== 'br' || pLen2 <= eLen || pLen <= eLen)) {
  34689. newParts.pop();
  34690. }
  34691. if(len > eLen) {
  34692. newParts.push(p.substr(0, pLen2 - eLen) + ellipsis);
  34693. } else {
  34694. newParts.push(p.substr(0, pLen2));
  34695. }
  34696. break;
  34697. }
  34698. prevTag = '';
  34699. }
  34700. }
  34701. return newParts.join('');
  34702. };
  34703. /*
  34704. * N.B. HTML entities are listed without the leading '&' and trailing ';'
  34705. * https://www.freeformatter.com/html-entities.html
  34706. *
  34707. * FWIW if we wanted to support the full set, it has 2261 entries:
  34708. * https://www.w3.org/TR/html5/entities.json
  34709. * though I notice that some of these are duplicates and/or are missing ";"
  34710. * eg: "&amp;", "&amp", "&AMP;", and "&AMP" all map to "&"
  34711. * We no longer need to include numeric entities here, these are now handled
  34712. * by String.fromCodePoint/fromCharCode
  34713. *
  34714. * Anyway the only ones that are really important to allow are the HTML special
  34715. * chars <, >, and &, because these ones can trigger special processing if not
  34716. * replaced by the corresponding entity.
  34717. */
  34718. var entityToUnicode = {
  34719. mu: 'μ',
  34720. amp: '&',
  34721. lt: '<',
  34722. gt: '>',
  34723. nbsp: ' ',
  34724. times: '×',
  34725. plusmn: '±',
  34726. deg: '°'
  34727. };
  34728. // NOTE: in general entities can contain uppercase too (so [a-zA-Z]) but all the
  34729. // ones we support use only lowercase. If we ever change that, update the regex.
  34730. var ENTITY_MATCH = /&(#\d+|#x[\da-fA-F]+|[a-z]+);/g;
  34731. function convertEntities(_str) {
  34732. return _str.replace(ENTITY_MATCH, function(fullMatch, innerMatch) {
  34733. var outChar;
  34734. if(innerMatch.charAt(0) === '#') {
  34735. // cannot use String.fromCodePoint in IE
  34736. outChar = fromCodePoint(
  34737. innerMatch.charAt(1) === 'x' ?
  34738. parseInt(innerMatch.substr(2), 16) :
  34739. parseInt(innerMatch.substr(1), 10)
  34740. );
  34741. }
  34742. else outChar = entityToUnicode[innerMatch];
  34743. // as in regular HTML, if we didn't decode the entity just
  34744. // leave the raw text in place.
  34745. return outChar || fullMatch;
  34746. });
  34747. }
  34748. exports.convertEntities = convertEntities;
  34749. function fromCodePoint(code) {
  34750. // Don't allow overflow. In Chrome this turns into � but I feel like it's
  34751. // more useful to just not convert it at all.
  34752. if(code > 0x10FFFF) return;
  34753. var stringFromCodePoint = String.fromCodePoint;
  34754. if(stringFromCodePoint) return stringFromCodePoint(code);
  34755. // IE doesn't have String.fromCodePoint
  34756. // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCodePoint
  34757. var stringFromCharCode = String.fromCharCode;
  34758. if(code <= 0xFFFF) return stringFromCharCode(code);
  34759. return stringFromCharCode(
  34760. (code >> 10) + 0xD7C0,
  34761. (code % 0x400) + 0xDC00
  34762. );
  34763. }
  34764. /*
  34765. * buildSVGText: convert our pseudo-html into SVG tspan elements, and attach these
  34766. * to containerNode
  34767. *
  34768. * @param {svg text element} containerNode: the <text> node to insert this text into
  34769. * @param {string} str: the pseudo-html string to convert to svg
  34770. *
  34771. * @returns {bool}: does the result contain any links? We need to handle the text element
  34772. * somewhat differently if it does, so just keep track of this when it happens.
  34773. */
  34774. function buildSVGText(containerNode, str) {
  34775. /*
  34776. * Normalize behavior between IE and others wrt newlines and whitespace:pre
  34777. * this combination makes IE barf https://github.com/plotly/plotly.js/issues/746
  34778. * Chrome and FF display \n, \r, or \r\n as a space in this mode.
  34779. * I feel like at some point we turned these into <br> but currently we don't so
  34780. * I'm just going to cement what we do now in Chrome and FF
  34781. */
  34782. str = str.replace(NEWLINES, ' ');
  34783. var hasLink = false;
  34784. // as we're building the text, keep track of what elements we're nested inside
  34785. // nodeStack will be an array of {node, type, style, href, target, popup}
  34786. // where only type: 'a' gets the last 3 and node is only added when it's created
  34787. var nodeStack = [];
  34788. var currentNode;
  34789. var currentLine = -1;
  34790. function newLine() {
  34791. currentLine++;
  34792. var lineNode = document.createElementNS(xmlnsNamespaces.svg, 'tspan');
  34793. d3.select(lineNode).attr({
  34794. class: 'line',
  34795. dy: (currentLine * LINE_SPACING) + 'em'
  34796. });
  34797. containerNode.appendChild(lineNode);
  34798. currentNode = lineNode;
  34799. var oldNodeStack = nodeStack;
  34800. nodeStack = [{node: lineNode}];
  34801. if(oldNodeStack.length > 1) {
  34802. for(var i = 1; i < oldNodeStack.length; i++) {
  34803. enterNode(oldNodeStack[i]);
  34804. }
  34805. }
  34806. }
  34807. function enterNode(nodeSpec) {
  34808. var type = nodeSpec.type;
  34809. var nodeAttrs = {};
  34810. var nodeType;
  34811. if(type === 'a') {
  34812. nodeType = 'a';
  34813. var target = nodeSpec.target;
  34814. var href = nodeSpec.href;
  34815. var popup = nodeSpec.popup;
  34816. if(href) {
  34817. nodeAttrs = {
  34818. 'xlink:xlink:show': (target === '_blank' || target.charAt(0) !== '_') ? 'new' : 'replace',
  34819. target: target,
  34820. 'xlink:xlink:href': href
  34821. };
  34822. if(popup) {
  34823. // security: href and target are not inserted as code but
  34824. // as attributes. popup is, but limited to /[A-Za-z0-9_=,]/
  34825. nodeAttrs.onclick = 'window.open(this.href.baseVal,this.target.baseVal,"' +
  34826. popup + '");return false;';
  34827. }
  34828. }
  34829. }
  34830. else nodeType = 'tspan';
  34831. if(nodeSpec.style) nodeAttrs.style = nodeSpec.style;
  34832. var newNode = document.createElementNS(xmlnsNamespaces.svg, nodeType);
  34833. if(type === 'sup' || type === 'sub') {
  34834. addTextNode(currentNode, ZERO_WIDTH_SPACE);
  34835. currentNode.appendChild(newNode);
  34836. var resetter = document.createElementNS(xmlnsNamespaces.svg, 'tspan');
  34837. addTextNode(resetter, ZERO_WIDTH_SPACE);
  34838. d3.select(resetter).attr('dy', RESET_DY[type]);
  34839. nodeAttrs.dy = SHIFT_DY[type];
  34840. currentNode.appendChild(newNode);
  34841. currentNode.appendChild(resetter);
  34842. }
  34843. else {
  34844. currentNode.appendChild(newNode);
  34845. }
  34846. d3.select(newNode).attr(nodeAttrs);
  34847. currentNode = nodeSpec.node = newNode;
  34848. nodeStack.push(nodeSpec);
  34849. }
  34850. function addTextNode(node, text) {
  34851. node.appendChild(document.createTextNode(text));
  34852. }
  34853. function exitNode(type) {
  34854. // A bare closing tag can't close the root node. If we encounter this it
  34855. // means there's an extra closing tag that can just be ignored:
  34856. if(nodeStack.length === 1) {
  34857. Lib.log('Ignoring unexpected end tag </' + type + '>.', str);
  34858. return;
  34859. }
  34860. var innerNode = nodeStack.pop();
  34861. if(type !== innerNode.type) {
  34862. Lib.log('Start tag <' + innerNode.type + '> doesnt match end tag <' +
  34863. type + '>. Pretending it did match.', str);
  34864. }
  34865. currentNode = nodeStack[nodeStack.length - 1].node;
  34866. }
  34867. var hasLines = BR_TAG.test(str);
  34868. if(hasLines) newLine();
  34869. else {
  34870. currentNode = containerNode;
  34871. nodeStack = [{node: containerNode}];
  34872. }
  34873. var parts = str.split(SPLIT_TAGS);
  34874. for(var i = 0; i < parts.length; i++) {
  34875. var parti = parts[i];
  34876. var match = parti.match(ONE_TAG);
  34877. var tagType = match && match[2].toLowerCase();
  34878. var tagStyle = TAG_STYLES[tagType];
  34879. if(tagType === 'br') {
  34880. newLine();
  34881. }
  34882. else if(tagStyle === undefined) {
  34883. addTextNode(currentNode, convertEntities(parti));
  34884. }
  34885. else {
  34886. // tag - open or close
  34887. if(match[1]) {
  34888. exitNode(tagType);
  34889. }
  34890. else {
  34891. var extra = match[4];
  34892. var nodeSpec = {type: tagType};
  34893. // now add style, from both the tag name and any extra css
  34894. // Most of the svg css that users will care about is just like html,
  34895. // but font color is different (uses fill). Let our users ignore this.
  34896. var css = getQuotedMatch(extra, STYLEMATCH);
  34897. if(css) {
  34898. css = css.replace(COLORMATCH, '$1 fill:');
  34899. if(tagStyle) css += ';' + tagStyle;
  34900. }
  34901. else if(tagStyle) css = tagStyle;
  34902. if(css) nodeSpec.style = css;
  34903. if(tagType === 'a') {
  34904. hasLink = true;
  34905. var href = getQuotedMatch(extra, HREFMATCH);
  34906. if(href) {
  34907. // check safe protocols
  34908. var dummyAnchor = document.createElement('a');
  34909. dummyAnchor.href = href;
  34910. if(PROTOCOLS.indexOf(dummyAnchor.protocol) !== -1) {
  34911. // Decode href to allow both already encoded and not encoded
  34912. // URIs. Without decoding prior encoding, an already encoded
  34913. // URI would be encoded twice producing a semantically different URI.
  34914. nodeSpec.href = encodeURI(decodeURI(href));
  34915. nodeSpec.target = getQuotedMatch(extra, TARGETMATCH) || '_blank';
  34916. nodeSpec.popup = getQuotedMatch(extra, POPUPMATCH);
  34917. }
  34918. }
  34919. }
  34920. enterNode(nodeSpec);
  34921. }
  34922. }
  34923. }
  34924. return hasLink;
  34925. }
  34926. exports.lineCount = function lineCount(s) {
  34927. return s.selectAll('tspan.line').size() || 1;
  34928. };
  34929. exports.positionText = function positionText(s, x, y) {
  34930. return s.each(function() {
  34931. var text = d3.select(this);
  34932. function setOrGet(attr, val) {
  34933. if(val === undefined) {
  34934. val = text.attr(attr);
  34935. if(val === null) {
  34936. text.attr(attr, 0);
  34937. val = 0;
  34938. }
  34939. }
  34940. else text.attr(attr, val);
  34941. return val;
  34942. }
  34943. var thisX = setOrGet('x', x);
  34944. var thisY = setOrGet('y', y);
  34945. if(this.nodeName === 'text') {
  34946. text.selectAll('tspan.line').attr({x: thisX, y: thisY});
  34947. }
  34948. });
  34949. };
  34950. function alignHTMLWith(_base, container, options) {
  34951. var alignH = options.horizontalAlign;
  34952. var alignV = options.verticalAlign || 'top';
  34953. var bRect = _base.node().getBoundingClientRect();
  34954. var cRect = container.node().getBoundingClientRect();
  34955. var thisRect;
  34956. var getTop;
  34957. var getLeft;
  34958. if(alignV === 'bottom') {
  34959. getTop = function() { return bRect.bottom - thisRect.height; };
  34960. } else if(alignV === 'middle') {
  34961. getTop = function() { return bRect.top + (bRect.height - thisRect.height) / 2; };
  34962. } else { // default: top
  34963. getTop = function() { return bRect.top; };
  34964. }
  34965. if(alignH === 'right') {
  34966. getLeft = function() { return bRect.right - thisRect.width; };
  34967. } else if(alignH === 'center') {
  34968. getLeft = function() { return bRect.left + (bRect.width - thisRect.width) / 2; };
  34969. } else { // default: left
  34970. getLeft = function() { return bRect.left; };
  34971. }
  34972. return function() {
  34973. thisRect = this.node().getBoundingClientRect();
  34974. this.style({
  34975. top: (getTop() - cRect.top) + 'px',
  34976. left: (getLeft() - cRect.left) + 'px',
  34977. 'z-index': 1000
  34978. });
  34979. return this;
  34980. };
  34981. }
  34982. /*
  34983. * Editable title
  34984. * @param {d3.selection} context: the element being edited. Normally text,
  34985. * but if it isn't, you should provide the styling options
  34986. * @param {object} options:
  34987. * @param {div} options.gd: graphDiv
  34988. * @param {d3.selection} options.delegate: item to bind events to if not this
  34989. * @param {boolean} options.immediate: start editing now (true) or on click (false, default)
  34990. * @param {string} options.fill: font color if not as shown
  34991. * @param {string} options.background: background color if not as shown
  34992. * @param {string} options.text: initial text, if not as shown
  34993. * @param {string} options.horizontalAlign: alignment of the edit box wrt. the bound element
  34994. * @param {string} options.verticalAlign: alignment of the edit box wrt. the bound element
  34995. */
  34996. exports.makeEditable = function(context, options) {
  34997. var gd = options.gd;
  34998. var _delegate = options.delegate;
  34999. var dispatch = d3.dispatch('edit', 'input', 'cancel');
  35000. var handlerElement = _delegate || context;
  35001. context.style({'pointer-events': _delegate ? 'none' : 'all'});
  35002. if(context.size() !== 1) throw new Error('boo');
  35003. function handleClick() {
  35004. appendEditable();
  35005. context.style({opacity: 0});
  35006. // also hide any mathjax svg
  35007. var svgClass = handlerElement.attr('class');
  35008. var mathjaxClass;
  35009. if(svgClass) mathjaxClass = '.' + svgClass.split(' ')[0] + '-math-group';
  35010. else mathjaxClass = '[class*=-math-group]';
  35011. if(mathjaxClass) {
  35012. d3.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0});
  35013. }
  35014. }
  35015. function selectElementContents(_el) {
  35016. var el = _el.node();
  35017. var range = document.createRange();
  35018. range.selectNodeContents(el);
  35019. var sel = window.getSelection();
  35020. sel.removeAllRanges();
  35021. sel.addRange(range);
  35022. el.focus();
  35023. }
  35024. function appendEditable() {
  35025. var plotDiv = d3.select(gd);
  35026. var container = plotDiv.select('.svg-container');
  35027. var div = container.append('div');
  35028. var cStyle = context.node().style;
  35029. var fontSize = parseFloat(cStyle.fontSize || 12);
  35030. var initialText = options.text;
  35031. if(initialText === undefined) initialText = context.attr('data-unformatted');
  35032. div.classed('plugin-editable editable', true)
  35033. .style({
  35034. position: 'absolute',
  35035. 'font-family': cStyle.fontFamily || 'Arial',
  35036. 'font-size': fontSize,
  35037. color: options.fill || cStyle.fill || 'black',
  35038. opacity: 1,
  35039. 'background-color': options.background || 'transparent',
  35040. outline: '#ffffff33 1px solid',
  35041. margin: [-fontSize / 8 + 1, 0, 0, -1].join('px ') + 'px',
  35042. padding: '0',
  35043. 'box-sizing': 'border-box'
  35044. })
  35045. .attr({contenteditable: true})
  35046. .text(initialText)
  35047. .call(alignHTMLWith(context, container, options))
  35048. .on('blur', function() {
  35049. gd._editing = false;
  35050. context.text(this.textContent)
  35051. .style({opacity: 1});
  35052. var svgClass = d3.select(this).attr('class');
  35053. var mathjaxClass;
  35054. if(svgClass) mathjaxClass = '.' + svgClass.split(' ')[0] + '-math-group';
  35055. else mathjaxClass = '[class*=-math-group]';
  35056. if(mathjaxClass) {
  35057. d3.select(context.node().parentNode).select(mathjaxClass).style({opacity: 0});
  35058. }
  35059. var text = this.textContent;
  35060. d3.select(this).transition().duration(0).remove();
  35061. d3.select(document).on('mouseup', null);
  35062. dispatch.edit.call(context, text);
  35063. })
  35064. .on('focus', function() {
  35065. var editDiv = this;
  35066. gd._editing = true;
  35067. d3.select(document).on('mouseup', function() {
  35068. if(d3.event.target === editDiv) return false;
  35069. if(document.activeElement === div.node()) div.node().blur();
  35070. });
  35071. })
  35072. .on('keyup', function() {
  35073. if(d3.event.which === 27) {
  35074. gd._editing = false;
  35075. context.style({opacity: 1});
  35076. d3.select(this)
  35077. .style({opacity: 0})
  35078. .on('blur', function() { return false; })
  35079. .transition().remove();
  35080. dispatch.cancel.call(context, this.textContent);
  35081. }
  35082. else {
  35083. dispatch.input.call(context, this.textContent);
  35084. d3.select(this).call(alignHTMLWith(context, container, options));
  35085. }
  35086. })
  35087. .on('keydown', function() {
  35088. if(d3.event.which === 13) this.blur();
  35089. })
  35090. .call(selectElementContents);
  35091. }
  35092. if(options.immediate) handleClick();
  35093. else handlerElement.on('click', handleClick);
  35094. return d3.rebind(context, dispatch, 'on');
  35095. };
  35096. },{"../constants/alignment":146,"../constants/xmlns_namespaces":150,"../lib":168,"d3":16}],190:[function(_dereq_,module,exports){
  35097. /**
  35098. * Copyright 2012-2019, Plotly, Inc.
  35099. * All rights reserved.
  35100. *
  35101. * This source code is licensed under the MIT license found in the
  35102. * LICENSE file in the root directory of this source tree.
  35103. */
  35104. 'use strict';
  35105. var timerCache = {};
  35106. /**
  35107. * Throttle a callback. `callback` executes synchronously only if
  35108. * more than `minInterval` milliseconds have already elapsed since the latest
  35109. * call (if any). Otherwise we wait until `minInterval` is over and execute the
  35110. * last callback received while waiting.
  35111. * So the first and last events in a train are always executed (eventually)
  35112. * but some of the events in the middle can be dropped.
  35113. *
  35114. * @param {string} id: an identifier to mark events to throttle together
  35115. * @param {number} minInterval: minimum time, in milliseconds, between
  35116. * invocations of `callback`
  35117. * @param {function} callback: the function to throttle. `callback` itself
  35118. * should be a purely synchronous function.
  35119. */
  35120. exports.throttle = function throttle(id, minInterval, callback) {
  35121. var cache = timerCache[id];
  35122. var now = Date.now();
  35123. if(!cache) {
  35124. /*
  35125. * Throw out old items before making a new one, to prevent the cache
  35126. * getting overgrown, for example from old plots that have been replaced.
  35127. * 1 minute age is arbitrary.
  35128. */
  35129. for(var idi in timerCache) {
  35130. if(timerCache[idi].ts < now - 60000) {
  35131. delete timerCache[idi];
  35132. }
  35133. }
  35134. cache = timerCache[id] = {ts: 0, timer: null};
  35135. }
  35136. _clearTimeout(cache);
  35137. function exec() {
  35138. callback();
  35139. cache.ts = Date.now();
  35140. if(cache.onDone) {
  35141. cache.onDone();
  35142. cache.onDone = null;
  35143. }
  35144. }
  35145. if(now > cache.ts + minInterval) {
  35146. exec();
  35147. return;
  35148. }
  35149. cache.timer = setTimeout(function() {
  35150. exec();
  35151. cache.timer = null;
  35152. }, minInterval);
  35153. };
  35154. exports.done = function(id) {
  35155. var cache = timerCache[id];
  35156. if(!cache || !cache.timer) return Promise.resolve();
  35157. return new Promise(function(resolve) {
  35158. var previousOnDone = cache.onDone;
  35159. cache.onDone = function onDone() {
  35160. if(previousOnDone) previousOnDone();
  35161. resolve();
  35162. cache.onDone = null;
  35163. };
  35164. });
  35165. };
  35166. /**
  35167. * Clear the throttle cache for one or all timers
  35168. * @param {optional string} id:
  35169. * if provided, clear just this timer
  35170. * if omitted, clear all timers (mainly useful for testing)
  35171. */
  35172. exports.clear = function(id) {
  35173. if(id) {
  35174. _clearTimeout(timerCache[id]);
  35175. delete timerCache[id];
  35176. }
  35177. else {
  35178. for(var idi in timerCache) exports.clear(idi);
  35179. }
  35180. };
  35181. function _clearTimeout(cache) {
  35182. if(cache && cache.timer !== null) {
  35183. clearTimeout(cache.timer);
  35184. cache.timer = null;
  35185. }
  35186. }
  35187. },{}],191:[function(_dereq_,module,exports){
  35188. /**
  35189. * Copyright 2012-2019, Plotly, Inc.
  35190. * All rights reserved.
  35191. *
  35192. * This source code is licensed under the MIT license found in the
  35193. * LICENSE file in the root directory of this source tree.
  35194. */
  35195. 'use strict';
  35196. var isNumeric = _dereq_('fast-isnumeric');
  35197. /**
  35198. * convert a linear value into a logged value, folding negative numbers into
  35199. * the given range
  35200. */
  35201. module.exports = function toLogRange(val, range) {
  35202. if(val > 0) return Math.log(val) / Math.LN10;
  35203. // move a negative value reference to a log axis - just put the
  35204. // result at the lowest range value on the plot (or if the range also went negative,
  35205. // one millionth of the top of the range)
  35206. var newVal = Math.log(Math.min(range[0], range[1])) / Math.LN10;
  35207. if(!isNumeric(newVal)) newVal = Math.log(Math.max(range[0], range[1])) / Math.LN10 - 6;
  35208. return newVal;
  35209. };
  35210. },{"fast-isnumeric":18}],192:[function(_dereq_,module,exports){
  35211. /**
  35212. * Copyright 2012-2019, Plotly, Inc.
  35213. * All rights reserved.
  35214. *
  35215. * This source code is licensed under the MIT license found in the
  35216. * LICENSE file in the root directory of this source tree.
  35217. */
  35218. 'use strict';
  35219. module.exports = {
  35220. moduleType: 'locale',
  35221. name: 'en-US',
  35222. dictionary: {
  35223. 'Click to enter Colorscale title': 'Click to enter Colorscale title'
  35224. },
  35225. format: {
  35226. date: '%m/%d/%Y'
  35227. }
  35228. };
  35229. },{}],193:[function(_dereq_,module,exports){
  35230. /**
  35231. * Copyright 2012-2019, Plotly, Inc.
  35232. * All rights reserved.
  35233. *
  35234. * This source code is licensed under the MIT license found in the
  35235. * LICENSE file in the root directory of this source tree.
  35236. */
  35237. 'use strict';
  35238. module.exports = {
  35239. moduleType: 'locale',
  35240. name: 'en',
  35241. dictionary: {
  35242. 'Click to enter Colorscale title': 'Click to enter Colourscale title'
  35243. },
  35244. format: {
  35245. days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  35246. shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
  35247. months: [
  35248. 'January', 'February', 'March', 'April', 'May', 'June',
  35249. 'July', 'August', 'September', 'October', 'November', 'December'
  35250. ],
  35251. shortMonths: [
  35252. 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
  35253. 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
  35254. ],
  35255. periods: ['AM', 'PM'],
  35256. dateTime: '%a %b %e %X %Y',
  35257. date: '%d/%m/%Y',
  35258. time: '%H:%M:%S',
  35259. decimal: '.',
  35260. thousands: ',',
  35261. grouping: [3],
  35262. currency: ['$', ''],
  35263. year: '%Y',
  35264. month: '%b %Y',
  35265. dayMonth: '%b %-d',
  35266. dayMonthYear: '%b %-d, %Y'
  35267. }
  35268. };
  35269. },{}],194:[function(_dereq_,module,exports){
  35270. /**
  35271. * Copyright 2012-2019, Plotly, Inc.
  35272. * All rights reserved.
  35273. *
  35274. * This source code is licensed under the MIT license found in the
  35275. * LICENSE file in the root directory of this source tree.
  35276. */
  35277. 'use strict';
  35278. var Registry = _dereq_('../registry');
  35279. /*
  35280. * containerArrayMatch: does this attribute string point into a
  35281. * layout container array?
  35282. *
  35283. * @param {String} astr: an attribute string, like *annotations[2].text*
  35284. *
  35285. * @returns {Object | false} Returns false if `astr` doesn't match a container
  35286. * array. If it does, returns:
  35287. * {array: {String}, index: {Number}, property: {String}}
  35288. * ie the attribute string for the array, the index within the array (or ''
  35289. * if the whole array) and the property within that (or '' if the whole array
  35290. * or the whole object)
  35291. */
  35292. module.exports = function containerArrayMatch(astr) {
  35293. var rootContainers = Registry.layoutArrayContainers;
  35294. var regexpContainers = Registry.layoutArrayRegexes;
  35295. var rootPart = astr.split('[')[0];
  35296. var arrayStr;
  35297. var match;
  35298. // look for regexp matches first, because they may be nested inside root matches
  35299. // eg updatemenus[i].buttons is nested inside updatemenus
  35300. for(var i = 0; i < regexpContainers.length; i++) {
  35301. match = astr.match(regexpContainers[i]);
  35302. if(match && match.index === 0) {
  35303. arrayStr = match[0];
  35304. break;
  35305. }
  35306. }
  35307. // now look for root matches
  35308. if(!arrayStr) arrayStr = rootContainers[rootContainers.indexOf(rootPart)];
  35309. if(!arrayStr) return false;
  35310. var tail = astr.substr(arrayStr.length);
  35311. if(!tail) return {array: arrayStr, index: '', property: ''};
  35312. match = tail.match(/^\[(0|[1-9][0-9]*)\](\.(.+))?$/);
  35313. if(!match) return false;
  35314. return {array: arrayStr, index: Number(match[1]), property: match[3] || ''};
  35315. };
  35316. },{"../registry":257}],195:[function(_dereq_,module,exports){
  35317. /**
  35318. * Copyright 2012-2019, Plotly, Inc.
  35319. * All rights reserved.
  35320. *
  35321. * This source code is licensed under the MIT license found in the
  35322. * LICENSE file in the root directory of this source tree.
  35323. */
  35324. 'use strict';
  35325. var Lib = _dereq_('../lib');
  35326. var extendFlat = Lib.extendFlat;
  35327. var isPlainObject = Lib.isPlainObject;
  35328. var traceOpts = {
  35329. valType: 'flaglist',
  35330. extras: ['none'],
  35331. flags: ['calc', 'clearAxisTypes', 'plot', 'style', 'markerSize', 'colorbars'],
  35332. };
  35333. var layoutOpts = {
  35334. valType: 'flaglist',
  35335. extras: ['none'],
  35336. flags: [
  35337. 'calc', 'plot', 'legend', 'ticks', 'axrange',
  35338. 'layoutstyle', 'modebar', 'camera', 'arraydraw'
  35339. ],
  35340. };
  35341. // flags for inside restyle/relayout include a few extras
  35342. // that shouldn't be used in attributes, to deal with certain
  35343. // combinations and conditionals efficiently
  35344. var traceEditTypeFlags = traceOpts.flags.slice()
  35345. .concat(['fullReplot']);
  35346. var layoutEditTypeFlags = layoutOpts.flags.slice()
  35347. .concat('layoutReplot');
  35348. module.exports = {
  35349. traces: traceOpts,
  35350. layout: layoutOpts,
  35351. /*
  35352. * default (all false) edit flags for restyle (traces)
  35353. * creates a new object each call, so the caller can mutate freely
  35354. */
  35355. traceFlags: function() { return falseObj(traceEditTypeFlags); },
  35356. /*
  35357. * default (all false) edit flags for relayout
  35358. * creates a new object each call, so the caller can mutate freely
  35359. */
  35360. layoutFlags: function() { return falseObj(layoutEditTypeFlags); },
  35361. /*
  35362. * update `flags` with the `editType` values found in `attr`
  35363. */
  35364. update: function(flags, attr) {
  35365. var editType = attr.editType;
  35366. if(editType && editType !== 'none') {
  35367. var editTypeParts = editType.split('+');
  35368. for(var i = 0; i < editTypeParts.length; i++) {
  35369. flags[editTypeParts[i]] = true;
  35370. }
  35371. }
  35372. },
  35373. overrideAll: overrideAll
  35374. };
  35375. function falseObj(keys) {
  35376. var out = {};
  35377. for(var i = 0; i < keys.length; i++) out[keys[i]] = false;
  35378. return out;
  35379. }
  35380. /**
  35381. * For attributes that are largely copied from elsewhere into a plot type that doesn't
  35382. * support partial redraws - overrides the editType field of all attributes in the object
  35383. *
  35384. * @param {object} attrs: the attributes to override. Will not be mutated.
  35385. * @param {string} editTypeOverride: the new editType to use
  35386. * @param {'nested'|'from-root'} overrideContainers:
  35387. * - 'nested' will override editType for nested containers but not the root.
  35388. * - 'from-root' will also override editType of the root container.
  35389. * Containers below the absolute top level (trace or layout root) DO need an
  35390. * editType even if they are not `valObject`s themselves (eg `scatter.marker`)
  35391. * to handle the case where you edit the whole container.
  35392. *
  35393. * @return {object} a new attributes object with `editType` modified as directed
  35394. */
  35395. function overrideAll(attrs, editTypeOverride, overrideContainers) {
  35396. var out = extendFlat({}, attrs);
  35397. for(var key in out) {
  35398. var attr = out[key];
  35399. if(isPlainObject(attr)) {
  35400. out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key);
  35401. }
  35402. }
  35403. if(overrideContainers === 'from-root') out.editType = editTypeOverride;
  35404. return out;
  35405. }
  35406. function overrideOne(attr, editTypeOverride, overrideContainers, key) {
  35407. if(attr.valType) {
  35408. var out = extendFlat({}, attr);
  35409. out.editType = editTypeOverride;
  35410. if(Array.isArray(attr.items)) {
  35411. out.items = new Array(attr.items.length);
  35412. for(var i = 0; i < attr.items.length; i++) {
  35413. out.items[i] = overrideOne(attr.items[i], editTypeOverride, 'from-root');
  35414. }
  35415. }
  35416. return out;
  35417. }
  35418. else {
  35419. // don't provide an editType for the _deprecated container
  35420. return overrideAll(attr, editTypeOverride,
  35421. (key.charAt(0) === '_') ? 'nested' : 'from-root');
  35422. }
  35423. }
  35424. },{"../lib":168}],196:[function(_dereq_,module,exports){
  35425. /**
  35426. * Copyright 2012-2019, Plotly, Inc.
  35427. * All rights reserved.
  35428. *
  35429. * This source code is licensed under the MIT license found in the
  35430. * LICENSE file in the root directory of this source tree.
  35431. */
  35432. 'use strict';
  35433. var isNumeric = _dereq_('fast-isnumeric');
  35434. var m4FromQuat = _dereq_('gl-mat4/fromQuat');
  35435. var Registry = _dereq_('../registry');
  35436. var Lib = _dereq_('../lib');
  35437. var Plots = _dereq_('../plots/plots');
  35438. var AxisIds = _dereq_('../plots/cartesian/axis_ids');
  35439. var cleanId = AxisIds.cleanId;
  35440. var getFromTrace = AxisIds.getFromTrace;
  35441. var Color = _dereq_('../components/color');
  35442. // clear the promise queue if one of them got rejected
  35443. exports.clearPromiseQueue = function(gd) {
  35444. if(Array.isArray(gd._promises) && gd._promises.length > 0) {
  35445. Lib.log('Clearing previous rejected promises from queue.');
  35446. }
  35447. gd._promises = [];
  35448. };
  35449. // make a few changes to the layout right away
  35450. // before it gets used for anything
  35451. // backward compatibility and cleanup of nonstandard options
  35452. exports.cleanLayout = function(layout) {
  35453. var i, j;
  35454. if(!layout) layout = {};
  35455. // cannot have (x|y)axis1, numbering goes axis, axis2, axis3...
  35456. if(layout.xaxis1) {
  35457. if(!layout.xaxis) layout.xaxis = layout.xaxis1;
  35458. delete layout.xaxis1;
  35459. }
  35460. if(layout.yaxis1) {
  35461. if(!layout.yaxis) layout.yaxis = layout.yaxis1;
  35462. delete layout.yaxis1;
  35463. }
  35464. if(layout.scene1) {
  35465. if(!layout.scene) layout.scene = layout.scene1;
  35466. delete layout.scene1;
  35467. }
  35468. var axisAttrRegex = (Plots.subplotsRegistry.cartesian || {}).attrRegex;
  35469. var polarAttrRegex = (Plots.subplotsRegistry.polar || {}).attrRegex;
  35470. var ternaryAttrRegex = (Plots.subplotsRegistry.ternary || {}).attrRegex;
  35471. var sceneAttrRegex = (Plots.subplotsRegistry.gl3d || {}).attrRegex;
  35472. var keys = Object.keys(layout);
  35473. for(i = 0; i < keys.length; i++) {
  35474. var key = keys[i];
  35475. // modifications to cartesian axes
  35476. if(axisAttrRegex && axisAttrRegex.test(key)) {
  35477. var ax = layout[key];
  35478. if(ax.anchor && ax.anchor !== 'free') {
  35479. ax.anchor = cleanId(ax.anchor);
  35480. }
  35481. if(ax.overlaying) ax.overlaying = cleanId(ax.overlaying);
  35482. // old method of axis type - isdate and islog (before category existed)
  35483. if(!ax.type) {
  35484. if(ax.isdate) ax.type = 'date';
  35485. else if(ax.islog) ax.type = 'log';
  35486. else if(ax.isdate === false && ax.islog === false) ax.type = 'linear';
  35487. }
  35488. if(ax.autorange === 'withzero' || ax.autorange === 'tozero') {
  35489. ax.autorange = true;
  35490. ax.rangemode = 'tozero';
  35491. }
  35492. delete ax.islog;
  35493. delete ax.isdate;
  35494. delete ax.categories; // replaced by _categories
  35495. // prune empty domain arrays made before the new nestedProperty
  35496. if(emptyContainer(ax, 'domain')) delete ax.domain;
  35497. // autotick -> tickmode
  35498. if(ax.autotick !== undefined) {
  35499. if(ax.tickmode === undefined) {
  35500. ax.tickmode = ax.autotick ? 'auto' : 'linear';
  35501. }
  35502. delete ax.autotick;
  35503. }
  35504. cleanTitle(ax);
  35505. }
  35506. // modifications for polar
  35507. else if(polarAttrRegex && polarAttrRegex.test(key)) {
  35508. var polar = layout[key];
  35509. cleanTitle(polar.radialaxis);
  35510. }
  35511. // modifications for ternary
  35512. else if(ternaryAttrRegex && ternaryAttrRegex.test(key)) {
  35513. var ternary = layout[key];
  35514. cleanTitle(ternary.aaxis);
  35515. cleanTitle(ternary.baxis);
  35516. cleanTitle(ternary.caxis);
  35517. }
  35518. // modifications for 3D scenes
  35519. else if(sceneAttrRegex && sceneAttrRegex.test(key)) {
  35520. var scene = layout[key];
  35521. // clean old Camera coords
  35522. var cameraposition = scene.cameraposition;
  35523. if(Array.isArray(cameraposition) && cameraposition[0].length === 4) {
  35524. var rotation = cameraposition[0];
  35525. var center = cameraposition[1];
  35526. var radius = cameraposition[2];
  35527. var mat = m4FromQuat([], rotation);
  35528. var eye = [];
  35529. for(j = 0; j < 3; ++j) {
  35530. eye[j] = center[j] + radius * mat[2 + 4 * j];
  35531. }
  35532. scene.camera = {
  35533. eye: {x: eye[0], y: eye[1], z: eye[2]},
  35534. center: {x: center[0], y: center[1], z: center[2]},
  35535. up: {x: 0, y: 0, z: 1} // we just ignore calculating camera z up in this case
  35536. };
  35537. delete scene.cameraposition;
  35538. }
  35539. // clean axis titles
  35540. cleanTitle(scene.xaxis);
  35541. cleanTitle(scene.yaxis);
  35542. cleanTitle(scene.zaxis);
  35543. }
  35544. }
  35545. var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0;
  35546. for(i = 0; i < annotationsLen; i++) {
  35547. var ann = layout.annotations[i];
  35548. if(!Lib.isPlainObject(ann)) continue;
  35549. if(ann.ref) {
  35550. if(ann.ref === 'paper') {
  35551. ann.xref = 'paper';
  35552. ann.yref = 'paper';
  35553. }
  35554. else if(ann.ref === 'data') {
  35555. ann.xref = 'x';
  35556. ann.yref = 'y';
  35557. }
  35558. delete ann.ref;
  35559. }
  35560. cleanAxRef(ann, 'xref');
  35561. cleanAxRef(ann, 'yref');
  35562. }
  35563. var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0;
  35564. for(i = 0; i < shapesLen; i++) {
  35565. var shape = layout.shapes[i];
  35566. if(!Lib.isPlainObject(shape)) continue;
  35567. cleanAxRef(shape, 'xref');
  35568. cleanAxRef(shape, 'yref');
  35569. }
  35570. var legend = layout.legend;
  35571. if(legend) {
  35572. // check for old-style legend positioning (x or y is +/- 100)
  35573. if(legend.x > 3) {
  35574. legend.x = 1.02;
  35575. legend.xanchor = 'left';
  35576. }
  35577. else if(legend.x < -2) {
  35578. legend.x = -0.02;
  35579. legend.xanchor = 'right';
  35580. }
  35581. if(legend.y > 3) {
  35582. legend.y = 1.02;
  35583. legend.yanchor = 'bottom';
  35584. }
  35585. else if(legend.y < -2) {
  35586. legend.y = -0.02;
  35587. legend.yanchor = 'top';
  35588. }
  35589. }
  35590. // clean plot title
  35591. cleanTitle(layout);
  35592. /*
  35593. * Moved from rotate -> orbit for dragmode
  35594. */
  35595. if(layout.dragmode === 'rotate') layout.dragmode = 'orbit';
  35596. // sanitize rgb(fractions) and rgba(fractions) that old tinycolor
  35597. // supported, but new tinycolor does not because they're not valid css
  35598. Color.clean(layout);
  35599. // clean the layout container in layout.template
  35600. if(layout.template && layout.template.layout) {
  35601. exports.cleanLayout(layout.template.layout);
  35602. }
  35603. return layout;
  35604. };
  35605. function cleanAxRef(container, attr) {
  35606. var valIn = container[attr];
  35607. var axLetter = attr.charAt(0);
  35608. if(valIn && valIn !== 'paper') {
  35609. container[attr] = cleanId(valIn, axLetter);
  35610. }
  35611. }
  35612. /**
  35613. * Cleans up old title attribute structure (flat) in favor of the new one (nested).
  35614. *
  35615. * @param {Object} titleContainer - an object potentially including deprecated title attributes
  35616. */
  35617. function cleanTitle(titleContainer) {
  35618. if(titleContainer) {
  35619. // title -> title.text
  35620. // (although title used to be a string attribute,
  35621. // numbers are accepted as well)
  35622. if(typeof titleContainer.title === 'string' || typeof titleContainer.title === 'number') {
  35623. titleContainer.title = {
  35624. text: titleContainer.title
  35625. };
  35626. }
  35627. rewireAttr('titlefont', 'font');
  35628. rewireAttr('titleposition', 'position');
  35629. rewireAttr('titleside', 'side');
  35630. rewireAttr('titleoffset', 'offset');
  35631. }
  35632. function rewireAttr(oldAttrName, newAttrName) {
  35633. var oldAttrSet = titleContainer[oldAttrName];
  35634. var newAttrSet = titleContainer.title && titleContainer.title[newAttrName];
  35635. if(oldAttrSet && !newAttrSet) {
  35636. // Ensure title object exists
  35637. if(!titleContainer.title) {
  35638. titleContainer.title = {};
  35639. }
  35640. titleContainer.title[newAttrName] = titleContainer[oldAttrName];
  35641. delete titleContainer[oldAttrName];
  35642. }
  35643. }
  35644. }
  35645. /*
  35646. * cleanData: Make a few changes to the data for backward compatibility
  35647. * before it gets used for anything. Modifies the data traces users provide.
  35648. *
  35649. * Important: if you're going to add something here that modifies a data array,
  35650. * update it in place so the new array === the old one.
  35651. */
  35652. exports.cleanData = function(data) {
  35653. for(var tracei = 0; tracei < data.length; tracei++) {
  35654. var trace = data[tracei];
  35655. var i;
  35656. // use xbins to bin data in x, and ybins to bin data in y
  35657. if(trace.type === 'histogramy' && 'xbins' in trace && !('ybins' in trace)) {
  35658. trace.ybins = trace.xbins;
  35659. delete trace.xbins;
  35660. }
  35661. // error_y.opacity is obsolete - merge into color
  35662. if(trace.error_y && 'opacity' in trace.error_y) {
  35663. var dc = Color.defaults;
  35664. var yeColor = trace.error_y.color || (Registry.traceIs(trace, 'bar') ?
  35665. Color.defaultLine :
  35666. dc[tracei % dc.length]);
  35667. trace.error_y.color = Color.addOpacity(
  35668. Color.rgb(yeColor),
  35669. Color.opacity(yeColor) * trace.error_y.opacity);
  35670. delete trace.error_y.opacity;
  35671. }
  35672. // convert bardir to orientation, and put the data into
  35673. // the axes it's eventually going to be used with
  35674. if('bardir' in trace) {
  35675. if(trace.bardir === 'h' && (Registry.traceIs(trace, 'bar') ||
  35676. trace.type.substr(0, 9) === 'histogram')) {
  35677. trace.orientation = 'h';
  35678. exports.swapXYData(trace);
  35679. }
  35680. delete trace.bardir;
  35681. }
  35682. // now we have only one 1D histogram type, and whether
  35683. // it uses x or y data depends on trace.orientation
  35684. if(trace.type === 'histogramy') exports.swapXYData(trace);
  35685. if(trace.type === 'histogramx' || trace.type === 'histogramy') {
  35686. trace.type = 'histogram';
  35687. }
  35688. // scl->scale, reversescl->reversescale
  35689. if('scl' in trace && !('colorscale' in trace)) {
  35690. trace.colorscale = trace.scl;
  35691. delete trace.scl;
  35692. }
  35693. if('reversescl' in trace && !('reversescale' in trace)) {
  35694. trace.reversescale = trace.reversescl;
  35695. delete trace.reversescl;
  35696. }
  35697. // axis ids x1 -> x, y1-> y
  35698. if(trace.xaxis) trace.xaxis = cleanId(trace.xaxis, 'x');
  35699. if(trace.yaxis) trace.yaxis = cleanId(trace.yaxis, 'y');
  35700. // scene ids scene1 -> scene
  35701. if(Registry.traceIs(trace, 'gl3d') && trace.scene) {
  35702. trace.scene = Plots.subplotsRegistry.gl3d.cleanId(trace.scene);
  35703. }
  35704. if(!Registry.traceIs(trace, 'pie') && !Registry.traceIs(trace, 'bar')) {
  35705. if(Array.isArray(trace.textposition)) {
  35706. for(i = 0; i < trace.textposition.length; i++) {
  35707. trace.textposition[i] = cleanTextPosition(trace.textposition[i]);
  35708. }
  35709. }
  35710. else if(trace.textposition) {
  35711. trace.textposition = cleanTextPosition(trace.textposition);
  35712. }
  35713. }
  35714. // fix typo in colorscale definition
  35715. var _module = Registry.getModule(trace);
  35716. if(_module && _module.colorbar) {
  35717. var containerName = _module.colorbar.container;
  35718. var container = containerName ? trace[containerName] : trace;
  35719. if(container && container.colorscale) {
  35720. if(container.colorscale === 'YIGnBu') container.colorscale = 'YlGnBu';
  35721. if(container.colorscale === 'YIOrRd') container.colorscale = 'YlOrRd';
  35722. }
  35723. }
  35724. // fix typo in surface 'highlight*' definitions
  35725. if(trace.type === 'surface' && Lib.isPlainObject(trace.contours)) {
  35726. var dims = ['x', 'y', 'z'];
  35727. for(i = 0; i < dims.length; i++) {
  35728. var opts = trace.contours[dims[i]];
  35729. if(!Lib.isPlainObject(opts)) continue;
  35730. if(opts.highlightColor) {
  35731. opts.highlightcolor = opts.highlightColor;
  35732. delete opts.highlightColor;
  35733. }
  35734. if(opts.highlightWidth) {
  35735. opts.highlightwidth = opts.highlightWidth;
  35736. delete opts.highlightWidth;
  35737. }
  35738. }
  35739. }
  35740. // fixes from converting finance from transforms to real trace types
  35741. if(trace.type === 'candlestick' || trace.type === 'ohlc') {
  35742. var increasingShowlegend = (trace.increasing || {}).showlegend !== false;
  35743. var decreasingShowlegend = (trace.decreasing || {}).showlegend !== false;
  35744. var increasingName = cleanFinanceDir(trace.increasing);
  35745. var decreasingName = cleanFinanceDir(trace.decreasing);
  35746. // now figure out something smart to do with the separate direction
  35747. // names we removed
  35748. if((increasingName !== false) && (decreasingName !== false)) {
  35749. // both sub-names existed: base name previously had no effect
  35750. // so ignore it and try to find a shared part of the sub-names
  35751. var newName = commonPrefix(
  35752. increasingName, decreasingName,
  35753. increasingShowlegend, decreasingShowlegend
  35754. );
  35755. // if no common part, leave whatever name was (or wasn't) there
  35756. if(newName) trace.name = newName;
  35757. }
  35758. else if((increasingName || decreasingName) && !trace.name) {
  35759. // one sub-name existed but not the base name - just use the sub-name
  35760. trace.name = increasingName || decreasingName;
  35761. }
  35762. }
  35763. // transforms backward compatibility fixes
  35764. if(Array.isArray(trace.transforms)) {
  35765. var transforms = trace.transforms;
  35766. for(i = 0; i < transforms.length; i++) {
  35767. var transform = transforms[i];
  35768. if(!Lib.isPlainObject(transform)) continue;
  35769. switch(transform.type) {
  35770. case 'filter':
  35771. if(transform.filtersrc) {
  35772. transform.target = transform.filtersrc;
  35773. delete transform.filtersrc;
  35774. }
  35775. if(transform.calendar) {
  35776. if(!transform.valuecalendar) {
  35777. transform.valuecalendar = transform.calendar;
  35778. }
  35779. delete transform.calendar;
  35780. }
  35781. break;
  35782. case 'groupby':
  35783. // Name has changed from `style` to `styles`, so use `style` but prefer `styles`:
  35784. transform.styles = transform.styles || transform.style;
  35785. if(transform.styles && !Array.isArray(transform.styles)) {
  35786. var prevStyles = transform.styles;
  35787. var styleKeys = Object.keys(prevStyles);
  35788. transform.styles = [];
  35789. for(var j = 0; j < styleKeys.length; j++) {
  35790. transform.styles.push({
  35791. target: styleKeys[j],
  35792. value: prevStyles[styleKeys[j]]
  35793. });
  35794. }
  35795. }
  35796. break;
  35797. }
  35798. }
  35799. }
  35800. // prune empty containers made before the new nestedProperty
  35801. if(emptyContainer(trace, 'line')) delete trace.line;
  35802. if('marker' in trace) {
  35803. if(emptyContainer(trace.marker, 'line')) delete trace.marker.line;
  35804. if(emptyContainer(trace, 'marker')) delete trace.marker;
  35805. }
  35806. // sanitize rgb(fractions) and rgba(fractions) that old tinycolor
  35807. // supported, but new tinycolor does not because they're not valid css
  35808. Color.clean(trace);
  35809. // remove obsolete autobin(x|y) attributes, but only if true
  35810. // if false, this needs to happen in Histogram.calc because it
  35811. // can be a one-time autobin so we need to know the results before
  35812. // we can push them back into the trace.
  35813. if(trace.autobinx) {
  35814. delete trace.autobinx;
  35815. delete trace.xbins;
  35816. }
  35817. if(trace.autobiny) {
  35818. delete trace.autobiny;
  35819. delete trace.ybins;
  35820. }
  35821. cleanTitle(trace);
  35822. if(trace.colorbar) cleanTitle(trace.colorbar);
  35823. if(trace.marker && trace.marker.colorbar) cleanTitle(trace.marker.colorbar);
  35824. if(trace.line && trace.line.colorbar) cleanTitle(trace.line.colorbar);
  35825. if(trace.aaxis) cleanTitle(trace.aaxis);
  35826. if(trace.baxis) cleanTitle(trace.baxis);
  35827. }
  35828. };
  35829. function cleanFinanceDir(dirContainer) {
  35830. if(!Lib.isPlainObject(dirContainer)) return false;
  35831. var dirName = dirContainer.name;
  35832. delete dirContainer.name;
  35833. delete dirContainer.showlegend;
  35834. return (typeof dirName === 'string' || typeof dirName === 'number') && String(dirName);
  35835. }
  35836. function commonPrefix(name1, name2, show1, show2) {
  35837. // if only one is shown in the legend, use that
  35838. if(show1 && !show2) return name1;
  35839. if(show2 && !show1) return name2;
  35840. // if both or neither are in the legend, check if one is blank (or whitespace)
  35841. // and use the other one
  35842. // note that hover labels can still use the name even if the legend doesn't
  35843. if(!name1.trim()) return name2;
  35844. if(!name2.trim()) return name1;
  35845. var minLen = Math.min(name1.length, name2.length);
  35846. var i;
  35847. for(i = 0; i < minLen; i++) {
  35848. if(name1.charAt(i) !== name2.charAt(i)) break;
  35849. }
  35850. var out = name1.substr(0, i);
  35851. return out.trim();
  35852. }
  35853. // textposition - support partial attributes (ie just 'top')
  35854. // and incorrect use of middle / center etc.
  35855. function cleanTextPosition(textposition) {
  35856. var posY = 'middle';
  35857. var posX = 'center';
  35858. if(typeof textposition === 'string') {
  35859. if(textposition.indexOf('top') !== -1) posY = 'top';
  35860. else if(textposition.indexOf('bottom') !== -1) posY = 'bottom';
  35861. if(textposition.indexOf('left') !== -1) posX = 'left';
  35862. else if(textposition.indexOf('right') !== -1) posX = 'right';
  35863. }
  35864. return posY + ' ' + posX;
  35865. }
  35866. function emptyContainer(outer, innerStr) {
  35867. return (innerStr in outer) &&
  35868. (typeof outer[innerStr] === 'object') &&
  35869. (Object.keys(outer[innerStr]).length === 0);
  35870. }
  35871. // swap all the data and data attributes associated with x and y
  35872. exports.swapXYData = function(trace) {
  35873. var i;
  35874. Lib.swapAttrs(trace, ['?', '?0', 'd?', '?bins', 'nbins?', 'autobin?', '?src', 'error_?']);
  35875. if(Array.isArray(trace.z) && Array.isArray(trace.z[0])) {
  35876. if(trace.transpose) delete trace.transpose;
  35877. else trace.transpose = true;
  35878. }
  35879. if(trace.error_x && trace.error_y) {
  35880. var errorY = trace.error_y;
  35881. var copyYstyle = ('copy_ystyle' in errorY) ?
  35882. errorY.copy_ystyle :
  35883. !(errorY.color || errorY.thickness || errorY.width);
  35884. Lib.swapAttrs(trace, ['error_?.copy_ystyle']);
  35885. if(copyYstyle) {
  35886. Lib.swapAttrs(trace, ['error_?.color', 'error_?.thickness', 'error_?.width']);
  35887. }
  35888. }
  35889. if(typeof trace.hoverinfo === 'string') {
  35890. var hoverInfoParts = trace.hoverinfo.split('+');
  35891. for(i = 0; i < hoverInfoParts.length; i++) {
  35892. if(hoverInfoParts[i] === 'x') hoverInfoParts[i] = 'y';
  35893. else if(hoverInfoParts[i] === 'y') hoverInfoParts[i] = 'x';
  35894. }
  35895. trace.hoverinfo = hoverInfoParts.join('+');
  35896. }
  35897. };
  35898. // coerce traceIndices input to array of trace indices
  35899. exports.coerceTraceIndices = function(gd, traceIndices) {
  35900. if(isNumeric(traceIndices)) {
  35901. return [traceIndices];
  35902. }
  35903. else if(!Array.isArray(traceIndices) || !traceIndices.length) {
  35904. return gd.data.map(function(_, i) { return i; });
  35905. }
  35906. else if(Array.isArray(traceIndices)) {
  35907. var traceIndicesOut = [];
  35908. for(var i = 0; i < traceIndices.length; i++) {
  35909. if(Lib.isIndex(traceIndices[i], gd.data.length)) {
  35910. traceIndicesOut.push(traceIndices[i]);
  35911. } else {
  35912. Lib.warn('trace index (', traceIndices[i], ') is not a number or is out of bounds');
  35913. }
  35914. }
  35915. return traceIndicesOut;
  35916. }
  35917. return traceIndices;
  35918. };
  35919. /**
  35920. * Manages logic around array container item creation / deletion / update
  35921. * that nested property alone can't handle.
  35922. *
  35923. * @param {Object} np
  35924. * nested property of update attribute string about trace or layout object
  35925. * @param {*} newVal
  35926. * update value passed to restyle / relayout / update
  35927. * @param {Object} undoit
  35928. * undo hash (N.B. undoit may be mutated here).
  35929. *
  35930. */
  35931. exports.manageArrayContainers = function(np, newVal, undoit) {
  35932. var obj = np.obj;
  35933. var parts = np.parts;
  35934. var pLength = parts.length;
  35935. var pLast = parts[pLength - 1];
  35936. var pLastIsNumber = isNumeric(pLast);
  35937. // delete item
  35938. if(pLastIsNumber && newVal === null) {
  35939. // Clear item in array container when new value is null
  35940. var contPath = parts.slice(0, pLength - 1).join('.');
  35941. var cont = Lib.nestedProperty(obj, contPath).get();
  35942. cont.splice(pLast, 1);
  35943. // Note that nested property clears null / undefined at end of
  35944. // array container, but not within them.
  35945. }
  35946. // create item
  35947. else if(pLastIsNumber && np.get() === undefined) {
  35948. // When adding a new item, make sure undo command will remove it
  35949. if(np.get() === undefined) undoit[np.astr] = null;
  35950. np.set(newVal);
  35951. }
  35952. // update item
  35953. else {
  35954. // If the last part of attribute string isn't a number,
  35955. // np.set is all we need.
  35956. np.set(newVal);
  35957. }
  35958. };
  35959. /*
  35960. * Match the part to strip off to turn an attribute into its parent
  35961. * really it should be either '.some_characters' or '[number]'
  35962. * but we're a little more permissive here and match either
  35963. * '.not_brackets_or_dot' or '[not_brackets_or_dot]'
  35964. */
  35965. var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/;
  35966. function getParent(attr) {
  35967. var tail = attr.search(ATTR_TAIL_RE);
  35968. if(tail > 0) return attr.substr(0, tail);
  35969. }
  35970. /*
  35971. * hasParent: does an attribute object contain a parent of the given attribute?
  35972. * for example, given 'images[2].x' do we also have 'images' or 'images[2]'?
  35973. *
  35974. * @param {Object} aobj
  35975. * update object, whose keys are attribute strings and values are their new settings
  35976. * @param {string} attr
  35977. * the attribute string to test against
  35978. * @returns {Boolean}
  35979. * is a parent of attr present in aobj?
  35980. */
  35981. exports.hasParent = function(aobj, attr) {
  35982. var attrParent = getParent(attr);
  35983. while(attrParent) {
  35984. if(attrParent in aobj) return true;
  35985. attrParent = getParent(attrParent);
  35986. }
  35987. return false;
  35988. };
  35989. /**
  35990. * Empty out types for all axes containing these traces so we auto-set them again
  35991. *
  35992. * @param {object} gd
  35993. * @param {[integer]} traces: trace indices to search for axes to clear the types of
  35994. * @param {object} layoutUpdate: any update being done concurrently to the layout,
  35995. * which may supercede clearing the axis types
  35996. */
  35997. var axLetters = ['x', 'y', 'z'];
  35998. exports.clearAxisTypes = function(gd, traces, layoutUpdate) {
  35999. for(var i = 0; i < traces.length; i++) {
  36000. var trace = gd._fullData[i];
  36001. for(var j = 0; j < 3; j++) {
  36002. var ax = getFromTrace(gd, trace, axLetters[j]);
  36003. // do not clear log type - that's never an auto result so must have been intentional
  36004. if(ax && ax.type !== 'log') {
  36005. var axAttr = ax._name;
  36006. var sceneName = ax._id.substr(1);
  36007. if(sceneName.substr(0, 5) === 'scene') {
  36008. if(layoutUpdate[sceneName] !== undefined) continue;
  36009. axAttr = sceneName + '.' + axAttr;
  36010. }
  36011. var typeAttr = axAttr + '.type';
  36012. if(layoutUpdate[axAttr] === undefined && layoutUpdate[typeAttr] === undefined) {
  36013. Lib.nestedProperty(gd.layout, typeAttr).set(null);
  36014. }
  36015. }
  36016. }
  36017. }
  36018. };
  36019. },{"../components/color":51,"../lib":168,"../plots/cartesian/axis_ids":215,"../plots/plots":245,"../registry":257,"fast-isnumeric":18,"gl-mat4/fromQuat":19}],197:[function(_dereq_,module,exports){
  36020. /**
  36021. * Copyright 2012-2019, Plotly, Inc.
  36022. * All rights reserved.
  36023. *
  36024. * This source code is licensed under the MIT license found in the
  36025. * LICENSE file in the root directory of this source tree.
  36026. */
  36027. 'use strict';
  36028. var main = _dereq_('./plot_api');
  36029. exports.plot = main.plot;
  36030. exports.newPlot = main.newPlot;
  36031. exports.restyle = main.restyle;
  36032. exports.relayout = main.relayout;
  36033. exports.redraw = main.redraw;
  36034. exports.update = main.update;
  36035. exports._guiRestyle = main._guiRestyle;
  36036. exports._guiRelayout = main._guiRelayout;
  36037. exports._guiUpdate = main._guiUpdate;
  36038. exports._storeDirectGUIEdit = main._storeDirectGUIEdit;
  36039. exports.react = main.react;
  36040. exports.extendTraces = main.extendTraces;
  36041. exports.prependTraces = main.prependTraces;
  36042. exports.addTraces = main.addTraces;
  36043. exports.deleteTraces = main.deleteTraces;
  36044. exports.moveTraces = main.moveTraces;
  36045. exports.purge = main.purge;
  36046. exports.addFrames = main.addFrames;
  36047. exports.deleteFrames = main.deleteFrames;
  36048. exports.animate = main.animate;
  36049. exports.setPlotConfig = main.setPlotConfig;
  36050. exports.toImage = _dereq_('./to_image');
  36051. exports.validate = _dereq_('./validate');
  36052. exports.downloadImage = _dereq_('../snapshot/download');
  36053. var templateApi = _dereq_('./template_api');
  36054. exports.makeTemplate = templateApi.makeTemplate;
  36055. exports.validateTemplate = templateApi.validateTemplate;
  36056. },{"../snapshot/download":259,"./plot_api":199,"./template_api":204,"./to_image":205,"./validate":206}],198:[function(_dereq_,module,exports){
  36057. /**
  36058. * Copyright 2012-2019, Plotly, Inc.
  36059. * All rights reserved.
  36060. *
  36061. * This source code is licensed under the MIT license found in the
  36062. * LICENSE file in the root directory of this source tree.
  36063. */
  36064. 'use strict';
  36065. var isPlainObject = _dereq_('../lib/is_plain_object');
  36066. var noop = _dereq_('../lib/noop');
  36067. var Loggers = _dereq_('../lib/loggers');
  36068. var sorterAsc = _dereq_('../lib/search').sorterAsc;
  36069. var Registry = _dereq_('../registry');
  36070. exports.containerArrayMatch = _dereq_('./container_array_match');
  36071. var isAddVal = exports.isAddVal = function isAddVal(val) {
  36072. return val === 'add' || isPlainObject(val);
  36073. };
  36074. var isRemoveVal = exports.isRemoveVal = function isRemoveVal(val) {
  36075. return val === null || val === 'remove';
  36076. };
  36077. /*
  36078. * applyContainerArrayChanges: for managing arrays of layout components in relayout
  36079. * handles them all with a consistent interface.
  36080. *
  36081. * Here are the supported actions -> relayout calls -> edits we get here
  36082. * (as prepared in _relayout):
  36083. *
  36084. * add an empty obj -> {'annotations[2]': 'add'} -> {2: {'': 'add'}}
  36085. * add a specific obj -> {'annotations[2]': {attrs}} -> {2: {'': {attrs}}}
  36086. * delete an obj -> {'annotations[2]': 'remove'} -> {2: {'': 'remove'}}
  36087. * -> {'annotations[2]': null} -> {2: {'': null}}
  36088. * delete the whole array -> {'annotations': 'remove'} -> {'': {'': 'remove'}}
  36089. * -> {'annotations': null} -> {'': {'': null}}
  36090. * edit an object -> {'annotations[2].text': 'boo'} -> {2: {'text': 'boo'}}
  36091. *
  36092. * You can combine many edits to different objects. Objects are added and edited
  36093. * in ascending order, then removed in descending order.
  36094. * For example, starting with [a, b, c], if you want to:
  36095. * - replace b with d:
  36096. * {'annotations[1]': d, 'annotations[2]': null} (b is item 2 after adding d)
  36097. * - add a new item d between a and b, and edit b:
  36098. * {'annotations[1]': d, 'annotations[2].x': newX} (b is item 2 after adding d)
  36099. * - delete b and edit c:
  36100. * {'annotations[1]': null, 'annotations[2].x': newX} (c is edited before b is removed)
  36101. *
  36102. * You CANNOT combine adding/deleting an item at index `i` with edits to the same index `i`
  36103. * You CANNOT combine replacing/deleting the whole array with anything else (for the same array).
  36104. *
  36105. * @param {HTMLDivElement} gd
  36106. * the DOM element of the graph container div
  36107. * @param {Lib.nestedProperty} componentType: the array we are editing
  36108. * @param {Object} edits
  36109. * the changes to make; keys are indices to edit, values are themselves objects:
  36110. * {attr: newValue} of changes to make to that index (with add/remove behavior
  36111. * in special values of the empty attr)
  36112. * @param {Object} flags
  36113. * the flags for which actions we're going to perform to display these (and
  36114. * any other) changes. If we're already `recalc`ing, we don't need to redraw
  36115. * individual items
  36116. * @param {function} _nestedProperty
  36117. * a (possibly modified for gui edits) nestedProperty constructor
  36118. * The modified version takes a 3rd argument, for a prefix to the attribute
  36119. * string necessary for storing GUI edits
  36120. *
  36121. * @returns {bool} `true` if it managed to complete drawing of the changes
  36122. * `false` would mean the parent should replot.
  36123. */
  36124. exports.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags, _nestedProperty) {
  36125. var componentType = np.astr;
  36126. var supplyComponentDefaults = Registry.getComponentMethod(componentType, 'supplyLayoutDefaults');
  36127. var draw = Registry.getComponentMethod(componentType, 'draw');
  36128. var drawOne = Registry.getComponentMethod(componentType, 'drawOne');
  36129. var replotLater = flags.replot || flags.recalc || (supplyComponentDefaults === noop) || (draw === noop);
  36130. var layout = gd.layout;
  36131. var fullLayout = gd._fullLayout;
  36132. if(edits['']) {
  36133. if(Object.keys(edits).length > 1) {
  36134. Loggers.warn('Full array edits are incompatible with other edits',
  36135. componentType);
  36136. }
  36137. var fullVal = edits[''][''];
  36138. if(isRemoveVal(fullVal)) np.set(null);
  36139. else if(Array.isArray(fullVal)) np.set(fullVal);
  36140. else {
  36141. Loggers.warn('Unrecognized full array edit value', componentType, fullVal);
  36142. return true;
  36143. }
  36144. if(replotLater) return false;
  36145. supplyComponentDefaults(layout, fullLayout);
  36146. draw(gd);
  36147. return true;
  36148. }
  36149. var componentNums = Object.keys(edits).map(Number).sort(sorterAsc);
  36150. var componentArrayIn = np.get();
  36151. var componentArray = componentArrayIn || [];
  36152. // componentArrayFull is used just to keep splices in line between
  36153. // full and input arrays, so private keys can be copied over after
  36154. // redoing supplyDefaults
  36155. // TODO: this assumes componentArray is in gd.layout - which will not be
  36156. // true after we extend this to restyle
  36157. var componentArrayFull = _nestedProperty(fullLayout, componentType).get();
  36158. var deletes = [];
  36159. var firstIndexChange = -1;
  36160. var maxIndex = componentArray.length;
  36161. var i;
  36162. var j;
  36163. var componentNum;
  36164. var objEdits;
  36165. var objKeys;
  36166. var objVal;
  36167. var adding, prefix;
  36168. // first make the add and edit changes
  36169. for(i = 0; i < componentNums.length; i++) {
  36170. componentNum = componentNums[i];
  36171. objEdits = edits[componentNum];
  36172. objKeys = Object.keys(objEdits);
  36173. objVal = objEdits[''],
  36174. adding = isAddVal(objVal);
  36175. if(componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) {
  36176. Loggers.warn('index out of range', componentType, componentNum);
  36177. continue;
  36178. }
  36179. if(objVal !== undefined) {
  36180. if(objKeys.length > 1) {
  36181. Loggers.warn(
  36182. 'Insertion & removal are incompatible with edits to the same index.',
  36183. componentType, componentNum);
  36184. }
  36185. if(isRemoveVal(objVal)) {
  36186. deletes.push(componentNum);
  36187. }
  36188. else if(adding) {
  36189. if(objVal === 'add') objVal = {};
  36190. componentArray.splice(componentNum, 0, objVal);
  36191. if(componentArrayFull) componentArrayFull.splice(componentNum, 0, {});
  36192. }
  36193. else {
  36194. Loggers.warn('Unrecognized full object edit value',
  36195. componentType, componentNum, objVal);
  36196. }
  36197. if(firstIndexChange === -1) firstIndexChange = componentNum;
  36198. }
  36199. else {
  36200. for(j = 0; j < objKeys.length; j++) {
  36201. prefix = componentType + '[' + componentNum + '].';
  36202. _nestedProperty(componentArray[componentNum], objKeys[j], prefix)
  36203. .set(objEdits[objKeys[j]]);
  36204. }
  36205. }
  36206. }
  36207. // now do deletes
  36208. for(i = deletes.length - 1; i >= 0; i--) {
  36209. componentArray.splice(deletes[i], 1);
  36210. // TODO: this drops private keys that had been stored in componentArrayFull
  36211. // does this have any ill effects?
  36212. if(componentArrayFull) componentArrayFull.splice(deletes[i], 1);
  36213. }
  36214. if(!componentArray.length) np.set(null);
  36215. else if(!componentArrayIn) np.set(componentArray);
  36216. if(replotLater) return false;
  36217. supplyComponentDefaults(layout, fullLayout);
  36218. // finally draw all the components we need to
  36219. // if we added or removed any, redraw all after it
  36220. if(drawOne !== noop) {
  36221. var indicesToDraw;
  36222. if(firstIndexChange === -1) {
  36223. // there's no re-indexing to do, so only redraw components that changed
  36224. indicesToDraw = componentNums;
  36225. }
  36226. else {
  36227. // in case the component array was shortened, we still need do call
  36228. // drawOne on the latter items so they get properly removed
  36229. maxIndex = Math.max(componentArray.length, maxIndex);
  36230. indicesToDraw = [];
  36231. for(i = 0; i < componentNums.length; i++) {
  36232. componentNum = componentNums[i];
  36233. if(componentNum >= firstIndexChange) break;
  36234. indicesToDraw.push(componentNum);
  36235. }
  36236. for(i = firstIndexChange; i < maxIndex; i++) {
  36237. indicesToDraw.push(i);
  36238. }
  36239. }
  36240. for(i = 0; i < indicesToDraw.length; i++) {
  36241. drawOne(gd, indicesToDraw[i]);
  36242. }
  36243. }
  36244. else draw(gd);
  36245. return true;
  36246. };
  36247. },{"../lib/is_plain_object":169,"../lib/loggers":172,"../lib/noop":177,"../lib/search":186,"../registry":257,"./container_array_match":194}],199:[function(_dereq_,module,exports){
  36248. /**
  36249. * Copyright 2012-2019, Plotly, Inc.
  36250. * All rights reserved.
  36251. *
  36252. * This source code is licensed under the MIT license found in the
  36253. * LICENSE file in the root directory of this source tree.
  36254. */
  36255. 'use strict';
  36256. var d3 = _dereq_('d3');
  36257. var isNumeric = _dereq_('fast-isnumeric');
  36258. var hasHover = _dereq_('has-hover');
  36259. var Lib = _dereq_('../lib');
  36260. var nestedProperty = Lib.nestedProperty;
  36261. var Events = _dereq_('../lib/events');
  36262. var Queue = _dereq_('../lib/queue');
  36263. var Registry = _dereq_('../registry');
  36264. var PlotSchema = _dereq_('./plot_schema');
  36265. var Plots = _dereq_('../plots/plots');
  36266. var Polar = _dereq_('../plots/polar/legacy');
  36267. var Axes = _dereq_('../plots/cartesian/axes');
  36268. var Drawing = _dereq_('../components/drawing');
  36269. var Color = _dereq_('../components/color');
  36270. var connectColorbar = _dereq_('../components/colorbar/connect');
  36271. var initInteractions = _dereq_('../plots/cartesian/graph_interact').initInteractions;
  36272. var xmlnsNamespaces = _dereq_('../constants/xmlns_namespaces');
  36273. var svgTextUtils = _dereq_('../lib/svg_text_utils');
  36274. var dfltConfig = _dereq_('./plot_config').dfltConfig;
  36275. var manageArrays = _dereq_('./manage_arrays');
  36276. var helpers = _dereq_('./helpers');
  36277. var subroutines = _dereq_('./subroutines');
  36278. var editTypes = _dereq_('./edit_types');
  36279. var AX_NAME_PATTERN = _dereq_('../plots/cartesian/constants').AX_NAME_PATTERN;
  36280. var numericNameWarningCount = 0;
  36281. var numericNameWarningCountLimit = 5;
  36282. /**
  36283. * Main plot-creation function
  36284. *
  36285. * @param {string id or DOM element} gd
  36286. * the id or DOM element of the graph container div
  36287. * @param {array of objects} data
  36288. * array of traces, containing the data and display information for each trace
  36289. * @param {object} layout
  36290. * object describing the overall display of the plot,
  36291. * all the stuff that doesn't pertain to any individual trace
  36292. * @param {object} config
  36293. * configuration options (see ./plot_config.js for more info)
  36294. *
  36295. * OR
  36296. *
  36297. * @param {string id or DOM element} gd
  36298. * the id or DOM element of the graph container div
  36299. * @param {object} figure
  36300. * object containing `data`, `layout`, `config`, and `frames` members
  36301. *
  36302. */
  36303. exports.plot = function(gd, data, layout, config) {
  36304. var frames;
  36305. gd = Lib.getGraphDiv(gd);
  36306. // Events.init is idempotent and bails early if gd has already been init'd
  36307. Events.init(gd);
  36308. if(Lib.isPlainObject(data)) {
  36309. var obj = data;
  36310. data = obj.data;
  36311. layout = obj.layout;
  36312. config = obj.config;
  36313. frames = obj.frames;
  36314. }
  36315. var okToPlot = Events.triggerHandler(gd, 'plotly_beforeplot', [data, layout, config]);
  36316. if(okToPlot === false) return Promise.reject();
  36317. // if there's no data or layout, and this isn't yet a plotly plot
  36318. // container, log a warning to help plotly.js users debug
  36319. if(!data && !layout && !Lib.isPlotDiv(gd)) {
  36320. Lib.warn('Calling Plotly.plot as if redrawing ' +
  36321. 'but this container doesn\'t yet have a plot.', gd);
  36322. }
  36323. function addFrames() {
  36324. if(frames) {
  36325. return exports.addFrames(gd, frames);
  36326. }
  36327. }
  36328. // transfer configuration options to gd until we move over to
  36329. // a more OO like model
  36330. setPlotContext(gd, config);
  36331. if(!layout) layout = {};
  36332. // hook class for plots main container (in case of plotly.js
  36333. // this won't be #embedded-graph or .js-tab-contents)
  36334. d3.select(gd).classed('js-plotly-plot', true);
  36335. // off-screen getBoundingClientRect testing space,
  36336. // in #js-plotly-tester (and stored as Drawing.tester)
  36337. // so we can share cached text across tabs
  36338. Drawing.makeTester();
  36339. // collect promises for any async actions during plotting
  36340. // any part of the plotting code can push to gd._promises, then
  36341. // before we move to the next step, we check that they're all
  36342. // complete, and empty out the promise list again.
  36343. if(!Array.isArray(gd._promises)) gd._promises = [];
  36344. var graphWasEmpty = ((gd.data || []).length === 0 && Array.isArray(data));
  36345. // if there is already data on the graph, append the new data
  36346. // if you only want to redraw, pass a non-array for data
  36347. if(Array.isArray(data)) {
  36348. helpers.cleanData(data);
  36349. if(graphWasEmpty) gd.data = data;
  36350. else gd.data.push.apply(gd.data, data);
  36351. // for routines outside graph_obj that want a clean tab
  36352. // (rather than appending to an existing one) gd.empty
  36353. // is used to determine whether to make a new tab
  36354. gd.empty = false;
  36355. }
  36356. if(!gd.layout || graphWasEmpty) gd.layout = helpers.cleanLayout(layout);
  36357. // if the user is trying to drag the axes, allow new data and layout
  36358. // to come in but don't allow a replot.
  36359. if(gd._dragging && !gd._transitioning) {
  36360. // signal to drag handler that after everything else is done
  36361. // we need to replot, because something has changed
  36362. gd._replotPending = true;
  36363. return Promise.reject();
  36364. } else {
  36365. // we're going ahead with a replot now
  36366. gd._replotPending = false;
  36367. }
  36368. Plots.supplyDefaults(gd);
  36369. var fullLayout = gd._fullLayout;
  36370. var hasCartesian = fullLayout._has('cartesian');
  36371. // Legacy polar plots
  36372. if(!fullLayout._has('polar') && data && data[0] && data[0].r) {
  36373. Lib.log('Legacy polar charts are deprecated!');
  36374. return plotLegacyPolar(gd, data, layout);
  36375. }
  36376. // so we don't try to re-call Plotly.plot from inside
  36377. // legend and colorbar, if margins changed
  36378. fullLayout._replotting = true;
  36379. // make or remake the framework if we need to
  36380. if(graphWasEmpty) makePlotFramework(gd);
  36381. // polar need a different framework
  36382. if(gd.framework !== makePlotFramework) {
  36383. gd.framework = makePlotFramework;
  36384. makePlotFramework(gd);
  36385. }
  36386. // clear gradient defs on each .plot call, because we know we'll loop through all traces
  36387. Drawing.initGradients(gd);
  36388. // save initial show spikes once per graph
  36389. if(graphWasEmpty) Axes.saveShowSpikeInitial(gd);
  36390. // prepare the data and find the autorange
  36391. // generate calcdata, if we need to
  36392. // to force redoing calcdata, just delete it before calling Plotly.plot
  36393. var recalc = !gd.calcdata || gd.calcdata.length !== (gd._fullData || []).length;
  36394. if(recalc) Plots.doCalcdata(gd);
  36395. // in case it has changed, attach fullData traces to calcdata
  36396. for(var i = 0; i < gd.calcdata.length; i++) {
  36397. gd.calcdata[i][0].trace = gd._fullData[i];
  36398. }
  36399. // make the figure responsive
  36400. if(gd._context.responsive) {
  36401. if(!gd._responsiveChartHandler) {
  36402. // Keep a reference to the resize handler to purge it down the road
  36403. gd._responsiveChartHandler = function() {Plots.resize(gd);};
  36404. // Listen to window resize
  36405. window.addEventListener('resize', gd._responsiveChartHandler);
  36406. }
  36407. } else {
  36408. Lib.clearResponsive(gd);
  36409. }
  36410. /*
  36411. * start async-friendly code - now we're actually drawing things
  36412. */
  36413. var oldmargins = JSON.stringify(fullLayout._size);
  36414. // draw framework first so that margin-pushing
  36415. // components can position themselves correctly
  36416. var drawFrameworkCalls = 0;
  36417. function drawFramework() {
  36418. var basePlotModules = fullLayout._basePlotModules;
  36419. for(var i = 0; i < basePlotModules.length; i++) {
  36420. if(basePlotModules[i].drawFramework) {
  36421. basePlotModules[i].drawFramework(gd);
  36422. }
  36423. }
  36424. if(!fullLayout._glcanvas && fullLayout._has('gl')) {
  36425. fullLayout._glcanvas = fullLayout._glcontainer.selectAll('.gl-canvas').data([{
  36426. key: 'contextLayer',
  36427. context: true,
  36428. pick: false
  36429. }, {
  36430. key: 'focusLayer',
  36431. context: false,
  36432. pick: false
  36433. }, {
  36434. key: 'pickLayer',
  36435. context: false,
  36436. pick: true
  36437. }], function(d) { return d.key; });
  36438. fullLayout._glcanvas.enter().append('canvas')
  36439. .attr('class', function(d) {
  36440. return 'gl-canvas gl-canvas-' + d.key.replace('Layer', '');
  36441. })
  36442. .style({
  36443. 'position': 'absolute',
  36444. 'top': 0,
  36445. 'left': 0,
  36446. 'width': '100%',
  36447. 'height': '100%',
  36448. 'overflow': 'visible',
  36449. 'pointer-events': 'none'
  36450. });
  36451. }
  36452. if(fullLayout._glcanvas) {
  36453. fullLayout._glcanvas
  36454. .attr('width', fullLayout.width)
  36455. .attr('height', fullLayout.height);
  36456. var regl = fullLayout._glcanvas.data()[0].regl;
  36457. if(regl) {
  36458. // Unfortunately, this can happen when relayouting to large
  36459. // width/height on some browsers.
  36460. if(Math.floor(fullLayout.width) !== regl._gl.drawingBufferWidth ||
  36461. Math.floor(fullLayout.height) !== regl._gl.drawingBufferHeight
  36462. ) {
  36463. var msg = 'WebGL context buffer and canvas dimensions do not match due to browser/WebGL bug.';
  36464. if(drawFrameworkCalls) {
  36465. Lib.error(msg);
  36466. } else {
  36467. Lib.log(msg + ' Clearing graph and plotting again.');
  36468. Plots.cleanPlot([], {}, gd._fullData, fullLayout);
  36469. Plots.supplyDefaults(gd);
  36470. fullLayout = gd._fullLayout;
  36471. Plots.doCalcdata(gd);
  36472. drawFrameworkCalls++;
  36473. return drawFramework();
  36474. }
  36475. }
  36476. }
  36477. }
  36478. return Plots.previousPromises(gd);
  36479. }
  36480. // draw anything that can affect margins.
  36481. function marginPushers() {
  36482. var calcdata = gd.calcdata;
  36483. var i, cd, trace;
  36484. // First reset the list of things that are allowed to change the margins
  36485. // So any deleted traces or components will be wiped out of the
  36486. // automargin calculation.
  36487. // This means *every* margin pusher must be listed here, even if it
  36488. // doesn't actually try to push the margins until later.
  36489. Plots.clearAutoMarginIds(gd);
  36490. subroutines.drawMarginPushers(gd);
  36491. Axes.allowAutoMargin(gd);
  36492. for(i = 0; i < calcdata.length; i++) {
  36493. cd = calcdata[i];
  36494. trace = cd[0].trace;
  36495. var colorbarOpts = trace._module.colorbar;
  36496. if(trace.visible !== true || !colorbarOpts) {
  36497. Plots.autoMargin(gd, 'cb' + trace.uid);
  36498. }
  36499. else connectColorbar(gd, cd, colorbarOpts);
  36500. }
  36501. Plots.doAutoMargin(gd);
  36502. return Plots.previousPromises(gd);
  36503. }
  36504. // in case the margins changed, draw margin pushers again
  36505. function marginPushersAgain() {
  36506. if(JSON.stringify(fullLayout._size) === oldmargins) return;
  36507. return Lib.syncOrAsync([
  36508. marginPushers,
  36509. subroutines.layoutStyles
  36510. ], gd);
  36511. }
  36512. function positionAndAutorange() {
  36513. if(!recalc) {
  36514. doAutoRangeAndConstraints();
  36515. return;
  36516. }
  36517. // TODO: autosize extra for text markers and images
  36518. // see https://github.com/plotly/plotly.js/issues/1111
  36519. return Lib.syncOrAsync([
  36520. Registry.getComponentMethod('shapes', 'calcAutorange'),
  36521. Registry.getComponentMethod('annotations', 'calcAutorange'),
  36522. doAutoRangeAndConstraints
  36523. ], gd);
  36524. }
  36525. function doAutoRangeAndConstraints() {
  36526. if(gd._transitioning) return;
  36527. subroutines.doAutoRangeAndConstraints(gd);
  36528. // store initial ranges *after* enforcing constraints, otherwise
  36529. // we will never look like we're at the initial ranges
  36530. if(graphWasEmpty) Axes.saveRangeInitial(gd);
  36531. // this one is different from shapes/annotations calcAutorange
  36532. // the others incorporate those components into ax._extremes,
  36533. // this one actually sets the ranges in rangesliders.
  36534. Registry.getComponentMethod('rangeslider', 'calcAutorange')(gd);
  36535. }
  36536. // draw ticks, titles, and calculate axis scaling (._b, ._m)
  36537. function drawAxes() {
  36538. return Axes.draw(gd, graphWasEmpty ? '' : 'redraw');
  36539. }
  36540. var seq = [
  36541. Plots.previousPromises,
  36542. addFrames,
  36543. drawFramework,
  36544. marginPushers,
  36545. marginPushersAgain
  36546. ];
  36547. if(hasCartesian) seq.push(positionAndAutorange);
  36548. seq.push(subroutines.layoutStyles);
  36549. if(hasCartesian) seq.push(drawAxes);
  36550. seq.push(
  36551. subroutines.drawData,
  36552. subroutines.finalDraw,
  36553. initInteractions,
  36554. Plots.addLinks,
  36555. Plots.rehover,
  36556. // TODO: doAutoMargin is only needed here for axis automargin, which
  36557. // happens outside of marginPushers where all the other automargins are
  36558. // calculated. Would be much better to separate margin calculations from
  36559. // component drawing - see https://github.com/plotly/plotly.js/issues/2704
  36560. Plots.doAutoMargin,
  36561. Plots.previousPromises
  36562. );
  36563. // even if everything we did was synchronous, return a promise
  36564. // so that the caller doesn't care which route we took
  36565. var plotDone = Lib.syncOrAsync(seq, gd);
  36566. if(!plotDone || !plotDone.then) plotDone = Promise.resolve();
  36567. return plotDone.then(function() {
  36568. emitAfterPlot(gd);
  36569. return gd;
  36570. });
  36571. };
  36572. function emitAfterPlot(gd) {
  36573. var fullLayout = gd._fullLayout;
  36574. if(fullLayout._redrawFromAutoMarginCount) {
  36575. fullLayout._redrawFromAutoMarginCount--;
  36576. } else {
  36577. gd.emit('plotly_afterplot');
  36578. }
  36579. }
  36580. exports.setPlotConfig = function setPlotConfig(obj) {
  36581. return Lib.extendFlat(dfltConfig, obj);
  36582. };
  36583. function setBackground(gd, bgColor) {
  36584. try {
  36585. gd._fullLayout._paper.style('background', bgColor);
  36586. } catch(e) {
  36587. Lib.error(e);
  36588. }
  36589. }
  36590. function opaqueSetBackground(gd, bgColor) {
  36591. var blend = Color.combine(bgColor, 'white');
  36592. setBackground(gd, blend);
  36593. }
  36594. function setPlotContext(gd, config) {
  36595. if(!gd._context) {
  36596. gd._context = Lib.extendDeep({}, dfltConfig);
  36597. // stash <base> href, used to make robust clipPath URLs
  36598. var base = d3.select('base');
  36599. gd._context._baseUrl = base.size() && base.attr('href') ?
  36600. window.location.href.split('#')[0] :
  36601. '';
  36602. }
  36603. var context = gd._context;
  36604. var i, keys, key;
  36605. if(config) {
  36606. keys = Object.keys(config);
  36607. for(i = 0; i < keys.length; i++) {
  36608. key = keys[i];
  36609. if(key === 'editable' || key === 'edits') continue;
  36610. if(key in context) {
  36611. if(key === 'setBackground' && config[key] === 'opaque') {
  36612. context[key] = opaqueSetBackground;
  36613. } else {
  36614. context[key] = config[key];
  36615. }
  36616. }
  36617. }
  36618. // map plot3dPixelRatio to plotGlPixelRatio for backward compatibility
  36619. if(config.plot3dPixelRatio && !context.plotGlPixelRatio) {
  36620. context.plotGlPixelRatio = context.plot3dPixelRatio;
  36621. }
  36622. // now deal with editable and edits - first editable overrides
  36623. // everything, then edits refines
  36624. var editable = config.editable;
  36625. if(editable !== undefined) {
  36626. // we're not going to *use* context.editable, we're only going to
  36627. // use context.edits... but keep it for the record
  36628. context.editable = editable;
  36629. keys = Object.keys(context.edits);
  36630. for(i = 0; i < keys.length; i++) {
  36631. context.edits[keys[i]] = editable;
  36632. }
  36633. }
  36634. if(config.edits) {
  36635. keys = Object.keys(config.edits);
  36636. for(i = 0; i < keys.length; i++) {
  36637. key = keys[i];
  36638. if(key in context.edits) {
  36639. context.edits[key] = config.edits[key];
  36640. }
  36641. }
  36642. }
  36643. // not part of the user-facing config options
  36644. context._exportedPlot = config._exportedPlot;
  36645. }
  36646. // staticPlot forces a bunch of others:
  36647. if(context.staticPlot) {
  36648. context.editable = false;
  36649. context.edits = {};
  36650. context.autosizable = false;
  36651. context.scrollZoom = false;
  36652. context.doubleClick = false;
  36653. context.showTips = false;
  36654. context.showLink = false;
  36655. context.displayModeBar = false;
  36656. }
  36657. // make sure hover-only devices have mode bar visible
  36658. if(context.displayModeBar === 'hover' && !hasHover) {
  36659. context.displayModeBar = true;
  36660. }
  36661. // default and fallback for setBackground
  36662. if(context.setBackground === 'transparent' || typeof context.setBackground !== 'function') {
  36663. context.setBackground = setBackground;
  36664. }
  36665. // Check if gd has a specified widht/height to begin with
  36666. context._hasZeroHeight = context._hasZeroHeight || gd.clientHeight === 0;
  36667. context._hasZeroWidth = context._hasZeroWidth || gd.clientWidth === 0;
  36668. // fill context._scrollZoom helper to help manage scrollZoom flaglist
  36669. var szIn = context.scrollZoom;
  36670. var szOut = context._scrollZoom = {};
  36671. if(szIn === true) {
  36672. szOut.cartesian = 1;
  36673. szOut.gl3d = 1;
  36674. szOut.geo = 1;
  36675. szOut.mapbox = 1;
  36676. } else if(typeof szIn === 'string') {
  36677. var parts = szIn.split('+');
  36678. for(i = 0; i < parts.length; i++) {
  36679. szOut[parts[i]] = 1;
  36680. }
  36681. } else if(szIn !== false) {
  36682. szOut.gl3d = 1;
  36683. szOut.geo = 1;
  36684. szOut.mapbox = 1;
  36685. }
  36686. }
  36687. function plotLegacyPolar(gd, data, layout) {
  36688. // build or reuse the container skeleton
  36689. var plotContainer = d3.select(gd).selectAll('.plot-container')
  36690. .data([0]);
  36691. plotContainer.enter()
  36692. .insert('div', ':first-child')
  36693. .classed('plot-container plotly', true);
  36694. var paperDiv = plotContainer.selectAll('.svg-container')
  36695. .data([0]);
  36696. paperDiv.enter().append('div')
  36697. .classed('svg-container', true)
  36698. .style('position', 'relative');
  36699. // empty it everytime for now
  36700. paperDiv.html('');
  36701. // fulfill gd requirements
  36702. if(data) gd.data = data;
  36703. if(layout) gd.layout = layout;
  36704. Polar.manager.fillLayout(gd);
  36705. // resize canvas
  36706. paperDiv.style({
  36707. width: gd._fullLayout.width + 'px',
  36708. height: gd._fullLayout.height + 'px'
  36709. });
  36710. // instantiate framework
  36711. gd.framework = Polar.manager.framework(gd);
  36712. // plot
  36713. gd.framework({data: gd.data, layout: gd.layout}, paperDiv.node());
  36714. // set undo point
  36715. gd.framework.setUndoPoint();
  36716. // get the resulting svg for extending it
  36717. var polarPlotSVG = gd.framework.svg();
  36718. // editable title
  36719. var opacity = 1;
  36720. var txt = gd._fullLayout.title ? gd._fullLayout.title.text : '';
  36721. if(txt === '' || !txt) opacity = 0;
  36722. var titleLayout = function() {
  36723. this.call(svgTextUtils.convertToTspans, gd);
  36724. // TODO: html/mathjax
  36725. // TODO: center title
  36726. };
  36727. var title = polarPlotSVG.select('.title-group text')
  36728. .call(titleLayout);
  36729. if(gd._context.edits.titleText) {
  36730. var placeholderText = Lib._(gd, 'Click to enter Plot title');
  36731. if(!txt || txt === placeholderText) {
  36732. opacity = 0.2;
  36733. // placeholder is not going through convertToTspans
  36734. // so needs explicit data-unformatted
  36735. title.attr({'data-unformatted': placeholderText})
  36736. .text(placeholderText)
  36737. .style({opacity: opacity})
  36738. .on('mouseover.opacity', function() {
  36739. d3.select(this).transition().duration(100)
  36740. .style('opacity', 1);
  36741. })
  36742. .on('mouseout.opacity', function() {
  36743. d3.select(this).transition().duration(1000)
  36744. .style('opacity', 0);
  36745. });
  36746. }
  36747. var setContenteditable = function() {
  36748. this.call(svgTextUtils.makeEditable, {gd: gd})
  36749. .on('edit', function(text) {
  36750. gd.framework({layout: {title: {text: text}}});
  36751. this.text(text)
  36752. .call(titleLayout);
  36753. this.call(setContenteditable);
  36754. })
  36755. .on('cancel', function() {
  36756. var txt = this.attr('data-unformatted');
  36757. this.text(txt).call(titleLayout);
  36758. });
  36759. };
  36760. title.call(setContenteditable);
  36761. }
  36762. gd._context.setBackground(gd, gd._fullLayout.paper_bgcolor);
  36763. Plots.addLinks(gd);
  36764. return Promise.resolve();
  36765. }
  36766. // convenience function to force a full redraw, mostly for use by plotly.js
  36767. exports.redraw = function(gd) {
  36768. gd = Lib.getGraphDiv(gd);
  36769. if(!Lib.isPlotDiv(gd)) {
  36770. throw new Error('This element is not a Plotly plot: ' + gd);
  36771. }
  36772. helpers.cleanData(gd.data);
  36773. helpers.cleanLayout(gd.layout);
  36774. gd.calcdata = undefined;
  36775. return exports.plot(gd).then(function() {
  36776. gd.emit('plotly_redraw');
  36777. return gd;
  36778. });
  36779. };
  36780. /**
  36781. * Convenience function to make idempotent plot option obvious to users.
  36782. *
  36783. * @param gd
  36784. * @param {Object[]} data
  36785. * @param {Object} layout
  36786. * @param {Object} config
  36787. */
  36788. exports.newPlot = function(gd, data, layout, config) {
  36789. gd = Lib.getGraphDiv(gd);
  36790. // remove gl contexts
  36791. Plots.cleanPlot([], {}, gd._fullData || [], gd._fullLayout || {});
  36792. Plots.purge(gd);
  36793. return exports.plot(gd, data, layout, config);
  36794. };
  36795. /**
  36796. * Wrap negative indicies to their positive counterparts.
  36797. *
  36798. * @param {Number[]} indices An array of indices
  36799. * @param {Number} maxIndex The maximum index allowable (arr.length - 1)
  36800. */
  36801. function positivifyIndices(indices, maxIndex) {
  36802. var parentLength = maxIndex + 1;
  36803. var positiveIndices = [];
  36804. var i;
  36805. var index;
  36806. for(i = 0; i < indices.length; i++) {
  36807. index = indices[i];
  36808. if(index < 0) {
  36809. positiveIndices.push(parentLength + index);
  36810. } else {
  36811. positiveIndices.push(index);
  36812. }
  36813. }
  36814. return positiveIndices;
  36815. }
  36816. /**
  36817. * Ensures that an index array for manipulating gd.data is valid.
  36818. *
  36819. * Intended for use with addTraces, deleteTraces, and moveTraces.
  36820. *
  36821. * @param gd
  36822. * @param indices
  36823. * @param arrayName
  36824. */
  36825. function assertIndexArray(gd, indices, arrayName) {
  36826. var i,
  36827. index;
  36828. for(i = 0; i < indices.length; i++) {
  36829. index = indices[i];
  36830. // validate that indices are indeed integers
  36831. if(index !== parseInt(index, 10)) {
  36832. throw new Error('all values in ' + arrayName + ' must be integers');
  36833. }
  36834. // check that all indices are in bounds for given gd.data array length
  36835. if(index >= gd.data.length || index < -gd.data.length) {
  36836. throw new Error(arrayName + ' must be valid indices for gd.data.');
  36837. }
  36838. // check that indices aren't repeated
  36839. if(indices.indexOf(index, i + 1) > -1 ||
  36840. index >= 0 && indices.indexOf(-gd.data.length + index) > -1 ||
  36841. index < 0 && indices.indexOf(gd.data.length + index) > -1) {
  36842. throw new Error('each index in ' + arrayName + ' must be unique.');
  36843. }
  36844. }
  36845. }
  36846. /**
  36847. * Private function used by Plotly.moveTraces to check input args
  36848. *
  36849. * @param gd
  36850. * @param currentIndices
  36851. * @param newIndices
  36852. */
  36853. function checkMoveTracesArgs(gd, currentIndices, newIndices) {
  36854. // check that gd has attribute 'data' and 'data' is array
  36855. if(!Array.isArray(gd.data)) {
  36856. throw new Error('gd.data must be an array.');
  36857. }
  36858. // validate currentIndices array
  36859. if(typeof currentIndices === 'undefined') {
  36860. throw new Error('currentIndices is a required argument.');
  36861. } else if(!Array.isArray(currentIndices)) {
  36862. currentIndices = [currentIndices];
  36863. }
  36864. assertIndexArray(gd, currentIndices, 'currentIndices');
  36865. // validate newIndices array if it exists
  36866. if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {
  36867. newIndices = [newIndices];
  36868. }
  36869. if(typeof newIndices !== 'undefined') {
  36870. assertIndexArray(gd, newIndices, 'newIndices');
  36871. }
  36872. // check currentIndices and newIndices are the same length if newIdices exists
  36873. if(typeof newIndices !== 'undefined' && currentIndices.length !== newIndices.length) {
  36874. throw new Error('current and new indices must be of equal length.');
  36875. }
  36876. }
  36877. /**
  36878. * A private function to reduce the type checking clutter in addTraces.
  36879. *
  36880. * @param gd
  36881. * @param traces
  36882. * @param newIndices
  36883. */
  36884. function checkAddTracesArgs(gd, traces, newIndices) {
  36885. var i, value;
  36886. // check that gd has attribute 'data' and 'data' is array
  36887. if(!Array.isArray(gd.data)) {
  36888. throw new Error('gd.data must be an array.');
  36889. }
  36890. // make sure traces exists
  36891. if(typeof traces === 'undefined') {
  36892. throw new Error('traces must be defined.');
  36893. }
  36894. // make sure traces is an array
  36895. if(!Array.isArray(traces)) {
  36896. traces = [traces];
  36897. }
  36898. // make sure each value in traces is an object
  36899. for(i = 0; i < traces.length; i++) {
  36900. value = traces[i];
  36901. if(typeof value !== 'object' || (Array.isArray(value) || value === null)) {
  36902. throw new Error('all values in traces array must be non-array objects');
  36903. }
  36904. }
  36905. // make sure we have an index for each trace
  36906. if(typeof newIndices !== 'undefined' && !Array.isArray(newIndices)) {
  36907. newIndices = [newIndices];
  36908. }
  36909. if(typeof newIndices !== 'undefined' && newIndices.length !== traces.length) {
  36910. throw new Error(
  36911. 'if indices is specified, traces.length must equal indices.length'
  36912. );
  36913. }
  36914. }
  36915. /**
  36916. * A private function to reduce the type checking clutter in spliceTraces.
  36917. * Get all update Properties from gd.data. Validate inputs and outputs.
  36918. * Used by prependTrace and extendTraces
  36919. *
  36920. * @param gd
  36921. * @param update
  36922. * @param indices
  36923. * @param maxPoints
  36924. */
  36925. function assertExtendTracesArgs(gd, update, indices, maxPoints) {
  36926. var maxPointsIsObject = Lib.isPlainObject(maxPoints);
  36927. if(!Array.isArray(gd.data)) {
  36928. throw new Error('gd.data must be an array');
  36929. }
  36930. if(!Lib.isPlainObject(update)) {
  36931. throw new Error('update must be a key:value object');
  36932. }
  36933. if(typeof indices === 'undefined') {
  36934. throw new Error('indices must be an integer or array of integers');
  36935. }
  36936. assertIndexArray(gd, indices, 'indices');
  36937. for(var key in update) {
  36938. /*
  36939. * Verify that the attribute to be updated contains as many trace updates
  36940. * as indices. Failure must result in throw and no-op
  36941. */
  36942. if(!Array.isArray(update[key]) || update[key].length !== indices.length) {
  36943. throw new Error('attribute ' + key + ' must be an array of length equal to indices array length');
  36944. }
  36945. /*
  36946. * if maxPoints is an object it must match keys and array lengths of 'update' 1:1
  36947. */
  36948. if(maxPointsIsObject &&
  36949. (!(key in maxPoints) || !Array.isArray(maxPoints[key]) ||
  36950. maxPoints[key].length !== update[key].length)) {
  36951. throw new Error('when maxPoints is set as a key:value object it must contain a 1:1 ' +
  36952. 'corrispondence with the keys and number of traces in the update object');
  36953. }
  36954. }
  36955. }
  36956. /**
  36957. * A private function to reduce the type checking clutter in spliceTraces.
  36958. *
  36959. * @param {Object|HTMLDivElement} gd
  36960. * @param {Object} update
  36961. * @param {Number[]} indices
  36962. * @param {Number||Object} maxPoints
  36963. * @return {Object[]}
  36964. */
  36965. function getExtendProperties(gd, update, indices, maxPoints) {
  36966. var maxPointsIsObject = Lib.isPlainObject(maxPoints);
  36967. var updateProps = [];
  36968. var trace, target, prop, insert, maxp;
  36969. // allow scalar index to represent a single trace position
  36970. if(!Array.isArray(indices)) indices = [indices];
  36971. // negative indices are wrapped around to their positive value. Equivalent to python indexing.
  36972. indices = positivifyIndices(indices, gd.data.length - 1);
  36973. // loop through all update keys and traces and harvest validated data.
  36974. for(var key in update) {
  36975. for(var j = 0; j < indices.length; j++) {
  36976. /*
  36977. * Choose the trace indexed by the indices map argument and get the prop setter-getter
  36978. * instance that references the key and value for this particular trace.
  36979. */
  36980. trace = gd.data[indices[j]];
  36981. prop = nestedProperty(trace, key);
  36982. /*
  36983. * Target is the existing gd.data.trace.dataArray value like "x" or "marker.size"
  36984. * Target must exist as an Array to allow the extend operation to be performed.
  36985. */
  36986. target = prop.get();
  36987. insert = update[key][j];
  36988. if(!Lib.isArrayOrTypedArray(insert)) {
  36989. throw new Error('attribute: ' + key + ' index: ' + j + ' must be an array');
  36990. }
  36991. if(!Lib.isArrayOrTypedArray(target)) {
  36992. throw new Error('cannot extend missing or non-array attribute: ' + key);
  36993. }
  36994. if(target.constructor !== insert.constructor) {
  36995. throw new Error('cannot extend array with an array of a different type: ' + key);
  36996. }
  36997. /*
  36998. * maxPoints may be an object map or a scalar. If object select the key:value, else
  36999. * Use the scalar maxPoints for all key and trace combinations.
  37000. */
  37001. maxp = maxPointsIsObject ? maxPoints[key][j] : maxPoints;
  37002. // could have chosen null here, -1 just tells us to not take a window
  37003. if(!isNumeric(maxp)) maxp = -1;
  37004. /*
  37005. * Wrap the nestedProperty in an object containing required data
  37006. * for lengthening and windowing this particular trace - key combination.
  37007. * Flooring maxp mirrors the behaviour of floats in the Array.slice JSnative function.
  37008. */
  37009. updateProps.push({
  37010. prop: prop,
  37011. target: target,
  37012. insert: insert,
  37013. maxp: Math.floor(maxp)
  37014. });
  37015. }
  37016. }
  37017. // all target and insertion data now validated
  37018. return updateProps;
  37019. }
  37020. /**
  37021. * A private function to key Extend and Prepend traces DRY
  37022. *
  37023. * @param {Object|HTMLDivElement} gd
  37024. * @param {Object} update
  37025. * @param {Number[]} indices
  37026. * @param {Number||Object} maxPoints
  37027. * @param {Function} updateArray
  37028. * @return {Object}
  37029. */
  37030. function spliceTraces(gd, update, indices, maxPoints, updateArray) {
  37031. assertExtendTracesArgs(gd, update, indices, maxPoints);
  37032. var updateProps = getExtendProperties(gd, update, indices, maxPoints);
  37033. var undoUpdate = {};
  37034. var undoPoints = {};
  37035. for(var i = 0; i < updateProps.length; i++) {
  37036. var prop = updateProps[i].prop;
  37037. var maxp = updateProps[i].maxp;
  37038. // return new array and remainder
  37039. var out = updateArray(updateProps[i].target, updateProps[i].insert, maxp);
  37040. prop.set(out[0]);
  37041. // build the inverse update object for the undo operation
  37042. if(!Array.isArray(undoUpdate[prop.astr])) undoUpdate[prop.astr] = [];
  37043. undoUpdate[prop.astr].push(out[1]);
  37044. // build the matching maxPoints undo object containing original trace lengths
  37045. if(!Array.isArray(undoPoints[prop.astr])) undoPoints[prop.astr] = [];
  37046. undoPoints[prop.astr].push(updateProps[i].target.length);
  37047. }
  37048. return {update: undoUpdate, maxPoints: undoPoints};
  37049. }
  37050. function concatTypedArray(arr0, arr1) {
  37051. var arr2 = new arr0.constructor(arr0.length + arr1.length);
  37052. arr2.set(arr0);
  37053. arr2.set(arr1, arr0.length);
  37054. return arr2;
  37055. }
  37056. /**
  37057. * extend && prepend traces at indices with update arrays, window trace lengths to maxPoints
  37058. *
  37059. * Extend and Prepend have identical APIs. Prepend inserts an array at the head while Extend
  37060. * inserts an array off the tail. Prepend truncates the tail of the array - counting maxPoints
  37061. * from the head, whereas Extend truncates the head of the array, counting backward maxPoints
  37062. * from the tail.
  37063. *
  37064. * If maxPoints is undefined, nonNumeric, negative or greater than extended trace length no
  37065. * truncation / windowing will be performed. If its zero, well the whole trace is truncated.
  37066. *
  37067. * @param {Object|HTMLDivElement} gd The graph div
  37068. * @param {Object} update The key:array map of target attributes to extend
  37069. * @param {Number|Number[]} indices The locations of traces to be extended
  37070. * @param {Number|Object} [maxPoints] Number of points for trace window after lengthening.
  37071. *
  37072. */
  37073. exports.extendTraces = function extendTraces(gd, update, indices, maxPoints) {
  37074. gd = Lib.getGraphDiv(gd);
  37075. function updateArray(target, insert, maxp) {
  37076. var newArray, remainder;
  37077. if(Lib.isTypedArray(target)) {
  37078. if(maxp < 0) {
  37079. var none = new target.constructor(0);
  37080. var both = concatTypedArray(target, insert);
  37081. if(maxp < 0) {
  37082. newArray = both;
  37083. remainder = none;
  37084. } else {
  37085. newArray = none;
  37086. remainder = both;
  37087. }
  37088. } else {
  37089. newArray = new target.constructor(maxp);
  37090. remainder = new target.constructor(target.length + insert.length - maxp);
  37091. if(maxp === insert.length) {
  37092. newArray.set(insert);
  37093. remainder.set(target);
  37094. } else if(maxp < insert.length) {
  37095. var numberOfItemsFromInsert = insert.length - maxp;
  37096. newArray.set(insert.subarray(numberOfItemsFromInsert));
  37097. remainder.set(target);
  37098. remainder.set(insert.subarray(0, numberOfItemsFromInsert), target.length);
  37099. } else {
  37100. var numberOfItemsFromTarget = maxp - insert.length;
  37101. var targetBegin = target.length - numberOfItemsFromTarget;
  37102. newArray.set(target.subarray(targetBegin));
  37103. newArray.set(insert, numberOfItemsFromTarget);
  37104. remainder.set(target.subarray(0, targetBegin));
  37105. }
  37106. }
  37107. } else {
  37108. newArray = target.concat(insert);
  37109. remainder = (maxp >= 0 && maxp < newArray.length) ?
  37110. newArray.splice(0, newArray.length - maxp) :
  37111. [];
  37112. }
  37113. return [newArray, remainder];
  37114. }
  37115. var undo = spliceTraces(gd, update, indices, maxPoints, updateArray);
  37116. var promise = exports.redraw(gd);
  37117. var undoArgs = [gd, undo.update, indices, undo.maxPoints];
  37118. Queue.add(gd, exports.prependTraces, undoArgs, extendTraces, arguments);
  37119. return promise;
  37120. };
  37121. exports.prependTraces = function prependTraces(gd, update, indices, maxPoints) {
  37122. gd = Lib.getGraphDiv(gd);
  37123. function updateArray(target, insert, maxp) {
  37124. var newArray, remainder;
  37125. if(Lib.isTypedArray(target)) {
  37126. if(maxp <= 0) {
  37127. var none = new target.constructor(0);
  37128. var both = concatTypedArray(insert, target);
  37129. if(maxp < 0) {
  37130. newArray = both;
  37131. remainder = none;
  37132. } else {
  37133. newArray = none;
  37134. remainder = both;
  37135. }
  37136. } else {
  37137. newArray = new target.constructor(maxp);
  37138. remainder = new target.constructor(target.length + insert.length - maxp);
  37139. if(maxp === insert.length) {
  37140. newArray.set(insert);
  37141. remainder.set(target);
  37142. } else if(maxp < insert.length) {
  37143. var numberOfItemsFromInsert = insert.length - maxp;
  37144. newArray.set(insert.subarray(0, numberOfItemsFromInsert));
  37145. remainder.set(insert.subarray(numberOfItemsFromInsert));
  37146. remainder.set(target, numberOfItemsFromInsert);
  37147. } else {
  37148. var numberOfItemsFromTarget = maxp - insert.length;
  37149. newArray.set(insert);
  37150. newArray.set(target.subarray(0, numberOfItemsFromTarget), insert.length);
  37151. remainder.set(target.subarray(numberOfItemsFromTarget));
  37152. }
  37153. }
  37154. } else {
  37155. newArray = insert.concat(target);
  37156. remainder = (maxp >= 0 && maxp < newArray.length) ?
  37157. newArray.splice(maxp, newArray.length) :
  37158. [];
  37159. }
  37160. return [newArray, remainder];
  37161. }
  37162. var undo = spliceTraces(gd, update, indices, maxPoints, updateArray);
  37163. var promise = exports.redraw(gd);
  37164. var undoArgs = [gd, undo.update, indices, undo.maxPoints];
  37165. Queue.add(gd, exports.extendTraces, undoArgs, prependTraces, arguments);
  37166. return promise;
  37167. };
  37168. /**
  37169. * Add data traces to an existing graph div.
  37170. *
  37171. * @param {Object|HTMLDivElement} gd The graph div
  37172. * @param {Object[]} gd.data The array of traces we're adding to
  37173. * @param {Object[]|Object} traces The object or array of objects to add
  37174. * @param {Number[]|Number} [newIndices=[gd.data.length]] Locations to add traces
  37175. *
  37176. */
  37177. exports.addTraces = function addTraces(gd, traces, newIndices) {
  37178. gd = Lib.getGraphDiv(gd);
  37179. var currentIndices = [];
  37180. var undoFunc = exports.deleteTraces;
  37181. var redoFunc = addTraces;
  37182. var undoArgs = [gd, currentIndices];
  37183. var redoArgs = [gd, traces]; // no newIndices here
  37184. var i;
  37185. var promise;
  37186. // all validation is done elsewhere to remove clutter here
  37187. checkAddTracesArgs(gd, traces, newIndices);
  37188. // make sure traces is an array
  37189. if(!Array.isArray(traces)) {
  37190. traces = [traces];
  37191. }
  37192. // make sure traces do not repeat existing ones
  37193. traces = traces.map(function(trace) {
  37194. return Lib.extendFlat({}, trace);
  37195. });
  37196. helpers.cleanData(traces);
  37197. // add the traces to gd.data (no redrawing yet!)
  37198. for(i = 0; i < traces.length; i++) {
  37199. gd.data.push(traces[i]);
  37200. }
  37201. // to continue, we need to call moveTraces which requires currentIndices
  37202. for(i = 0; i < traces.length; i++) {
  37203. currentIndices.push(-traces.length + i);
  37204. }
  37205. // if the user didn't define newIndices, they just want the traces appended
  37206. // i.e., we can simply redraw and be done
  37207. if(typeof newIndices === 'undefined') {
  37208. promise = exports.redraw(gd);
  37209. Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
  37210. return promise;
  37211. }
  37212. // make sure indices is property defined
  37213. if(!Array.isArray(newIndices)) {
  37214. newIndices = [newIndices];
  37215. }
  37216. try {
  37217. // this is redundant, but necessary to not catch later possible errors!
  37218. checkMoveTracesArgs(gd, currentIndices, newIndices);
  37219. }
  37220. catch(error) {
  37221. // something went wrong, reset gd to be safe and rethrow error
  37222. gd.data.splice(gd.data.length - traces.length, traces.length);
  37223. throw error;
  37224. }
  37225. // if we're here, the user has defined specific places to place the new traces
  37226. // this requires some extra work that moveTraces will do
  37227. Queue.startSequence(gd);
  37228. Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
  37229. promise = exports.moveTraces(gd, currentIndices, newIndices);
  37230. Queue.stopSequence(gd);
  37231. return promise;
  37232. };
  37233. /**
  37234. * Delete traces at `indices` from gd.data array.
  37235. *
  37236. * @param {Object|HTMLDivElement} gd The graph div
  37237. * @param {Object[]} gd.data The array of traces we're removing from
  37238. * @param {Number|Number[]} indices The indices
  37239. */
  37240. exports.deleteTraces = function deleteTraces(gd, indices) {
  37241. gd = Lib.getGraphDiv(gd);
  37242. var traces = [];
  37243. var undoFunc = exports.addTraces;
  37244. var redoFunc = deleteTraces;
  37245. var undoArgs = [gd, traces, indices];
  37246. var redoArgs = [gd, indices];
  37247. var i;
  37248. var deletedTrace;
  37249. // make sure indices are defined
  37250. if(typeof indices === 'undefined') {
  37251. throw new Error('indices must be an integer or array of integers.');
  37252. } else if(!Array.isArray(indices)) {
  37253. indices = [indices];
  37254. }
  37255. assertIndexArray(gd, indices, 'indices');
  37256. // convert negative indices to positive indices
  37257. indices = positivifyIndices(indices, gd.data.length - 1);
  37258. // we want descending here so that splicing later doesn't affect indexing
  37259. indices.sort(Lib.sorterDes);
  37260. for(i = 0; i < indices.length; i += 1) {
  37261. deletedTrace = gd.data.splice(indices[i], 1)[0];
  37262. traces.push(deletedTrace);
  37263. }
  37264. var promise = exports.redraw(gd);
  37265. Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
  37266. return promise;
  37267. };
  37268. /**
  37269. * Move traces at currentIndices array to locations in newIndices array.
  37270. *
  37271. * If newIndices is omitted, currentIndices will be moved to the end. E.g.,
  37272. * these are equivalent:
  37273. *
  37274. * Plotly.moveTraces(gd, [1, 2, 3], [-3, -2, -1])
  37275. * Plotly.moveTraces(gd, [1, 2, 3])
  37276. *
  37277. * @param {Object|HTMLDivElement} gd The graph div
  37278. * @param {Object[]} gd.data The array of traces we're removing from
  37279. * @param {Number|Number[]} currentIndices The locations of traces to be moved
  37280. * @param {Number|Number[]} [newIndices] The locations to move traces to
  37281. *
  37282. * Example calls:
  37283. *
  37284. * // move trace i to location x
  37285. * Plotly.moveTraces(gd, i, x)
  37286. *
  37287. * // move trace i to end of array
  37288. * Plotly.moveTraces(gd, i)
  37289. *
  37290. * // move traces i, j, k to end of array (i != j != k)
  37291. * Plotly.moveTraces(gd, [i, j, k])
  37292. *
  37293. * // move traces [i, j, k] to [x, y, z] (i != j != k) (x != y != z)
  37294. * Plotly.moveTraces(gd, [i, j, k], [x, y, z])
  37295. *
  37296. * // reorder all traces (assume there are 5--a, b, c, d, e)
  37297. * Plotly.moveTraces(gd, [b, d, e, a, c]) // same as 'move to end'
  37298. */
  37299. exports.moveTraces = function moveTraces(gd, currentIndices, newIndices) {
  37300. gd = Lib.getGraphDiv(gd);
  37301. var newData = [];
  37302. var movingTraceMap = [];
  37303. var undoFunc = moveTraces;
  37304. var redoFunc = moveTraces;
  37305. var undoArgs = [gd, newIndices, currentIndices];
  37306. var redoArgs = [gd, currentIndices, newIndices];
  37307. var i;
  37308. // to reduce complexity here, check args elsewhere
  37309. // this throws errors where appropriate
  37310. checkMoveTracesArgs(gd, currentIndices, newIndices);
  37311. // make sure currentIndices is an array
  37312. currentIndices = Array.isArray(currentIndices) ? currentIndices : [currentIndices];
  37313. // if undefined, define newIndices to point to the end of gd.data array
  37314. if(typeof newIndices === 'undefined') {
  37315. newIndices = [];
  37316. for(i = 0; i < currentIndices.length; i++) {
  37317. newIndices.push(-currentIndices.length + i);
  37318. }
  37319. }
  37320. // make sure newIndices is an array if it's user-defined
  37321. newIndices = Array.isArray(newIndices) ? newIndices : [newIndices];
  37322. // convert negative indices to positive indices (they're the same length)
  37323. currentIndices = positivifyIndices(currentIndices, gd.data.length - 1);
  37324. newIndices = positivifyIndices(newIndices, gd.data.length - 1);
  37325. // at this point, we've coerced the index arrays into predictable forms
  37326. // get the traces that aren't being moved around
  37327. for(i = 0; i < gd.data.length; i++) {
  37328. // if index isn't in currentIndices, include it in ignored!
  37329. if(currentIndices.indexOf(i) === -1) {
  37330. newData.push(gd.data[i]);
  37331. }
  37332. }
  37333. // get a mapping of indices to moving traces
  37334. for(i = 0; i < currentIndices.length; i++) {
  37335. movingTraceMap.push({newIndex: newIndices[i], trace: gd.data[currentIndices[i]]});
  37336. }
  37337. // reorder this mapping by newIndex, ascending
  37338. movingTraceMap.sort(function(a, b) {
  37339. return a.newIndex - b.newIndex;
  37340. });
  37341. // now, add the moving traces back in, in order!
  37342. for(i = 0; i < movingTraceMap.length; i += 1) {
  37343. newData.splice(movingTraceMap[i].newIndex, 0, movingTraceMap[i].trace);
  37344. }
  37345. gd.data = newData;
  37346. var promise = exports.redraw(gd);
  37347. Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
  37348. return promise;
  37349. };
  37350. /**
  37351. * restyle: update trace attributes of an existing plot
  37352. *
  37353. * Can be called two ways.
  37354. *
  37355. * Signature 1:
  37356. * @param {String | HTMLDivElement} gd
  37357. * the id or DOM element of the graph container div
  37358. * @param {String} astr
  37359. * attribute string (like `'marker.symbol'`) to update
  37360. * @param {*} val
  37361. * value to give this attribute
  37362. * @param {Number[] | Number} [traces]
  37363. * integer or array of integers for the traces to alter (all if omitted)
  37364. *
  37365. * Signature 2:
  37366. * @param {String | HTMLDivElement} gd
  37367. * (as in signature 1)
  37368. * @param {Object} aobj
  37369. * attribute object `{astr1: val1, astr2: val2 ...}`
  37370. * allows setting multiple attributes simultaneously
  37371. * @param {Number[] | Number} [traces]
  37372. * (as in signature 1)
  37373. *
  37374. * `val` (or `val1`, `val2` ... in the object form) can be an array,
  37375. * to apply different values to each trace.
  37376. *
  37377. * If the array is too short, it will wrap around (useful for
  37378. * style files that want to specify cyclical default values).
  37379. */
  37380. function restyle(gd, astr, val, _traces) {
  37381. gd = Lib.getGraphDiv(gd);
  37382. helpers.clearPromiseQueue(gd);
  37383. var aobj = {};
  37384. if(typeof astr === 'string') aobj[astr] = val;
  37385. else if(Lib.isPlainObject(astr)) {
  37386. // the 3-arg form
  37387. aobj = Lib.extendFlat({}, astr);
  37388. if(_traces === undefined) _traces = val;
  37389. }
  37390. else {
  37391. Lib.warn('Restyle fail.', astr, val, _traces);
  37392. return Promise.reject();
  37393. }
  37394. if(Object.keys(aobj).length) gd.changed = true;
  37395. var traces = helpers.coerceTraceIndices(gd, _traces);
  37396. var specs = _restyle(gd, aobj, traces);
  37397. var flags = specs.flags;
  37398. // clear calcdata and/or axis types if required so they get regenerated
  37399. if(flags.calc) gd.calcdata = undefined;
  37400. if(flags.clearAxisTypes) helpers.clearAxisTypes(gd, traces, {});
  37401. // fill in redraw sequence
  37402. var seq = [];
  37403. if(flags.fullReplot) {
  37404. seq.push(exports.plot);
  37405. } else {
  37406. seq.push(Plots.previousPromises);
  37407. // maybe only call Plots.supplyDataDefaults in the splom case,
  37408. // to skip over long and slow axes defaults
  37409. Plots.supplyDefaults(gd);
  37410. if(flags.markerSize) {
  37411. Plots.doCalcdata(gd);
  37412. addAxRangeSequence(seq);
  37413. // TODO
  37414. // if all axes have autorange:false, then
  37415. // proceed to subroutines.doTraceStyle(),
  37416. // otherwise we must go through addAxRangeSequence,
  37417. // which in general must redraws 'all' axes
  37418. }
  37419. if(flags.style) seq.push(subroutines.doTraceStyle);
  37420. if(flags.colorbars) seq.push(subroutines.doColorBars);
  37421. seq.push(emitAfterPlot);
  37422. }
  37423. seq.push(Plots.rehover);
  37424. Queue.add(gd,
  37425. restyle, [gd, specs.undoit, specs.traces],
  37426. restyle, [gd, specs.redoit, specs.traces]
  37427. );
  37428. var plotDone = Lib.syncOrAsync(seq, gd);
  37429. if(!plotDone || !plotDone.then) plotDone = Promise.resolve();
  37430. return plotDone.then(function() {
  37431. gd.emit('plotly_restyle', specs.eventData);
  37432. return gd;
  37433. });
  37434. }
  37435. exports.restyle = restyle;
  37436. // for undo: undefined initial vals must be turned into nulls
  37437. // so that we unset rather than ignore them
  37438. function undefinedToNull(val) {
  37439. if(val === undefined) return null;
  37440. return val;
  37441. }
  37442. /**
  37443. * Factory function to wrap nestedProperty with GUI edits if necessary
  37444. * with GUI edits we add an optional prefix to the nestedProperty constructor
  37445. * to prepend to the attribute string in the preGUI store.
  37446. */
  37447. function makeNP(preGUI, guiEditFlag) {
  37448. if(!guiEditFlag) return nestedProperty;
  37449. return function(container, attr, prefix) {
  37450. var np = nestedProperty(container, attr);
  37451. var npSet = np.set;
  37452. np.set = function(val) {
  37453. var fullAttr = (prefix || '') + attr;
  37454. storeCurrent(fullAttr, np.get(), val, preGUI);
  37455. npSet(val);
  37456. };
  37457. return np;
  37458. };
  37459. }
  37460. function storeCurrent(attr, val, newVal, preGUI) {
  37461. if(Array.isArray(val) || Array.isArray(newVal)) {
  37462. var arrayVal = Array.isArray(val) ? val : [];
  37463. var arrayNew = Array.isArray(newVal) ? newVal : [];
  37464. var maxLen = Math.max(arrayVal.length, arrayNew.length);
  37465. for(var i = 0; i < maxLen; i++) {
  37466. storeCurrent(attr + '[' + i + ']', arrayVal[i], arrayNew[i], preGUI);
  37467. }
  37468. }
  37469. else if(Lib.isPlainObject(val) || Lib.isPlainObject(newVal)) {
  37470. var objVal = Lib.isPlainObject(val) ? val : {};
  37471. var objNew = Lib.isPlainObject(newVal) ? newVal : {};
  37472. var objBoth = Lib.extendFlat({}, objVal, objNew);
  37473. for(var key in objBoth) {
  37474. storeCurrent(attr + '.' + key, objVal[key], objNew[key], preGUI);
  37475. }
  37476. }
  37477. else if(preGUI[attr] === undefined) {
  37478. preGUI[attr] = undefinedToNull(val);
  37479. }
  37480. }
  37481. /**
  37482. * storeDirectGUIEdit: for routines that skip restyle/relayout and mock it
  37483. * by emitting a plotly_restyle or plotly_relayout event, this routine
  37484. * keeps track of the initial state in _preGUI for use by uirevision
  37485. * Does *not* apply these changes to data/layout - that's the responsibility
  37486. * of the calling routine.
  37487. *
  37488. * @param {object} container: the input attributes container (eg `layout` or a `trace`)
  37489. * @param {object} preGUI: where original values should be stored, either
  37490. * `layout._preGUI` or `layout._tracePreGUI[uid]`
  37491. * @param {object} edits: the {attr: val} object as normally passed to `relayout` etc
  37492. */
  37493. exports._storeDirectGUIEdit = function(container, preGUI, edits) {
  37494. for(var attr in edits) {
  37495. var np = nestedProperty(container, attr);
  37496. storeCurrent(attr, np.get(), edits[attr], preGUI);
  37497. }
  37498. };
  37499. function _restyle(gd, aobj, traces) {
  37500. var fullLayout = gd._fullLayout;
  37501. var fullData = gd._fullData;
  37502. var data = gd.data;
  37503. var guiEditFlag = fullLayout._guiEditing;
  37504. var layoutNP = makeNP(fullLayout._preGUI, guiEditFlag);
  37505. var eventData = Lib.extendDeepAll({}, aobj);
  37506. var i;
  37507. cleanDeprecatedAttributeKeys(aobj);
  37508. // initialize flags
  37509. var flags = editTypes.traceFlags();
  37510. // copies of the change (and previous values of anything affected)
  37511. // for the undo / redo queue
  37512. var redoit = {};
  37513. var undoit = {};
  37514. var axlist;
  37515. // make a new empty vals array for undoit
  37516. function a0() { return traces.map(function() { return undefined; }); }
  37517. // for autoranging multiple axes
  37518. function addToAxlist(axid) {
  37519. var axName = Axes.id2name(axid);
  37520. if(axlist.indexOf(axName) === -1) axlist.push(axName);
  37521. }
  37522. function autorangeAttr(axName) { return 'LAYOUT' + axName + '.autorange'; }
  37523. function rangeAttr(axName) { return 'LAYOUT' + axName + '.range'; }
  37524. function getFullTrace(traceIndex) {
  37525. // usually fullData maps 1:1 onto data, but with groupby transforms
  37526. // the fullData index can be greater. Take the *first* matching trace.
  37527. for(var j = traceIndex; j < fullData.length; j++) {
  37528. if(fullData[j]._input === data[traceIndex]) return fullData[j];
  37529. }
  37530. // should never get here - and if we *do* it should cause an error
  37531. // later on undefined fullTrace is passed to nestedProperty.
  37532. }
  37533. // for attrs that interact (like scales & autoscales), save the
  37534. // old vals before making the change
  37535. // val=undefined will not set a value, just record what the value was.
  37536. // val=null will delete the attribute
  37537. // attr can be an array to set several at once (all to the same val)
  37538. function doextra(attr, val, i) {
  37539. if(Array.isArray(attr)) {
  37540. attr.forEach(function(a) { doextra(a, val, i); });
  37541. return;
  37542. }
  37543. // quit if explicitly setting this elsewhere
  37544. if(attr in aobj || helpers.hasParent(aobj, attr)) return;
  37545. var extraparam;
  37546. if(attr.substr(0, 6) === 'LAYOUT') {
  37547. extraparam = layoutNP(gd.layout, attr.replace('LAYOUT', ''));
  37548. } else {
  37549. var tracei = traces[i];
  37550. var preGUI = fullLayout._tracePreGUI[getFullTrace(tracei)._fullInput.uid];
  37551. extraparam = makeNP(preGUI, guiEditFlag)(data[tracei], attr);
  37552. }
  37553. if(!(attr in undoit)) {
  37554. undoit[attr] = a0();
  37555. }
  37556. if(undoit[attr][i] === undefined) {
  37557. undoit[attr][i] = undefinedToNull(extraparam.get());
  37558. }
  37559. if(val !== undefined) {
  37560. extraparam.set(val);
  37561. }
  37562. }
  37563. function allBins(binAttr) {
  37564. return function(j) {
  37565. return fullData[j][binAttr];
  37566. };
  37567. }
  37568. function arrayBins(binAttr) {
  37569. return function(vij, j) {
  37570. return vij === false ? fullData[traces[j]][binAttr] : null;
  37571. };
  37572. }
  37573. // now make the changes to gd.data (and occasionally gd.layout)
  37574. // and figure out what kind of graphics update we need to do
  37575. for(var ai in aobj) {
  37576. if(helpers.hasParent(aobj, ai)) {
  37577. throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously');
  37578. }
  37579. var vi = aobj[ai];
  37580. var cont;
  37581. var contFull;
  37582. var param;
  37583. var oldVal;
  37584. var newVal;
  37585. var valObject;
  37586. // Backward compatibility shim for turning histogram autobin on,
  37587. // or freezing previous autobinned values.
  37588. // Replace obsolete `autobin(x|y): true` with `(x|y)bins: null`
  37589. // and `autobin(x|y): false` with the `(x|y)bins` in `fullData`
  37590. if(ai === 'autobinx' || ai === 'autobiny') {
  37591. ai = ai.charAt(ai.length - 1) + 'bins';
  37592. if(Array.isArray(vi)) vi = vi.map(arrayBins(ai));
  37593. else if(vi === false) vi = traces.map(allBins(ai));
  37594. else vi = null;
  37595. }
  37596. redoit[ai] = vi;
  37597. if(ai.substr(0, 6) === 'LAYOUT') {
  37598. param = layoutNP(gd.layout, ai.replace('LAYOUT', ''));
  37599. undoit[ai] = [undefinedToNull(param.get())];
  37600. // since we're allowing val to be an array, allow it here too,
  37601. // even though that's meaningless
  37602. param.set(Array.isArray(vi) ? vi[0] : vi);
  37603. // ironically, the layout attrs in restyle only require replot,
  37604. // not relayout
  37605. flags.calc = true;
  37606. continue;
  37607. }
  37608. // set attribute in gd.data
  37609. undoit[ai] = a0();
  37610. for(i = 0; i < traces.length; i++) {
  37611. cont = data[traces[i]];
  37612. contFull = getFullTrace(traces[i]);
  37613. var preGUI = fullLayout._tracePreGUI[contFull._fullInput.uid];
  37614. param = makeNP(preGUI, guiEditFlag)(cont, ai);
  37615. oldVal = param.get();
  37616. newVal = Array.isArray(vi) ? vi[i % vi.length] : vi;
  37617. if(newVal === undefined) continue;
  37618. var finalPart = param.parts[param.parts.length - 1];
  37619. var prefix = ai.substr(0, ai.length - finalPart.length - 1);
  37620. var prefixDot = prefix ? prefix + '.' : '';
  37621. var innerContFull = prefix ?
  37622. nestedProperty(contFull, prefix).get() : contFull;
  37623. valObject = PlotSchema.getTraceValObject(contFull, param.parts);
  37624. if(valObject && valObject.impliedEdits && newVal !== null) {
  37625. for(var impliedKey in valObject.impliedEdits) {
  37626. doextra(Lib.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i);
  37627. }
  37628. }
  37629. // changing colorbar size modes,
  37630. // make the resulting size not change
  37631. // note that colorbar fractional sizing is based on the
  37632. // original plot size, before anything (like a colorbar)
  37633. // increases the margins
  37634. else if((finalPart === 'thicknessmode' || finalPart === 'lenmode') &&
  37635. oldVal !== newVal &&
  37636. (newVal === 'fraction' || newVal === 'pixels') &&
  37637. innerContFull
  37638. ) {
  37639. var gs = fullLayout._size;
  37640. var orient = innerContFull.orient;
  37641. var topOrBottom = (orient === 'top') || (orient === 'bottom');
  37642. if(finalPart === 'thicknessmode') {
  37643. var thicknorm = topOrBottom ? gs.h : gs.w;
  37644. doextra(prefixDot + 'thickness', innerContFull.thickness *
  37645. (newVal === 'fraction' ? 1 / thicknorm : thicknorm), i);
  37646. }
  37647. else {
  37648. var lennorm = topOrBottom ? gs.w : gs.h;
  37649. doextra(prefixDot + 'len', innerContFull.len *
  37650. (newVal === 'fraction' ? 1 / lennorm : lennorm), i);
  37651. }
  37652. }
  37653. else if(ai === 'type' && (newVal === 'pie') !== (oldVal === 'pie')) {
  37654. var labelsTo = 'x';
  37655. var valuesTo = 'y';
  37656. if((newVal === 'bar' || oldVal === 'bar') && cont.orientation === 'h') {
  37657. labelsTo = 'y';
  37658. valuesTo = 'x';
  37659. }
  37660. Lib.swapAttrs(cont, ['?', '?src'], 'labels', labelsTo);
  37661. Lib.swapAttrs(cont, ['d?', '?0'], 'label', labelsTo);
  37662. Lib.swapAttrs(cont, ['?', '?src'], 'values', valuesTo);
  37663. if(oldVal === 'pie') {
  37664. nestedProperty(cont, 'marker.color')
  37665. .set(nestedProperty(cont, 'marker.colors').get());
  37666. // super kludgy - but if all pies are gone we won't remove them otherwise
  37667. fullLayout._pielayer.selectAll('g.trace').remove();
  37668. } else if(Registry.traceIs(cont, 'cartesian')) {
  37669. nestedProperty(cont, 'marker.colors')
  37670. .set(nestedProperty(cont, 'marker.color').get());
  37671. }
  37672. }
  37673. undoit[ai][i] = undefinedToNull(oldVal);
  37674. // set the new value - if val is an array, it's one el per trace
  37675. // first check for attributes that get more complex alterations
  37676. var swapAttrs = [
  37677. 'swapxy', 'swapxyaxes', 'orientation', 'orientationaxes'
  37678. ];
  37679. if(swapAttrs.indexOf(ai) !== -1) {
  37680. // setting an orientation: make sure it's changing
  37681. // before we swap everything else
  37682. if(ai === 'orientation') {
  37683. param.set(newVal);
  37684. // obnoxious that we need this level of coupling... but in order to
  37685. // properly handle setting orientation to `null` we need to mimic
  37686. // the logic inside Bars.supplyDefaults for default orientation
  37687. var defaultOrientation = (cont.x && !cont.y) ? 'h' : 'v';
  37688. if((param.get() || defaultOrientation) === contFull.orientation) {
  37689. continue;
  37690. }
  37691. }
  37692. // orientationaxes has no value,
  37693. // it flips everything and the axes
  37694. else if(ai === 'orientationaxes') {
  37695. cont.orientation =
  37696. {v: 'h', h: 'v'}[contFull.orientation];
  37697. }
  37698. helpers.swapXYData(cont);
  37699. flags.calc = flags.clearAxisTypes = true;
  37700. }
  37701. else if(Plots.dataArrayContainers.indexOf(param.parts[0]) !== -1) {
  37702. // TODO: use manageArrays.applyContainerArrayChanges here too
  37703. helpers.manageArrayContainers(param, newVal, undoit);
  37704. flags.calc = true;
  37705. }
  37706. else {
  37707. if(valObject) {
  37708. // must redo calcdata when restyling array values of arrayOk attributes
  37709. // ... but no need to this for regl-based traces
  37710. if(valObject.arrayOk &&
  37711. !Registry.traceIs(contFull, 'regl') &&
  37712. (Lib.isArrayOrTypedArray(newVal) || Lib.isArrayOrTypedArray(oldVal))
  37713. ) {
  37714. flags.calc = true;
  37715. }
  37716. else editTypes.update(flags, valObject);
  37717. }
  37718. else {
  37719. /*
  37720. * if we couldn't find valObject, assume a full recalc.
  37721. * This can happen if you're changing type and making
  37722. * some other edits too, so the modules we're
  37723. * looking at don't have these attributes in them.
  37724. */
  37725. flags.calc = true;
  37726. }
  37727. // all the other ones, just modify that one attribute
  37728. param.set(newVal);
  37729. }
  37730. }
  37731. // swap the data attributes of the relevant x and y axes?
  37732. if(['swapxyaxes', 'orientationaxes'].indexOf(ai) !== -1) {
  37733. Axes.swap(gd, traces);
  37734. }
  37735. // swap hovermode if set to "compare x/y data"
  37736. if(ai === 'orientationaxes') {
  37737. var hovermode = nestedProperty(gd.layout, 'hovermode');
  37738. if(hovermode.get() === 'x') {
  37739. hovermode.set('y');
  37740. } else if(hovermode.get() === 'y') {
  37741. hovermode.set('x');
  37742. }
  37743. }
  37744. // Major enough changes deserve autoscale and
  37745. // non-reversed axes so people don't get confused
  37746. //
  37747. // Note: autobin (or its new analog bin clearing) is not included here
  37748. // since we're not pushing bins back to gd.data, so if we have bin
  37749. // info it was explicitly provided by the user.
  37750. if(['orientation', 'type'].indexOf(ai) !== -1) {
  37751. axlist = [];
  37752. for(i = 0; i < traces.length; i++) {
  37753. var trace = data[traces[i]];
  37754. if(Registry.traceIs(trace, 'cartesian')) {
  37755. addToAxlist(trace.xaxis || 'x');
  37756. addToAxlist(trace.yaxis || 'y');
  37757. }
  37758. }
  37759. doextra(axlist.map(autorangeAttr), true, 0);
  37760. doextra(axlist.map(rangeAttr), [0, 1], 0);
  37761. }
  37762. }
  37763. if(flags.calc || flags.plot) {
  37764. flags.fullReplot = true;
  37765. }
  37766. return {
  37767. flags: flags,
  37768. undoit: undoit,
  37769. redoit: redoit,
  37770. traces: traces,
  37771. eventData: Lib.extendDeepNoArrays([], [eventData, traces])
  37772. };
  37773. }
  37774. /**
  37775. * Converts deprecated attribute keys to
  37776. * the current API to ensure backwards compatibility.
  37777. *
  37778. * This is needed for the update mechanism to determine which
  37779. * subroutines to run based on the actual attribute
  37780. * definitions (that don't include the deprecated ones).
  37781. *
  37782. * E.g. Maps {'xaxis.title': 'A chart'} to {'xaxis.title.text': 'A chart'}
  37783. * and {titlefont: {...}} to {'title.font': {...}}.
  37784. *
  37785. * @param aobj
  37786. */
  37787. function cleanDeprecatedAttributeKeys(aobj) {
  37788. var oldAxisTitleRegex = Lib.counterRegex('axis', '\.title', false, false);
  37789. var colorbarRegex = /colorbar\.title$/;
  37790. var keys = Object.keys(aobj);
  37791. var i, key, value;
  37792. for(i = 0; i < keys.length; i++) {
  37793. key = keys[i];
  37794. value = aobj[key];
  37795. if((key === 'title' || oldAxisTitleRegex.test(key) || colorbarRegex.test(key)) &&
  37796. (typeof value === 'string' || typeof value === 'number')) {
  37797. replace(key, key.replace('title', 'title.text'));
  37798. } else if(key.indexOf('titlefont') > -1) {
  37799. replace(key, key.replace('titlefont', 'title.font'));
  37800. } else if(key.indexOf('titleposition') > -1) {
  37801. replace(key, key.replace('titleposition', 'title.position'));
  37802. } else if(key.indexOf('titleside') > -1) {
  37803. replace(key, key.replace('titleside', 'title.side'));
  37804. } else if(key.indexOf('titleoffset') > -1) {
  37805. replace(key, key.replace('titleoffset', 'title.offset'));
  37806. }
  37807. }
  37808. function replace(oldAttrStr, newAttrStr) {
  37809. aobj[newAttrStr] = aobj[oldAttrStr];
  37810. delete aobj[oldAttrStr];
  37811. }
  37812. }
  37813. /**
  37814. * relayout: update layout attributes of an existing plot
  37815. *
  37816. * Can be called two ways:
  37817. *
  37818. * Signature 1:
  37819. * @param {String | HTMLDivElement} gd
  37820. * the id or dom element of the graph container div
  37821. * @param {String} astr
  37822. * attribute string (like `'xaxis.range[0]'`) to update
  37823. * @param {*} val
  37824. * value to give this attribute
  37825. *
  37826. * Signature 2:
  37827. * @param {String | HTMLDivElement} gd
  37828. * (as in signature 1)
  37829. * @param {Object} aobj
  37830. * attribute object `{astr1: val1, astr2: val2 ...}`
  37831. * allows setting multiple attributes simultaneously
  37832. */
  37833. function relayout(gd, astr, val) {
  37834. gd = Lib.getGraphDiv(gd);
  37835. helpers.clearPromiseQueue(gd);
  37836. if(gd.framework && gd.framework.isPolar) {
  37837. return Promise.resolve(gd);
  37838. }
  37839. var aobj = {};
  37840. if(typeof astr === 'string') {
  37841. aobj[astr] = val;
  37842. } else if(Lib.isPlainObject(astr)) {
  37843. aobj = Lib.extendFlat({}, astr);
  37844. } else {
  37845. Lib.warn('Relayout fail.', astr, val);
  37846. return Promise.reject();
  37847. }
  37848. if(Object.keys(aobj).length) gd.changed = true;
  37849. var specs = _relayout(gd, aobj);
  37850. var flags = specs.flags;
  37851. // clear calcdata if required
  37852. if(flags.calc) gd.calcdata = undefined;
  37853. // fill in redraw sequence
  37854. // even if we don't have anything left in aobj,
  37855. // something may have happened within relayout that we
  37856. // need to wait for
  37857. var seq = [Plots.previousPromises];
  37858. if(flags.layoutReplot) {
  37859. seq.push(subroutines.layoutReplot);
  37860. }
  37861. else if(Object.keys(aobj).length) {
  37862. axRangeSupplyDefaultsByPass(gd, flags, specs) || Plots.supplyDefaults(gd);
  37863. if(flags.legend) seq.push(subroutines.doLegend);
  37864. if(flags.layoutstyle) seq.push(subroutines.layoutStyles);
  37865. if(flags.axrange) addAxRangeSequence(seq, specs.rangesAltered);
  37866. if(flags.ticks) seq.push(subroutines.doTicksRelayout);
  37867. if(flags.modebar) seq.push(subroutines.doModeBar);
  37868. if(flags.camera) seq.push(subroutines.doCamera);
  37869. seq.push(emitAfterPlot);
  37870. }
  37871. seq.push(Plots.rehover);
  37872. Queue.add(gd,
  37873. relayout, [gd, specs.undoit],
  37874. relayout, [gd, specs.redoit]
  37875. );
  37876. var plotDone = Lib.syncOrAsync(seq, gd);
  37877. if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);
  37878. return plotDone.then(function() {
  37879. gd.emit('plotly_relayout', specs.eventData);
  37880. return gd;
  37881. });
  37882. }
  37883. exports.relayout = relayout;
  37884. // Optimization mostly for large splom traces where
  37885. // Plots.supplyDefaults can take > 100ms
  37886. function axRangeSupplyDefaultsByPass(gd, flags, specs) {
  37887. var k;
  37888. if(!flags.axrange) return false;
  37889. for(k in flags) {
  37890. if(k !== 'axrange' && flags[k]) return false;
  37891. }
  37892. for(k in specs.rangesAltered) {
  37893. var axName = Axes.id2name(k);
  37894. var axIn = gd.layout[axName];
  37895. var axOut = gd._fullLayout[axName];
  37896. axOut.autorange = axIn.autorange;
  37897. axOut.range = axIn.range.slice();
  37898. axOut.cleanRange();
  37899. }
  37900. return true;
  37901. }
  37902. function addAxRangeSequence(seq, rangesAltered) {
  37903. // N.B. leave as sequence of subroutines (for now) instead of
  37904. // subroutine of its own so that finalDraw always gets
  37905. // executed after drawData
  37906. var drawAxes = rangesAltered ?
  37907. function(gd) {
  37908. var opts = {skipTitle: true};
  37909. for(var id in rangesAltered) {
  37910. if(Axes.getFromId(gd, id).automargin) {
  37911. opts = {};
  37912. break;
  37913. }
  37914. }
  37915. return Axes.draw(gd, Object.keys(rangesAltered), opts);
  37916. } :
  37917. function(gd) {
  37918. return Axes.draw(gd, 'redraw');
  37919. };
  37920. seq.push(
  37921. subroutines.doAutoRangeAndConstraints,
  37922. drawAxes,
  37923. subroutines.drawData,
  37924. subroutines.finalDraw
  37925. );
  37926. }
  37927. var AX_RANGE_RE = /^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/;
  37928. var AX_AUTORANGE_RE = /^[xyz]axis[0-9]*\.autorange$/;
  37929. var AX_DOMAIN_RE = /^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/;
  37930. function _relayout(gd, aobj) {
  37931. var layout = gd.layout;
  37932. var fullLayout = gd._fullLayout;
  37933. var guiEditFlag = fullLayout._guiEditing;
  37934. var layoutNP = makeNP(fullLayout._preGUI, guiEditFlag);
  37935. var keys = Object.keys(aobj);
  37936. var axes = Axes.list(gd);
  37937. var eventData = Lib.extendDeepAll({}, aobj);
  37938. var arrayEdits = {};
  37939. var arrayStr, i, j;
  37940. cleanDeprecatedAttributeKeys(aobj);
  37941. keys = Object.keys(aobj);
  37942. // look for 'allaxes', split out into all axes
  37943. // in case of 3D the axis are nested within a scene which is held in _id
  37944. for(i = 0; i < keys.length; i++) {
  37945. if(keys[i].indexOf('allaxes') === 0) {
  37946. for(j = 0; j < axes.length; j++) {
  37947. var scene = axes[j]._id.substr(1);
  37948. var axisAttr = (scene.indexOf('scene') !== -1) ? (scene + '.') : '';
  37949. var newkey = keys[i].replace('allaxes', axisAttr + axes[j]._name);
  37950. if(!aobj[newkey]) aobj[newkey] = aobj[keys[i]];
  37951. }
  37952. delete aobj[keys[i]];
  37953. }
  37954. }
  37955. // initialize flags
  37956. var flags = editTypes.layoutFlags();
  37957. // copies of the change (and previous values of anything affected)
  37958. // for the undo / redo queue
  37959. var redoit = {};
  37960. var undoit = {};
  37961. // for attrs that interact (like scales & autoscales), save the
  37962. // old vals before making the change
  37963. // val=undefined will not set a value, just record what the value was.
  37964. // attr can be an array to set several at once (all to the same val)
  37965. function doextra(attr, val) {
  37966. if(Array.isArray(attr)) {
  37967. attr.forEach(function(a) { doextra(a, val); });
  37968. return;
  37969. }
  37970. // if we have another value for this attribute (explicitly or
  37971. // via a parent) do not override with this auto-generated extra
  37972. if(attr in aobj || helpers.hasParent(aobj, attr)) return;
  37973. var p = layoutNP(layout, attr);
  37974. if(!(attr in undoit)) {
  37975. undoit[attr] = undefinedToNull(p.get());
  37976. }
  37977. if(val !== undefined) p.set(val);
  37978. }
  37979. // for constraint enforcement: keep track of all axes (as {id: name})
  37980. // we're editing the (auto)range of, so we can tell the others constrained
  37981. // to scale with them that it's OK for them to shrink
  37982. var rangesAltered = {};
  37983. var axId;
  37984. function recordAlteredAxis(pleafPlus) {
  37985. var axId = Axes.name2id(pleafPlus.split('.')[0]);
  37986. rangesAltered[axId] = 1;
  37987. return axId;
  37988. }
  37989. // alter gd.layout
  37990. for(var ai in aobj) {
  37991. if(helpers.hasParent(aobj, ai)) {
  37992. throw new Error('cannot set ' + ai + 'and a parent attribute simultaneously');
  37993. }
  37994. var p = layoutNP(layout, ai);
  37995. var vi = aobj[ai];
  37996. var plen = p.parts.length;
  37997. // p.parts may end with an index integer if the property is an array
  37998. var pend = plen - 1;
  37999. while(pend > 0 && typeof p.parts[pend] !== 'string') pend--;
  38000. // last property in chain (leaf node)
  38001. var pleaf = p.parts[pend];
  38002. // leaf plus immediate parent
  38003. var pleafPlus = p.parts[pend - 1] + '.' + pleaf;
  38004. // trunk nodes (everything except the leaf)
  38005. var ptrunk = p.parts.slice(0, pend).join('.');
  38006. var parentIn = nestedProperty(gd.layout, ptrunk).get();
  38007. var parentFull = nestedProperty(fullLayout, ptrunk).get();
  38008. var vOld = p.get();
  38009. if(vi === undefined) continue;
  38010. redoit[ai] = vi;
  38011. // axis reverse is special - it is its own inverse
  38012. // op and has no flag.
  38013. undoit[ai] = (pleaf === 'reverse') ? vi : undefinedToNull(vOld);
  38014. var valObject = PlotSchema.getLayoutValObject(fullLayout, p.parts);
  38015. if(valObject && valObject.impliedEdits && vi !== null) {
  38016. for(var impliedKey in valObject.impliedEdits) {
  38017. doextra(Lib.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]);
  38018. }
  38019. }
  38020. // Setting width or height to null must reset the graph's width / height
  38021. // back to its initial value as computed during the first pass in Plots.plotAutoSize.
  38022. //
  38023. // To do so, we must manually set them back here using the _initialAutoSize cache.
  38024. // can't use impliedEdits for this because behavior depends on vi
  38025. if(['width', 'height'].indexOf(ai) !== -1) {
  38026. if(vi) {
  38027. doextra('autosize', null);
  38028. // currently we don't support autosize one dim only - so
  38029. // explicitly set the other one. Note that doextra will
  38030. // ignore this if the same relayout call also provides oppositeAttr
  38031. var oppositeAttr = ai === 'height' ? 'width' : 'height';
  38032. doextra(oppositeAttr, fullLayout[oppositeAttr]);
  38033. }
  38034. else {
  38035. fullLayout[ai] = gd._initialAutoSize[ai];
  38036. }
  38037. }
  38038. else if(ai === 'autosize') {
  38039. // depends on vi here too, so again can't use impliedEdits
  38040. doextra('width', vi ? null : fullLayout.width);
  38041. doextra('height', vi ? null : fullLayout.height);
  38042. }
  38043. // check autorange vs range
  38044. else if(pleafPlus.match(AX_RANGE_RE)) {
  38045. recordAlteredAxis(pleafPlus);
  38046. nestedProperty(fullLayout, ptrunk + '._inputRange').set(null);
  38047. }
  38048. else if(pleafPlus.match(AX_AUTORANGE_RE)) {
  38049. recordAlteredAxis(pleafPlus);
  38050. nestedProperty(fullLayout, ptrunk + '._inputRange').set(null);
  38051. var axFull = nestedProperty(fullLayout, ptrunk).get();
  38052. if(axFull._inputDomain) {
  38053. // if we're autoranging and this axis has a constrained domain,
  38054. // reset it so we don't get locked into a shrunken size
  38055. axFull._input.domain = axFull._inputDomain.slice();
  38056. }
  38057. }
  38058. else if(pleafPlus.match(AX_DOMAIN_RE)) {
  38059. nestedProperty(fullLayout, ptrunk + '._inputDomain').set(null);
  38060. }
  38061. // toggling axis type between log and linear: we need to convert
  38062. // positions for components that are still using linearized values,
  38063. // not data values like newer components.
  38064. // previously we did this for log <-> not-log, but now only do it
  38065. // for log <-> linear
  38066. if(pleaf === 'type') {
  38067. var ax = parentIn;
  38068. var toLog = parentFull.type === 'linear' && vi === 'log';
  38069. var fromLog = parentFull.type === 'log' && vi === 'linear';
  38070. if(toLog || fromLog) {
  38071. if(!ax || !ax.range) {
  38072. // 2D never gets here, but 3D does
  38073. // I don't think this is needed, but left here in case there
  38074. // are edge cases I'm not thinking of.
  38075. doextra(ptrunk + '.autorange', true);
  38076. }
  38077. else if(!parentFull.autorange) {
  38078. // toggling log without autorange: need to also recalculate ranges
  38079. // because log axes use linearized values for range endpoints
  38080. var r0 = ax.range[0];
  38081. var r1 = ax.range[1];
  38082. if(toLog) {
  38083. // if both limits are negative, autorange
  38084. if(r0 <= 0 && r1 <= 0) {
  38085. doextra(ptrunk + '.autorange', true);
  38086. }
  38087. // if one is negative, set it 6 orders below the other.
  38088. if(r0 <= 0) r0 = r1 / 1e6;
  38089. else if(r1 <= 0) r1 = r0 / 1e6;
  38090. // now set the range values as appropriate
  38091. doextra(ptrunk + '.range[0]', Math.log(r0) / Math.LN10);
  38092. doextra(ptrunk + '.range[1]', Math.log(r1) / Math.LN10);
  38093. }
  38094. else {
  38095. doextra(ptrunk + '.range[0]', Math.pow(10, r0));
  38096. doextra(ptrunk + '.range[1]', Math.pow(10, r1));
  38097. }
  38098. }
  38099. else if(toLog) {
  38100. // just make sure the range is positive and in the right
  38101. // order, it'll get recalculated later
  38102. ax.range = (ax.range[1] > ax.range[0]) ? [1, 2] : [2, 1];
  38103. }
  38104. // clear polar view initial stash for radial range so that
  38105. // value get recomputed in correct units
  38106. if(Array.isArray(fullLayout._subplots.polar) &&
  38107. fullLayout._subplots.polar.length &&
  38108. fullLayout[p.parts[0]] &&
  38109. p.parts[1] === 'radialaxis'
  38110. ) {
  38111. delete fullLayout[p.parts[0]]._subplot.viewInitial['radialaxis.range'];
  38112. }
  38113. // Annotations and images also need to convert to/from linearized coords
  38114. // Shapes do not need this :)
  38115. Registry.getComponentMethod('annotations', 'convertCoords')(gd, parentFull, vi, doextra);
  38116. Registry.getComponentMethod('images', 'convertCoords')(gd, parentFull, vi, doextra);
  38117. }
  38118. else {
  38119. // any other type changes: the range from the previous type
  38120. // will not make sense, so autorange it.
  38121. doextra(ptrunk + '.autorange', true);
  38122. doextra(ptrunk + '.range', null);
  38123. }
  38124. nestedProperty(fullLayout, ptrunk + '._inputRange').set(null);
  38125. }
  38126. else if(pleaf.match(AX_NAME_PATTERN)) {
  38127. var fullProp = nestedProperty(fullLayout, ai).get();
  38128. var newType = (vi || {}).type;
  38129. // This can potentially cause strange behavior if the autotype is not
  38130. // numeric (linear, because we don't auto-log) but the previous type
  38131. // was log. That's a very strange edge case though
  38132. if(!newType || newType === '-') newType = 'linear';
  38133. Registry.getComponentMethod('annotations', 'convertCoords')(gd, fullProp, newType, doextra);
  38134. Registry.getComponentMethod('images', 'convertCoords')(gd, fullProp, newType, doextra);
  38135. }
  38136. // alter gd.layout
  38137. // collect array component edits for execution all together
  38138. // so we can ensure consistent behavior adding/removing items
  38139. // and order-independence for add/remove/edit all together in
  38140. // one relayout call
  38141. var containerArrayMatch = manageArrays.containerArrayMatch(ai);
  38142. if(containerArrayMatch) {
  38143. arrayStr = containerArrayMatch.array;
  38144. i = containerArrayMatch.index;
  38145. var propStr = containerArrayMatch.property;
  38146. var updateValObject = valObject || {editType: 'calc'};
  38147. if(i !== '' && propStr === '') {
  38148. // special handling of undoit if we're adding or removing an element
  38149. // ie 'annotations[2]' which can be {...} (add) or null,
  38150. // does not work when replacing the entire array
  38151. if(manageArrays.isAddVal(vi)) {
  38152. undoit[ai] = null;
  38153. } else if(manageArrays.isRemoveVal(vi)) {
  38154. undoit[ai] = (nestedProperty(layout, arrayStr).get() || [])[i];
  38155. } else {
  38156. Lib.warn('unrecognized full object value', aobj);
  38157. }
  38158. }
  38159. editTypes.update(flags, updateValObject);
  38160. // prepare the edits object we'll send to applyContainerArrayChanges
  38161. if(!arrayEdits[arrayStr]) arrayEdits[arrayStr] = {};
  38162. var objEdits = arrayEdits[arrayStr][i];
  38163. if(!objEdits) objEdits = arrayEdits[arrayStr][i] = {};
  38164. objEdits[propStr] = vi;
  38165. delete aobj[ai];
  38166. }
  38167. // handle axis reversal explicitly, as there's no 'reverse' attribute
  38168. else if(pleaf === 'reverse') {
  38169. if(parentIn.range) parentIn.range.reverse();
  38170. else {
  38171. doextra(ptrunk + '.autorange', true);
  38172. parentIn.range = [1, 0];
  38173. }
  38174. if(parentFull.autorange) flags.calc = true;
  38175. else flags.plot = true;
  38176. }
  38177. else {
  38178. if((fullLayout._has('scatter-like') && fullLayout._has('regl')) &&
  38179. (ai === 'dragmode' &&
  38180. (vi === 'lasso' || vi === 'select') &&
  38181. !(vOld === 'lasso' || vOld === 'select'))
  38182. ) {
  38183. flags.plot = true;
  38184. }
  38185. else if(valObject) editTypes.update(flags, valObject);
  38186. else flags.calc = true;
  38187. p.set(vi);
  38188. }
  38189. }
  38190. // now we've collected component edits - execute them all together
  38191. for(arrayStr in arrayEdits) {
  38192. var finished = manageArrays.applyContainerArrayChanges(gd,
  38193. layoutNP(layout, arrayStr), arrayEdits[arrayStr], flags, layoutNP);
  38194. if(!finished) flags.plot = true;
  38195. }
  38196. // figure out if we need to recalculate axis constraints
  38197. var constraints = fullLayout._axisConstraintGroups || [];
  38198. for(axId in rangesAltered) {
  38199. for(i = 0; i < constraints.length; i++) {
  38200. var group = constraints[i];
  38201. if(group[axId]) {
  38202. // Always recalc if we're changing constrained ranges.
  38203. // Otherwise it's possible to violate the constraints by
  38204. // specifying arbitrary ranges for all axes in the group.
  38205. // this way some ranges may expand beyond what's specified,
  38206. // as they do at first draw, to satisfy the constraints.
  38207. flags.calc = true;
  38208. for(var groupAxId in group) {
  38209. if(!rangesAltered[groupAxId]) {
  38210. Axes.getFromId(gd, groupAxId)._constraintShrinkable = true;
  38211. }
  38212. }
  38213. }
  38214. }
  38215. }
  38216. // If the autosize changed or height or width was explicitly specified,
  38217. // this triggers a redraw
  38218. // TODO: do we really need special aobj.height/width handling here?
  38219. // couldn't editType do this?
  38220. if(updateAutosize(gd) || aobj.height || aobj.width) flags.plot = true;
  38221. if(flags.plot || flags.calc) {
  38222. flags.layoutReplot = true;
  38223. }
  38224. // now all attribute mods are done, as are
  38225. // redo and undo so we can save them
  38226. return {
  38227. flags: flags,
  38228. rangesAltered: rangesAltered,
  38229. undoit: undoit,
  38230. redoit: redoit,
  38231. eventData: eventData
  38232. };
  38233. }
  38234. /*
  38235. * updateAutosize: we made a change, does it change the autosize result?
  38236. * puts the new size into fullLayout
  38237. * returns true if either height or width changed
  38238. */
  38239. function updateAutosize(gd) {
  38240. var fullLayout = gd._fullLayout;
  38241. var oldWidth = fullLayout.width;
  38242. var oldHeight = fullLayout.height;
  38243. // calculate autosizing
  38244. if(gd.layout.autosize) Plots.plotAutoSize(gd, gd.layout, fullLayout);
  38245. return (fullLayout.width !== oldWidth) || (fullLayout.height !== oldHeight);
  38246. }
  38247. /**
  38248. * update: update trace and layout attributes of an existing plot
  38249. *
  38250. * @param {String | HTMLDivElement} gd
  38251. * the id or DOM element of the graph container div
  38252. * @param {Object} traceUpdate
  38253. * attribute object `{astr1: val1, astr2: val2 ...}`
  38254. * corresponding to updates in the plot's traces
  38255. * @param {Object} layoutUpdate
  38256. * attribute object `{astr1: val1, astr2: val2 ...}`
  38257. * corresponding to updates in the plot's layout
  38258. * @param {Number[] | Number} [traces]
  38259. * integer or array of integers for the traces to alter (all if omitted)
  38260. *
  38261. */
  38262. function update(gd, traceUpdate, layoutUpdate, _traces) {
  38263. gd = Lib.getGraphDiv(gd);
  38264. helpers.clearPromiseQueue(gd);
  38265. if(gd.framework && gd.framework.isPolar) {
  38266. return Promise.resolve(gd);
  38267. }
  38268. if(!Lib.isPlainObject(traceUpdate)) traceUpdate = {};
  38269. if(!Lib.isPlainObject(layoutUpdate)) layoutUpdate = {};
  38270. if(Object.keys(traceUpdate).length) gd.changed = true;
  38271. if(Object.keys(layoutUpdate).length) gd.changed = true;
  38272. var traces = helpers.coerceTraceIndices(gd, _traces);
  38273. var restyleSpecs = _restyle(gd, Lib.extendFlat({}, traceUpdate), traces);
  38274. var restyleFlags = restyleSpecs.flags;
  38275. var relayoutSpecs = _relayout(gd, Lib.extendFlat({}, layoutUpdate));
  38276. var relayoutFlags = relayoutSpecs.flags;
  38277. // clear calcdata and/or axis types if required
  38278. if(restyleFlags.calc || relayoutFlags.calc) gd.calcdata = undefined;
  38279. if(restyleFlags.clearAxisTypes) helpers.clearAxisTypes(gd, traces, layoutUpdate);
  38280. // fill in redraw sequence
  38281. var seq = [];
  38282. if(restyleFlags.fullReplot && relayoutFlags.layoutReplot) {
  38283. var data = gd.data;
  38284. var layout = gd.layout;
  38285. // clear existing data/layout on gd
  38286. // so that Plotly.plot doesn't try to extend them
  38287. gd.data = undefined;
  38288. gd.layout = undefined;
  38289. seq.push(function() { return exports.plot(gd, data, layout); });
  38290. }
  38291. else if(restyleFlags.fullReplot) {
  38292. seq.push(exports.plot);
  38293. }
  38294. else if(relayoutFlags.layoutReplot) {
  38295. seq.push(subroutines.layoutReplot);
  38296. }
  38297. else {
  38298. seq.push(Plots.previousPromises);
  38299. axRangeSupplyDefaultsByPass(gd, relayoutFlags, relayoutSpecs) || Plots.supplyDefaults(gd);
  38300. if(restyleFlags.style) seq.push(subroutines.doTraceStyle);
  38301. if(restyleFlags.colorbars) seq.push(subroutines.doColorBars);
  38302. if(relayoutFlags.legend) seq.push(subroutines.doLegend);
  38303. if(relayoutFlags.layoutstyle) seq.push(subroutines.layoutStyles);
  38304. if(relayoutFlags.axrange) addAxRangeSequence(seq, relayoutSpecs.rangesAltered);
  38305. if(relayoutFlags.ticks) seq.push(subroutines.doTicksRelayout);
  38306. if(relayoutFlags.modebar) seq.push(subroutines.doModeBar);
  38307. if(relayoutFlags.camera) seq.push(subroutines.doCamera);
  38308. seq.push(emitAfterPlot);
  38309. }
  38310. seq.push(Plots.rehover);
  38311. Queue.add(gd,
  38312. update, [gd, restyleSpecs.undoit, relayoutSpecs.undoit, restyleSpecs.traces],
  38313. update, [gd, restyleSpecs.redoit, relayoutSpecs.redoit, restyleSpecs.traces]
  38314. );
  38315. var plotDone = Lib.syncOrAsync(seq, gd);
  38316. if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);
  38317. return plotDone.then(function() {
  38318. gd.emit('plotly_update', {
  38319. data: restyleSpecs.eventData,
  38320. layout: relayoutSpecs.eventData
  38321. });
  38322. return gd;
  38323. });
  38324. }
  38325. exports.update = update;
  38326. /*
  38327. * internal-use-only restyle/relayout/update variants that record the initial
  38328. * values in (fullLayout|fullTrace)._preGUI so changes can be persisted across
  38329. * Plotly.react data updates, dependent on uirevision attributes
  38330. */
  38331. function guiEdit(func) {
  38332. return function wrappedEdit(gd) {
  38333. gd._fullLayout._guiEditing = true;
  38334. var p = func.apply(null, arguments);
  38335. gd._fullLayout._guiEditing = false;
  38336. return p;
  38337. };
  38338. }
  38339. exports._guiRestyle = guiEdit(restyle);
  38340. exports._guiRelayout = guiEdit(relayout);
  38341. exports._guiUpdate = guiEdit(update);
  38342. // For connecting edited layout attributes to uirevision attrs
  38343. // If no `attr` we use `match[1] + '.uirevision'`
  38344. // Ordered by most common edits first, to minimize our search time
  38345. var layoutUIControlPatterns = [
  38346. {pattern: /^hiddenlabels/, attr: 'legend.uirevision'},
  38347. {pattern: /^((x|y)axis\d*)\.((auto)?range|title\.text)/},
  38348. // showspikes and modes include those nested inside scenes
  38349. {pattern: /axis\d*\.showspikes$/, attr: 'modebar.uirevision'},
  38350. {pattern: /(hover|drag)mode$/, attr: 'modebar.uirevision'},
  38351. {pattern: /^(scene\d*)\.camera/},
  38352. {pattern: /^(geo\d*)\.(projection|center)/},
  38353. {pattern: /^(ternary\d*\.[abc]axis)\.(min|title\.text)$/},
  38354. {pattern: /^(polar\d*\.radialaxis)\.((auto)?range|angle|title\.text)/},
  38355. {pattern: /^(polar\d*\.angularaxis)\.rotation/},
  38356. {pattern: /^(mapbox\d*)\.(center|zoom|bearing|pitch)/},
  38357. {pattern: /^legend\.(x|y)$/, attr: 'editrevision'},
  38358. {pattern: /^(shapes|annotations)/, attr: 'editrevision'},
  38359. {pattern: /^title\.text$/, attr: 'editrevision'}
  38360. ];
  38361. // same for trace attributes: if `attr` is given it's in layout,
  38362. // or with no `attr` we use `trace.uirevision`
  38363. var traceUIControlPatterns = [
  38364. {pattern: /^selectedpoints$/, attr: 'selectionrevision'},
  38365. // "visible" includes trace.transforms[i].styles[j].value.visible
  38366. {pattern: /(^|value\.)visible$/, attr: 'legend.uirevision'},
  38367. {pattern: /^dimensions\[\d+\]\.constraintrange/},
  38368. // below this you must be in editable: true mode
  38369. // TODO: I still put name and title with `trace.uirevision`
  38370. // reasonable or should these be `editrevision`?
  38371. // Also applies to axis titles up in the layout section
  38372. // "name" also includes transform.styles
  38373. {pattern: /(^|value\.)name$/},
  38374. // including nested colorbar attributes (ie marker.colorbar)
  38375. {pattern: /colorbar\.title\.text$/},
  38376. {pattern: /colorbar\.(x|y)$/, attr: 'editrevision'}
  38377. ];
  38378. function findUIPattern(key, patternSpecs) {
  38379. for(var i = 0; i < patternSpecs.length; i++) {
  38380. var spec = patternSpecs[i];
  38381. var match = key.match(spec.pattern);
  38382. if(match) {
  38383. return {head: match[1], attr: spec.attr};
  38384. }
  38385. }
  38386. }
  38387. // We're finding the new uirevision before supplyDefaults, so do the
  38388. // inheritance manually. Note that only `undefined` inherits - other
  38389. // falsy values are returned.
  38390. function getNewRev(revAttr, container) {
  38391. var newRev = nestedProperty(container, revAttr).get();
  38392. if(newRev !== undefined) return newRev;
  38393. var parts = revAttr.split('.');
  38394. parts.pop();
  38395. while(parts.length > 1) {
  38396. parts.pop();
  38397. newRev = nestedProperty(container, parts.join('.') + '.uirevision').get();
  38398. if(newRev !== undefined) return newRev;
  38399. }
  38400. return container.uirevision;
  38401. }
  38402. function getFullTraceIndexFromUid(uid, fullData) {
  38403. for(var i = 0; i < fullData.length; i++) {
  38404. if(fullData[i]._fullInput.uid === uid) return i;
  38405. }
  38406. return -1;
  38407. }
  38408. function getTraceIndexFromUid(uid, data, tracei) {
  38409. for(var i = 0; i < data.length; i++) {
  38410. if(data[i].uid === uid) return i;
  38411. }
  38412. // fall back on trace order, but only if user didn't provide a uid for that trace
  38413. return (!data[tracei] || data[tracei].uid) ? -1 : tracei;
  38414. }
  38415. function valsMatch(v1, v2) {
  38416. var v1IsObj = Lib.isPlainObject(v1);
  38417. var v1IsArray = Array.isArray(v1);
  38418. if(v1IsObj || v1IsArray) {
  38419. return (
  38420. (v1IsObj && Lib.isPlainObject(v2)) ||
  38421. (v1IsArray && Array.isArray(v2))
  38422. ) && JSON.stringify(v1) === JSON.stringify(v2);
  38423. }
  38424. return v1 === v2;
  38425. }
  38426. function applyUIRevisions(data, layout, oldFullData, oldFullLayout) {
  38427. var layoutPreGUI = oldFullLayout._preGUI;
  38428. var key, revAttr, oldRev, newRev, match, preGUIVal, newNP, newVal;
  38429. var bothInheritAutorange = [];
  38430. var newRangeAccepted = {};
  38431. for(key in layoutPreGUI) {
  38432. match = findUIPattern(key, layoutUIControlPatterns);
  38433. if(match) {
  38434. revAttr = match.attr || (match.head + '.uirevision');
  38435. oldRev = nestedProperty(oldFullLayout, revAttr).get();
  38436. newRev = oldRev && getNewRev(revAttr, layout);
  38437. if(newRev && (newRev === oldRev)) {
  38438. preGUIVal = layoutPreGUI[key];
  38439. if(preGUIVal === null) preGUIVal = undefined;
  38440. newNP = nestedProperty(layout, key);
  38441. newVal = newNP.get();
  38442. if(valsMatch(newVal, preGUIVal)) {
  38443. if(newVal === undefined && key.substr(key.length - 9) === 'autorange') {
  38444. bothInheritAutorange.push(key.substr(0, key.length - 10));
  38445. }
  38446. newNP.set(undefinedToNull(nestedProperty(oldFullLayout, key).get()));
  38447. continue;
  38448. }
  38449. }
  38450. }
  38451. else {
  38452. Lib.warn('unrecognized GUI edit: ' + key);
  38453. }
  38454. // if we got this far, the new value was accepted as the new starting
  38455. // point (either because it changed or revision changed)
  38456. // so remove it from _preGUI for next time.
  38457. delete layoutPreGUI[key];
  38458. if(key.substr(key.length - 8, 6) === 'range[') {
  38459. newRangeAccepted[key.substr(0, key.length - 9)] = 1;
  38460. }
  38461. }
  38462. // Special logic for `autorange`, since it interacts with `range`:
  38463. // If the new figure's matching `range` was kept, and `autorange`
  38464. // wasn't supplied explicitly in either the original or the new figure,
  38465. // we shouldn't alter that - but we may just have done that, so fix it.
  38466. for(var i = 0; i < bothInheritAutorange.length; i++) {
  38467. var axAttr = bothInheritAutorange[i];
  38468. if(newRangeAccepted[axAttr]) {
  38469. var newAx = nestedProperty(layout, axAttr).get();
  38470. if(newAx) delete newAx.autorange;
  38471. }
  38472. }
  38473. // Now traces - try to match them up by uid (in case we added/deleted in
  38474. // the middle), then fall back on index.
  38475. var allTracePreGUI = oldFullLayout._tracePreGUI;
  38476. for(var uid in allTracePreGUI) {
  38477. var tracePreGUI = allTracePreGUI[uid];
  38478. var newTrace = null;
  38479. var fullInput;
  38480. for(key in tracePreGUI) {
  38481. // wait until we know we have preGUI values to look for traces
  38482. // but if we don't find both, stop looking at this uid
  38483. if(!newTrace) {
  38484. var fulli = getFullTraceIndexFromUid(uid, oldFullData);
  38485. if(fulli < 0) {
  38486. // Somehow we didn't even have this trace in oldFullData...
  38487. // I guess this could happen with `deleteTraces` or something
  38488. delete allTracePreGUI[uid];
  38489. break;
  38490. }
  38491. var fullTrace = oldFullData[fulli];
  38492. fullInput = fullTrace._fullInput;
  38493. var newTracei = getTraceIndexFromUid(uid, data, fullInput.index);
  38494. if(newTracei < 0) {
  38495. // No match in new data
  38496. delete allTracePreGUI[uid];
  38497. break;
  38498. }
  38499. newTrace = data[newTracei];
  38500. }
  38501. match = findUIPattern(key, traceUIControlPatterns);
  38502. if(match) {
  38503. if(match.attr) {
  38504. oldRev = nestedProperty(oldFullLayout, match.attr).get();
  38505. newRev = oldRev && getNewRev(match.attr, layout);
  38506. }
  38507. else {
  38508. oldRev = fullInput.uirevision;
  38509. // inheritance for trace.uirevision is simple, just layout.uirevision
  38510. newRev = newTrace.uirevision;
  38511. if(newRev === undefined) newRev = layout.uirevision;
  38512. }
  38513. if(newRev && newRev === oldRev) {
  38514. preGUIVal = tracePreGUI[key];
  38515. if(preGUIVal === null) preGUIVal = undefined;
  38516. newNP = nestedProperty(newTrace, key);
  38517. newVal = newNP.get();
  38518. if(valsMatch(newVal, preGUIVal)) {
  38519. newNP.set(undefinedToNull(nestedProperty(fullInput, key).get()));
  38520. continue;
  38521. }
  38522. }
  38523. }
  38524. else {
  38525. Lib.warn('unrecognized GUI edit: ' + key + ' in trace uid ' + uid);
  38526. }
  38527. delete tracePreGUI[key];
  38528. }
  38529. }
  38530. }
  38531. /**
  38532. * Plotly.react:
  38533. * A plot/update method that takes the full plot state (same API as plot/newPlot)
  38534. * and diffs to determine the minimal update pathway
  38535. *
  38536. * @param {string id or DOM element} gd
  38537. * the id or DOM element of the graph container div
  38538. * @param {array of objects} data
  38539. * array of traces, containing the data and display information for each trace
  38540. * @param {object} layout
  38541. * object describing the overall display of the plot,
  38542. * all the stuff that doesn't pertain to any individual trace
  38543. * @param {object} config
  38544. * configuration options (see ./plot_config.js for more info)
  38545. *
  38546. * OR
  38547. *
  38548. * @param {string id or DOM element} gd
  38549. * the id or DOM element of the graph container div
  38550. * @param {object} figure
  38551. * object containing `data`, `layout`, `config`, and `frames` members
  38552. *
  38553. */
  38554. exports.react = function(gd, data, layout, config) {
  38555. var frames, plotDone;
  38556. function addFrames() { return exports.addFrames(gd, frames); }
  38557. gd = Lib.getGraphDiv(gd);
  38558. var oldFullData = gd._fullData;
  38559. var oldFullLayout = gd._fullLayout;
  38560. // you can use this as the initial draw as well as to update
  38561. if(!Lib.isPlotDiv(gd) || !oldFullData || !oldFullLayout) {
  38562. plotDone = exports.newPlot(gd, data, layout, config);
  38563. }
  38564. else {
  38565. if(Lib.isPlainObject(data)) {
  38566. var obj = data;
  38567. data = obj.data;
  38568. layout = obj.layout;
  38569. config = obj.config;
  38570. frames = obj.frames;
  38571. }
  38572. var configChanged = false;
  38573. // assume that if there's a config at all, we're reacting to it too,
  38574. // and completely replace the previous config
  38575. if(config) {
  38576. var oldConfig = Lib.extendDeep({}, gd._context);
  38577. gd._context = undefined;
  38578. setPlotContext(gd, config);
  38579. configChanged = diffConfig(oldConfig, gd._context);
  38580. }
  38581. gd.data = data || [];
  38582. helpers.cleanData(gd.data);
  38583. gd.layout = layout || {};
  38584. helpers.cleanLayout(gd.layout);
  38585. applyUIRevisions(gd.data, gd.layout, oldFullData, oldFullLayout);
  38586. // "true" skips updating calcdata and remapping arrays from calcTransforms,
  38587. // which supplyDefaults usually does at the end, but we may need to NOT do
  38588. // if the diff (which we haven't determined yet) says we'll recalc
  38589. Plots.supplyDefaults(gd, {skipUpdateCalc: true});
  38590. var newFullData = gd._fullData;
  38591. var newFullLayout = gd._fullLayout;
  38592. var immutable = newFullLayout.datarevision === undefined;
  38593. var transition = newFullLayout.transition;
  38594. var relayoutFlags = diffLayout(gd, oldFullLayout, newFullLayout, immutable, transition);
  38595. var newDataRevision = relayoutFlags.newDataRevision;
  38596. var restyleFlags = diffData(gd, oldFullData, newFullData, immutable, transition, newDataRevision);
  38597. // TODO: how to translate this part of relayout to Plotly.react?
  38598. // // Setting width or height to null must reset the graph's width / height
  38599. // // back to its initial value as computed during the first pass in Plots.plotAutoSize.
  38600. // //
  38601. // // To do so, we must manually set them back here using the _initialAutoSize cache.
  38602. // if(['width', 'height'].indexOf(ai) !== -1 && vi === null) {
  38603. // fullLayout[ai] = gd._initialAutoSize[ai];
  38604. // }
  38605. if(updateAutosize(gd)) relayoutFlags.layoutReplot = true;
  38606. // clear calcdata if required
  38607. if(restyleFlags.calc || relayoutFlags.calc) gd.calcdata = undefined;
  38608. // otherwise do the calcdata updates and calcTransform array remaps that we skipped earlier
  38609. else Plots.supplyDefaultsUpdateCalc(gd.calcdata, newFullData);
  38610. // Note: what restyle/relayout use impliedEdits and clearAxisTypes for
  38611. // must be handled by the user when using Plotly.react.
  38612. // fill in redraw sequence
  38613. var seq = [];
  38614. if(frames) {
  38615. gd._transitionData = {};
  38616. Plots.createTransitionData(gd);
  38617. seq.push(addFrames);
  38618. }
  38619. // Transition pathway,
  38620. // only used when 'transition' is set by user and
  38621. // when at least one animatable attribute has changed,
  38622. // N.B. config changed aren't animatable
  38623. if(newFullLayout.transition && !configChanged && (restyleFlags.anim || relayoutFlags.anim)) {
  38624. Plots.doCalcdata(gd);
  38625. subroutines.doAutoRangeAndConstraints(gd);
  38626. seq.push(function() {
  38627. return Plots.transitionFromReact(gd, restyleFlags, relayoutFlags, oldFullLayout);
  38628. });
  38629. }
  38630. else if(restyleFlags.fullReplot || relayoutFlags.layoutReplot || configChanged) {
  38631. gd._fullLayout._skipDefaults = true;
  38632. seq.push(exports.plot);
  38633. }
  38634. else {
  38635. for(var componentType in relayoutFlags.arrays) {
  38636. var indices = relayoutFlags.arrays[componentType];
  38637. if(indices.length) {
  38638. var drawOne = Registry.getComponentMethod(componentType, 'drawOne');
  38639. if(drawOne !== Lib.noop) {
  38640. for(var i = 0; i < indices.length; i++) {
  38641. drawOne(gd, indices[i]);
  38642. }
  38643. }
  38644. else {
  38645. var draw = Registry.getComponentMethod(componentType, 'draw');
  38646. if(draw === Lib.noop) {
  38647. throw new Error('cannot draw components: ' + componentType);
  38648. }
  38649. draw(gd);
  38650. }
  38651. }
  38652. }
  38653. seq.push(Plots.previousPromises);
  38654. if(restyleFlags.style) seq.push(subroutines.doTraceStyle);
  38655. if(restyleFlags.colorbars) seq.push(subroutines.doColorBars);
  38656. if(relayoutFlags.legend) seq.push(subroutines.doLegend);
  38657. if(relayoutFlags.layoutstyle) seq.push(subroutines.layoutStyles);
  38658. if(relayoutFlags.axrange) addAxRangeSequence(seq);
  38659. if(relayoutFlags.ticks) seq.push(subroutines.doTicksRelayout);
  38660. if(relayoutFlags.modebar) seq.push(subroutines.doModeBar);
  38661. if(relayoutFlags.camera) seq.push(subroutines.doCamera);
  38662. seq.push(emitAfterPlot);
  38663. }
  38664. seq.push(Plots.rehover);
  38665. plotDone = Lib.syncOrAsync(seq, gd);
  38666. if(!plotDone || !plotDone.then) plotDone = Promise.resolve(gd);
  38667. }
  38668. return plotDone.then(function() {
  38669. gd.emit('plotly_react', {
  38670. data: data,
  38671. layout: layout
  38672. });
  38673. return gd;
  38674. });
  38675. };
  38676. function diffData(gd, oldFullData, newFullData, immutable, transition, newDataRevision) {
  38677. var sameTraceLength = oldFullData.length === newFullData.length;
  38678. if(!transition && !sameTraceLength) {
  38679. return {
  38680. fullReplot: true,
  38681. calc: true
  38682. };
  38683. }
  38684. var flags = editTypes.traceFlags();
  38685. flags.arrays = {};
  38686. flags.nChanges = 0;
  38687. flags.nChangesAnim = 0;
  38688. var i, trace;
  38689. function getTraceValObject(parts) {
  38690. return PlotSchema.getTraceValObject(trace, parts);
  38691. }
  38692. var diffOpts = {
  38693. getValObject: getTraceValObject,
  38694. flags: flags,
  38695. immutable: immutable,
  38696. transition: transition,
  38697. newDataRevision: newDataRevision,
  38698. gd: gd
  38699. };
  38700. var seenUIDs = {};
  38701. for(i = 0; i < oldFullData.length; i++) {
  38702. if(newFullData[i]) {
  38703. trace = newFullData[i]._fullInput;
  38704. if(Plots.hasMakesDataTransform(trace)) trace = newFullData[i];
  38705. if(seenUIDs[trace.uid]) continue;
  38706. seenUIDs[trace.uid] = 1;
  38707. getDiffFlags(oldFullData[i]._fullInput, trace, [], diffOpts);
  38708. }
  38709. }
  38710. if(flags.calc || flags.plot) {
  38711. flags.fullReplot = true;
  38712. }
  38713. if(transition && flags.nChanges && flags.nChangesAnim) {
  38714. flags.anim = (flags.nChanges === flags.nChangesAnim) && sameTraceLength ? 'all' : 'some';
  38715. }
  38716. return flags;
  38717. }
  38718. function diffLayout(gd, oldFullLayout, newFullLayout, immutable, transition) {
  38719. var flags = editTypes.layoutFlags();
  38720. flags.arrays = {};
  38721. flags.rangesAltered = {};
  38722. flags.nChanges = 0;
  38723. flags.nChangesAnim = 0;
  38724. function getLayoutValObject(parts) {
  38725. return PlotSchema.getLayoutValObject(newFullLayout, parts);
  38726. }
  38727. var diffOpts = {
  38728. getValObject: getLayoutValObject,
  38729. flags: flags,
  38730. immutable: immutable,
  38731. transition: transition,
  38732. gd: gd
  38733. };
  38734. getDiffFlags(oldFullLayout, newFullLayout, [], diffOpts);
  38735. if(flags.plot || flags.calc) {
  38736. flags.layoutReplot = true;
  38737. }
  38738. if(transition && flags.nChanges && flags.nChangesAnim) {
  38739. flags.anim = flags.nChanges === flags.nChangesAnim ? 'all' : 'some';
  38740. }
  38741. return flags;
  38742. }
  38743. function getDiffFlags(oldContainer, newContainer, outerparts, opts) {
  38744. var valObject, key, astr;
  38745. var getValObject = opts.getValObject;
  38746. var flags = opts.flags;
  38747. var immutable = opts.immutable;
  38748. var inArray = opts.inArray;
  38749. var arrayIndex = opts.arrayIndex;
  38750. function changed() {
  38751. var editType = valObject.editType;
  38752. if(inArray && editType.indexOf('arraydraw') !== -1) {
  38753. Lib.pushUnique(flags.arrays[inArray], arrayIndex);
  38754. return;
  38755. }
  38756. editTypes.update(flags, valObject);
  38757. if(editType !== 'none') {
  38758. flags.nChanges++;
  38759. }
  38760. // track animatable changes
  38761. if(opts.transition && valObject.anim) {
  38762. flags.nChangesAnim++;
  38763. }
  38764. // track cartesian axes with altered ranges
  38765. if(AX_RANGE_RE.test(astr) || AX_AUTORANGE_RE.test(astr)) {
  38766. flags.rangesAltered[outerparts[0]] = 1;
  38767. }
  38768. // clear _inputDomain on cartesian axes with altered domains
  38769. if(AX_DOMAIN_RE.test(astr)) {
  38770. nestedProperty(newContainer, '_inputDomain').set(null);
  38771. }
  38772. // track datarevision changes
  38773. if(key === 'datarevision') {
  38774. flags.newDataRevision = 1;
  38775. }
  38776. }
  38777. function valObjectCanBeDataArray(valObject) {
  38778. return valObject.valType === 'data_array' || valObject.arrayOk;
  38779. }
  38780. for(key in oldContainer) {
  38781. // short-circuit based on previous calls or previous keys that already maximized the pathway
  38782. if(flags.calc && !opts.transition) return;
  38783. var oldVal = oldContainer[key];
  38784. var newVal = newContainer[key];
  38785. var parts = outerparts.concat(key);
  38786. astr = parts.join('.');
  38787. if(key.charAt(0) === '_' || typeof oldVal === 'function' || oldVal === newVal) continue;
  38788. // FIXME: ax.tick0 and dtick get filled in during plotting (except for geo subplots),
  38789. // and unlike other auto values they don't make it back into the input,
  38790. // so newContainer won't have them.
  38791. if((key === 'tick0' || key === 'dtick') && outerparts[0] !== 'geo') {
  38792. var tickMode = newContainer.tickmode;
  38793. if(tickMode === 'auto' || tickMode === 'array' || !tickMode) continue;
  38794. }
  38795. // FIXME: Similarly for axis ranges for 3D
  38796. // contourcarpet doesn't HAVE zmin/zmax, they're just auto-added. It needs them.
  38797. if(key === 'range' && newContainer.autorange) continue;
  38798. if((key === 'zmin' || key === 'zmax') && newContainer.type === 'contourcarpet') continue;
  38799. valObject = getValObject(parts);
  38800. // in case type changed, we may not even *have* a valObject.
  38801. if(!valObject) continue;
  38802. if(valObject._compareAsJSON && JSON.stringify(oldVal) === JSON.stringify(newVal)) continue;
  38803. var valType = valObject.valType;
  38804. var i;
  38805. var canBeDataArray = valObjectCanBeDataArray(valObject);
  38806. var wasArray = Array.isArray(oldVal);
  38807. var nowArray = Array.isArray(newVal);
  38808. // hack for traces that modify the data in supplyDefaults, like
  38809. // converting 1D to 2D arrays, which will always create new objects
  38810. if(wasArray && nowArray) {
  38811. var inputKey = '_input_' + key;
  38812. var oldValIn = oldContainer[inputKey];
  38813. var newValIn = newContainer[inputKey];
  38814. if(Array.isArray(oldValIn) && oldValIn === newValIn) continue;
  38815. }
  38816. if(newVal === undefined) {
  38817. if(canBeDataArray && wasArray) flags.calc = true;
  38818. else changed();
  38819. }
  38820. else if(valObject._isLinkedToArray) {
  38821. var arrayEditIndices = [];
  38822. var extraIndices = false;
  38823. if(!inArray) flags.arrays[key] = arrayEditIndices;
  38824. var minLen = Math.min(oldVal.length, newVal.length);
  38825. var maxLen = Math.max(oldVal.length, newVal.length);
  38826. if(minLen !== maxLen) {
  38827. if(valObject.editType === 'arraydraw') {
  38828. extraIndices = true;
  38829. }
  38830. else {
  38831. changed();
  38832. continue;
  38833. }
  38834. }
  38835. for(i = 0; i < minLen; i++) {
  38836. getDiffFlags(oldVal[i], newVal[i], parts.concat(i),
  38837. // add array indices, but not if we're already in an array
  38838. Lib.extendFlat({inArray: key, arrayIndex: i}, opts));
  38839. }
  38840. // put this at the end so that we know our collected array indices are sorted
  38841. // but the check for length changes happens up front so we can short-circuit
  38842. // diffing if appropriate
  38843. if(extraIndices) {
  38844. for(i = minLen; i < maxLen; i++) {
  38845. arrayEditIndices.push(i);
  38846. }
  38847. }
  38848. }
  38849. else if(!valType && Lib.isPlainObject(oldVal)) {
  38850. getDiffFlags(oldVal, newVal, parts, opts);
  38851. }
  38852. else if(canBeDataArray) {
  38853. if(wasArray && nowArray) {
  38854. // don't try to diff two data arrays. If immutable we know the data changed,
  38855. // if not, assume it didn't and let `layout.datarevision` tell us if it did
  38856. if(immutable) {
  38857. flags.calc = true;
  38858. }
  38859. // look for animatable attributes when the data changed
  38860. if(immutable || opts.newDataRevision) {
  38861. changed();
  38862. }
  38863. }
  38864. else if(wasArray !== nowArray) {
  38865. flags.calc = true;
  38866. }
  38867. else changed();
  38868. }
  38869. else if(wasArray && nowArray) {
  38870. // info array, colorscale, 'any' - these are short, just stringify.
  38871. // I don't *think* that covers up any real differences post-validation, does it?
  38872. // otherwise we need to dive in 1 (info_array) or 2 (colorscale) levels and compare
  38873. // all elements.
  38874. if(oldVal.length !== newVal.length || String(oldVal) !== String(newVal)) {
  38875. changed();
  38876. }
  38877. }
  38878. else {
  38879. changed();
  38880. }
  38881. }
  38882. for(key in newContainer) {
  38883. if(!(key in oldContainer || key.charAt(0) === '_' || typeof newContainer[key] === 'function')) {
  38884. valObject = getValObject(outerparts.concat(key));
  38885. if(valObjectCanBeDataArray(valObject) && Array.isArray(newContainer[key])) {
  38886. flags.calc = true;
  38887. return;
  38888. }
  38889. else changed();
  38890. }
  38891. }
  38892. }
  38893. /*
  38894. * simple diff for config - for now, just treat all changes as equivalent
  38895. */
  38896. function diffConfig(oldConfig, newConfig) {
  38897. var key;
  38898. for(key in oldConfig) {
  38899. if(key.charAt(0) === '_') continue;
  38900. var oldVal = oldConfig[key];
  38901. var newVal = newConfig[key];
  38902. if(oldVal !== newVal) {
  38903. if(Lib.isPlainObject(oldVal) && Lib.isPlainObject(newVal)) {
  38904. if(diffConfig(oldVal, newVal)) {
  38905. return true;
  38906. }
  38907. }
  38908. else if(Array.isArray(oldVal) && Array.isArray(newVal)) {
  38909. if(oldVal.length !== newVal.length) {
  38910. return true;
  38911. }
  38912. for(var i = 0; i < oldVal.length; i++) {
  38913. if(oldVal[i] !== newVal[i]) {
  38914. if(Lib.isPlainObject(oldVal[i]) && Lib.isPlainObject(newVal[i])) {
  38915. if(diffConfig(oldVal[i], newVal[i])) {
  38916. return true;
  38917. }
  38918. }
  38919. else {
  38920. return true;
  38921. }
  38922. }
  38923. }
  38924. }
  38925. else {
  38926. return true;
  38927. }
  38928. }
  38929. }
  38930. }
  38931. /**
  38932. * Animate to a frame, sequence of frame, frame group, or frame definition
  38933. *
  38934. * @param {string id or DOM element} gd
  38935. * the id or DOM element of the graph container div
  38936. *
  38937. * @param {string or object or array of strings or array of objects} frameOrGroupNameOrFrameList
  38938. * a single frame, array of frames, or group to which to animate. The intent is
  38939. * inferred by the type of the input. Valid inputs are:
  38940. *
  38941. * - string, e.g. 'groupname': animate all frames of a given `group` in the order
  38942. * in which they are defined via `Plotly.addFrames`.
  38943. *
  38944. * - array of strings, e.g. ['frame1', frame2']: a list of frames by name to which
  38945. * to animate in sequence
  38946. *
  38947. * - object: {data: ...}: a frame definition to which to animate. The frame is not
  38948. * and does not need to be added via `Plotly.addFrames`. It may contain any of
  38949. * the properties of a frame, including `data`, `layout`, and `traces`. The
  38950. * frame is used as provided and does not use the `baseframe` property.
  38951. *
  38952. * - array of objects, e.g. [{data: ...}, {data: ...}]: a list of frame objects,
  38953. * each following the same rules as a single `object`.
  38954. *
  38955. * @param {object} animationOpts
  38956. * configuration for the animation
  38957. */
  38958. exports.animate = function(gd, frameOrGroupNameOrFrameList, animationOpts) {
  38959. gd = Lib.getGraphDiv(gd);
  38960. if(!Lib.isPlotDiv(gd)) {
  38961. throw new Error(
  38962. 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' +
  38963. 'to create a plot before animating it. For more details, see ' +
  38964. 'https://plot.ly/javascript/animations/'
  38965. );
  38966. }
  38967. var trans = gd._transitionData;
  38968. // This is the queue of frames that will be animated as soon as possible. They
  38969. // are popped immediately upon the *start* of a transition:
  38970. if(!trans._frameQueue) {
  38971. trans._frameQueue = [];
  38972. }
  38973. animationOpts = Plots.supplyAnimationDefaults(animationOpts);
  38974. var transitionOpts = animationOpts.transition;
  38975. var frameOpts = animationOpts.frame;
  38976. // Since frames are popped immediately, an empty queue only means all frames have
  38977. // *started* to transition, not that the animation is complete. To solve that,
  38978. // track a separate counter that increments at the same time as frames are added
  38979. // to the queue, but decrements only when the transition is complete.
  38980. if(trans._frameWaitingCnt === undefined) {
  38981. trans._frameWaitingCnt = 0;
  38982. }
  38983. function getTransitionOpts(i) {
  38984. if(Array.isArray(transitionOpts)) {
  38985. if(i >= transitionOpts.length) {
  38986. return transitionOpts[0];
  38987. } else {
  38988. return transitionOpts[i];
  38989. }
  38990. } else {
  38991. return transitionOpts;
  38992. }
  38993. }
  38994. function getFrameOpts(i) {
  38995. if(Array.isArray(frameOpts)) {
  38996. if(i >= frameOpts.length) {
  38997. return frameOpts[0];
  38998. } else {
  38999. return frameOpts[i];
  39000. }
  39001. } else {
  39002. return frameOpts;
  39003. }
  39004. }
  39005. // Execute a callback after the wrapper function has been called n times.
  39006. // This is used to defer the resolution until a transition has resovled *and*
  39007. // the frame has completed. If it's not done this way, then we get a race
  39008. // condition in which the animation might resolve before a transition is complete
  39009. // or vice versa.
  39010. function callbackOnNthTime(cb, n) {
  39011. var cnt = 0;
  39012. return function() {
  39013. if(cb && ++cnt === n) {
  39014. return cb();
  39015. }
  39016. };
  39017. }
  39018. return new Promise(function(resolve, reject) {
  39019. function discardExistingFrames() {
  39020. if(trans._frameQueue.length === 0) {
  39021. return;
  39022. }
  39023. while(trans._frameQueue.length) {
  39024. var next = trans._frameQueue.pop();
  39025. if(next.onInterrupt) {
  39026. next.onInterrupt();
  39027. }
  39028. }
  39029. gd.emit('plotly_animationinterrupted', []);
  39030. }
  39031. function queueFrames(frameList) {
  39032. if(frameList.length === 0) return;
  39033. for(var i = 0; i < frameList.length; i++) {
  39034. var computedFrame;
  39035. if(frameList[i].type === 'byname') {
  39036. // If it's a named frame, compute it:
  39037. computedFrame = Plots.computeFrame(gd, frameList[i].name);
  39038. } else {
  39039. // Otherwise we must have been given a simple object, so treat
  39040. // the input itself as the computed frame.
  39041. computedFrame = frameList[i].data;
  39042. }
  39043. var frameOpts = getFrameOpts(i);
  39044. var transitionOpts = getTransitionOpts(i);
  39045. // It doesn't make much sense for the transition duration to be greater than
  39046. // the frame duration, so limit it:
  39047. transitionOpts.duration = Math.min(transitionOpts.duration, frameOpts.duration);
  39048. var nextFrame = {
  39049. frame: computedFrame,
  39050. name: frameList[i].name,
  39051. frameOpts: frameOpts,
  39052. transitionOpts: transitionOpts,
  39053. };
  39054. if(i === frameList.length - 1) {
  39055. // The last frame in this .animate call stores the promise resolve
  39056. // and reject callbacks. This is how we ensure that the animation
  39057. // loop (which may exist as a result of a *different* .animate call)
  39058. // still resolves or rejecdts this .animate call's promise. once it's
  39059. // complete.
  39060. nextFrame.onComplete = callbackOnNthTime(resolve, 2);
  39061. nextFrame.onInterrupt = reject;
  39062. }
  39063. trans._frameQueue.push(nextFrame);
  39064. }
  39065. // Set it as never having transitioned to a frame. This will cause the animation
  39066. // loop to immediately transition to the next frame (which, for immediate mode,
  39067. // is the first frame in the list since all others would have been discarded
  39068. // below)
  39069. if(animationOpts.mode === 'immediate') {
  39070. trans._lastFrameAt = -Infinity;
  39071. }
  39072. // Only it's not already running, start a RAF loop. This could be avoided in the
  39073. // case that there's only one frame, but it significantly complicated the logic
  39074. // and only sped things up by about 5% or so for a lorenz attractor simulation.
  39075. // It would be a fine thing to implement, but the benefit of that optimization
  39076. // doesn't seem worth the extra complexity.
  39077. if(!trans._animationRaf) {
  39078. beginAnimationLoop();
  39079. }
  39080. }
  39081. function stopAnimationLoop() {
  39082. gd.emit('plotly_animated');
  39083. // Be sure to unset also since it's how we know whether a loop is already running:
  39084. window.cancelAnimationFrame(trans._animationRaf);
  39085. trans._animationRaf = null;
  39086. }
  39087. function nextFrame() {
  39088. if(trans._currentFrame && trans._currentFrame.onComplete) {
  39089. // Execute the callback and unset it to ensure it doesn't
  39090. // accidentally get called twice
  39091. trans._currentFrame.onComplete();
  39092. }
  39093. var newFrame = trans._currentFrame = trans._frameQueue.shift();
  39094. if(newFrame) {
  39095. // Since it's sometimes necessary to do deep digging into frame data,
  39096. // we'll consider it not 100% impossible for nulls or numbers to sneak through,
  39097. // so check when casting the name, just to be absolutely certain:
  39098. var stringName = newFrame.name ? newFrame.name.toString() : null;
  39099. gd._fullLayout._currentFrame = stringName;
  39100. trans._lastFrameAt = Date.now();
  39101. trans._timeToNext = newFrame.frameOpts.duration;
  39102. // This is simply called and it's left to .transition to decide how to manage
  39103. // interrupting current transitions. That means we don't need to worry about
  39104. // how it resolves or what happens after this:
  39105. Plots.transition(gd,
  39106. newFrame.frame.data,
  39107. newFrame.frame.layout,
  39108. helpers.coerceTraceIndices(gd, newFrame.frame.traces),
  39109. newFrame.frameOpts,
  39110. newFrame.transitionOpts
  39111. ).then(function() {
  39112. if(newFrame.onComplete) {
  39113. newFrame.onComplete();
  39114. }
  39115. });
  39116. gd.emit('plotly_animatingframe', {
  39117. name: stringName,
  39118. frame: newFrame.frame,
  39119. animation: {
  39120. frame: newFrame.frameOpts,
  39121. transition: newFrame.transitionOpts,
  39122. }
  39123. });
  39124. } else {
  39125. // If there are no more frames, then stop the RAF loop:
  39126. stopAnimationLoop();
  39127. }
  39128. }
  39129. function beginAnimationLoop() {
  39130. gd.emit('plotly_animating');
  39131. // If no timer is running, then set last frame = long ago so that the next
  39132. // frame is immediately transitioned:
  39133. trans._lastFrameAt = -Infinity;
  39134. trans._timeToNext = 0;
  39135. trans._runningTransitions = 0;
  39136. trans._currentFrame = null;
  39137. var doFrame = function() {
  39138. // This *must* be requested before nextFrame since nextFrame may decide
  39139. // to cancel it if there's nothing more to animated:
  39140. trans._animationRaf = window.requestAnimationFrame(doFrame);
  39141. // Check if we're ready for a new frame:
  39142. if(Date.now() - trans._lastFrameAt > trans._timeToNext) {
  39143. nextFrame();
  39144. }
  39145. };
  39146. doFrame();
  39147. }
  39148. // This is an animate-local counter that helps match up option input list
  39149. // items with the particular frame.
  39150. var configCounter = 0;
  39151. function setTransitionConfig(frame) {
  39152. if(Array.isArray(transitionOpts)) {
  39153. if(configCounter >= transitionOpts.length) {
  39154. frame.transitionOpts = transitionOpts[configCounter];
  39155. } else {
  39156. frame.transitionOpts = transitionOpts[0];
  39157. }
  39158. } else {
  39159. frame.transitionOpts = transitionOpts;
  39160. }
  39161. configCounter++;
  39162. return frame;
  39163. }
  39164. // Disambiguate what's sort of frames have been received
  39165. var i, frame;
  39166. var frameList = [];
  39167. var allFrames = frameOrGroupNameOrFrameList === undefined || frameOrGroupNameOrFrameList === null;
  39168. var isFrameArray = Array.isArray(frameOrGroupNameOrFrameList);
  39169. var isSingleFrame = !allFrames && !isFrameArray && Lib.isPlainObject(frameOrGroupNameOrFrameList);
  39170. if(isSingleFrame) {
  39171. // In this case, a simple object has been passed to animate.
  39172. frameList.push({
  39173. type: 'object',
  39174. data: setTransitionConfig(Lib.extendFlat({}, frameOrGroupNameOrFrameList))
  39175. });
  39176. } else if(allFrames || ['string', 'number'].indexOf(typeof frameOrGroupNameOrFrameList) !== -1) {
  39177. // In this case, null or undefined has been passed so that we want to
  39178. // animate *all* currently defined frames
  39179. for(i = 0; i < trans._frames.length; i++) {
  39180. frame = trans._frames[i];
  39181. if(!frame) continue;
  39182. if(allFrames || String(frame.group) === String(frameOrGroupNameOrFrameList)) {
  39183. frameList.push({
  39184. type: 'byname',
  39185. name: String(frame.name),
  39186. data: setTransitionConfig({name: frame.name})
  39187. });
  39188. }
  39189. }
  39190. } else if(isFrameArray) {
  39191. for(i = 0; i < frameOrGroupNameOrFrameList.length; i++) {
  39192. var frameOrName = frameOrGroupNameOrFrameList[i];
  39193. if(['number', 'string'].indexOf(typeof frameOrName) !== -1) {
  39194. frameOrName = String(frameOrName);
  39195. // In this case, there's an array and this frame is a string name:
  39196. frameList.push({
  39197. type: 'byname',
  39198. name: frameOrName,
  39199. data: setTransitionConfig({name: frameOrName})
  39200. });
  39201. } else if(Lib.isPlainObject(frameOrName)) {
  39202. frameList.push({
  39203. type: 'object',
  39204. data: setTransitionConfig(Lib.extendFlat({}, frameOrName))
  39205. });
  39206. }
  39207. }
  39208. }
  39209. // Verify that all of these frames actually exist; return and reject if not:
  39210. for(i = 0; i < frameList.length; i++) {
  39211. frame = frameList[i];
  39212. if(frame.type === 'byname' && !trans._frameHash[frame.data.name]) {
  39213. Lib.warn('animate failure: frame not found: "' + frame.data.name + '"');
  39214. reject();
  39215. return;
  39216. }
  39217. }
  39218. // If the mode is either next or immediate, then all currently queued frames must
  39219. // be dumped and the corresponding .animate promises rejected.
  39220. if(['next', 'immediate'].indexOf(animationOpts.mode) !== -1) {
  39221. discardExistingFrames();
  39222. }
  39223. if(animationOpts.direction === 'reverse') {
  39224. frameList.reverse();
  39225. }
  39226. var currentFrame = gd._fullLayout._currentFrame;
  39227. if(currentFrame && animationOpts.fromcurrent) {
  39228. var idx = -1;
  39229. for(i = 0; i < frameList.length; i++) {
  39230. frame = frameList[i];
  39231. if(frame.type === 'byname' && frame.name === currentFrame) {
  39232. idx = i;
  39233. break;
  39234. }
  39235. }
  39236. if(idx > 0 && idx < frameList.length - 1) {
  39237. var filteredFrameList = [];
  39238. for(i = 0; i < frameList.length; i++) {
  39239. frame = frameList[i];
  39240. if(frameList[i].type !== 'byname' || i > idx) {
  39241. filteredFrameList.push(frame);
  39242. }
  39243. }
  39244. frameList = filteredFrameList;
  39245. }
  39246. }
  39247. if(frameList.length > 0) {
  39248. queueFrames(frameList);
  39249. } else {
  39250. // This is the case where there were simply no frames. It's a little strange
  39251. // since there's not much to do:
  39252. gd.emit('plotly_animated');
  39253. resolve();
  39254. }
  39255. });
  39256. };
  39257. /**
  39258. * Register new frames
  39259. *
  39260. * @param {string id or DOM element} gd
  39261. * the id or DOM element of the graph container div
  39262. *
  39263. * @param {array of objects} frameList
  39264. * list of frame definitions, in which each object includes any of:
  39265. * - name: {string} name of frame to add
  39266. * - data: {array of objects} trace data
  39267. * - layout {object} layout definition
  39268. * - traces {array} trace indices
  39269. * - baseframe {string} name of frame from which this frame gets defaults
  39270. *
  39271. * @param {array of integers} indices
  39272. * an array of integer indices matching the respective frames in `frameList`. If not
  39273. * provided, an index will be provided in serial order. If already used, the frame
  39274. * will be overwritten.
  39275. */
  39276. exports.addFrames = function(gd, frameList, indices) {
  39277. gd = Lib.getGraphDiv(gd);
  39278. if(frameList === null || frameList === undefined) {
  39279. return Promise.resolve();
  39280. }
  39281. if(!Lib.isPlotDiv(gd)) {
  39282. throw new Error(
  39283. 'This element is not a Plotly plot: ' + gd + '. It\'s likely that you\'ve failed ' +
  39284. 'to create a plot before adding frames. For more details, see ' +
  39285. 'https://plot.ly/javascript/animations/'
  39286. );
  39287. }
  39288. var i, frame, j, idx;
  39289. var _frames = gd._transitionData._frames;
  39290. var _frameHash = gd._transitionData._frameHash;
  39291. if(!Array.isArray(frameList)) {
  39292. throw new Error('addFrames failure: frameList must be an Array of frame definitions' + frameList);
  39293. }
  39294. // Create a sorted list of insertions since we run into lots of problems if these
  39295. // aren't in ascending order of index:
  39296. //
  39297. // Strictly for sorting. Make sure this is guaranteed to never collide with any
  39298. // already-exisisting indices:
  39299. var bigIndex = _frames.length + frameList.length * 2;
  39300. var insertions = [];
  39301. var _frameHashLocal = {};
  39302. for(i = frameList.length - 1; i >= 0; i--) {
  39303. if(!Lib.isPlainObject(frameList[i])) continue;
  39304. // The entire logic for checking for this type of name collision can be removed once we migrate to ES6 and
  39305. // use a Map instead of an Object instance, as Map keys aren't converted to strings.
  39306. var lookupName = frameList[i].name;
  39307. var name = (_frameHash[lookupName] || _frameHashLocal[lookupName] || {}).name;
  39308. var newName = frameList[i].name;
  39309. var collisionPresent = _frameHash[name] || _frameHashLocal[name];
  39310. if(name && newName && typeof newName === 'number' && collisionPresent && numericNameWarningCount < numericNameWarningCountLimit) {
  39311. numericNameWarningCount++;
  39312. Lib.warn('addFrames: overwriting frame "' + (_frameHash[name] || _frameHashLocal[name]).name +
  39313. '" with a frame whose name of type "number" also equates to "' +
  39314. name + '". This is valid but may potentially lead to unexpected ' +
  39315. 'behavior since all plotly.js frame names are stored internally ' +
  39316. 'as strings.');
  39317. if(numericNameWarningCount === numericNameWarningCountLimit) {
  39318. Lib.warn('addFrames: This API call has yielded too many of these warnings. ' +
  39319. 'For the rest of this call, further warnings about numeric frame ' +
  39320. 'names will be suppressed.');
  39321. }
  39322. }
  39323. _frameHashLocal[lookupName] = {name: lookupName};
  39324. insertions.push({
  39325. frame: Plots.supplyFrameDefaults(frameList[i]),
  39326. index: (indices && indices[i] !== undefined && indices[i] !== null) ? indices[i] : bigIndex + i
  39327. });
  39328. }
  39329. // Sort this, taking note that undefined insertions end up at the end:
  39330. insertions.sort(function(a, b) {
  39331. if(a.index > b.index) return -1;
  39332. if(a.index < b.index) return 1;
  39333. return 0;
  39334. });
  39335. var ops = [];
  39336. var revops = [];
  39337. var frameCount = _frames.length;
  39338. for(i = insertions.length - 1; i >= 0; i--) {
  39339. frame = insertions[i].frame;
  39340. if(typeof frame.name === 'number') {
  39341. Lib.warn('Warning: addFrames accepts frames with numeric names, but the numbers are' +
  39342. 'implicitly cast to strings');
  39343. }
  39344. if(!frame.name) {
  39345. // Repeatedly assign a default name, incrementing the counter each time until
  39346. // we get a name that's not in the hashed lookup table:
  39347. while(_frameHash[(frame.name = 'frame ' + gd._transitionData._counter++)]);
  39348. }
  39349. if(_frameHash[frame.name]) {
  39350. // If frame is present, overwrite its definition:
  39351. for(j = 0; j < _frames.length; j++) {
  39352. if((_frames[j] || {}).name === frame.name) break;
  39353. }
  39354. ops.push({type: 'replace', index: j, value: frame});
  39355. revops.unshift({type: 'replace', index: j, value: _frames[j]});
  39356. } else {
  39357. // Otherwise insert it at the end of the list:
  39358. idx = Math.max(0, Math.min(insertions[i].index, frameCount));
  39359. ops.push({type: 'insert', index: idx, value: frame});
  39360. revops.unshift({type: 'delete', index: idx});
  39361. frameCount++;
  39362. }
  39363. }
  39364. var undoFunc = Plots.modifyFrames;
  39365. var redoFunc = Plots.modifyFrames;
  39366. var undoArgs = [gd, revops];
  39367. var redoArgs = [gd, ops];
  39368. if(Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
  39369. return Plots.modifyFrames(gd, ops);
  39370. };
  39371. /**
  39372. * Delete frame
  39373. *
  39374. * @param {string id or DOM element} gd
  39375. * the id or DOM element of the graph container div
  39376. *
  39377. * @param {array of integers} frameList
  39378. * list of integer indices of frames to be deleted
  39379. */
  39380. exports.deleteFrames = function(gd, frameList) {
  39381. gd = Lib.getGraphDiv(gd);
  39382. if(!Lib.isPlotDiv(gd)) {
  39383. throw new Error('This element is not a Plotly plot: ' + gd);
  39384. }
  39385. var i, idx;
  39386. var _frames = gd._transitionData._frames;
  39387. var ops = [];
  39388. var revops = [];
  39389. if(!frameList) {
  39390. frameList = [];
  39391. for(i = 0; i < _frames.length; i++) {
  39392. frameList.push(i);
  39393. }
  39394. }
  39395. frameList = frameList.slice(0);
  39396. frameList.sort();
  39397. for(i = frameList.length - 1; i >= 0; i--) {
  39398. idx = frameList[i];
  39399. ops.push({type: 'delete', index: idx});
  39400. revops.unshift({type: 'insert', index: idx, value: _frames[idx]});
  39401. }
  39402. var undoFunc = Plots.modifyFrames;
  39403. var redoFunc = Plots.modifyFrames;
  39404. var undoArgs = [gd, revops];
  39405. var redoArgs = [gd, ops];
  39406. if(Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs);
  39407. return Plots.modifyFrames(gd, ops);
  39408. };
  39409. /**
  39410. * Purge a graph container div back to its initial pre-Plotly.plot state
  39411. *
  39412. * @param {string id or DOM element} gd
  39413. * the id or DOM element of the graph container div
  39414. */
  39415. exports.purge = function purge(gd) {
  39416. gd = Lib.getGraphDiv(gd);
  39417. var fullLayout = gd._fullLayout || {};
  39418. var fullData = gd._fullData || [];
  39419. // remove gl contexts
  39420. Plots.cleanPlot([], {}, fullData, fullLayout);
  39421. // purge properties
  39422. Plots.purge(gd);
  39423. // purge event emitter methods
  39424. Events.purge(gd);
  39425. // remove plot container
  39426. if(fullLayout._container) fullLayout._container.remove();
  39427. // in contrast to Plotly.Plots.purge which does NOT clear _context!
  39428. delete gd._context;
  39429. return gd;
  39430. };
  39431. // -------------------------------------------------------
  39432. // makePlotFramework: Create the plot container and axes
  39433. // -------------------------------------------------------
  39434. function makePlotFramework(gd) {
  39435. var gd3 = d3.select(gd);
  39436. var fullLayout = gd._fullLayout;
  39437. // Plot container
  39438. fullLayout._container = gd3.selectAll('.plot-container').data([0]);
  39439. fullLayout._container.enter().insert('div', ':first-child')
  39440. .classed('plot-container', true)
  39441. .classed('plotly', true);
  39442. // Make the svg container
  39443. fullLayout._paperdiv = fullLayout._container.selectAll('.svg-container').data([0]);
  39444. fullLayout._paperdiv.enter().append('div')
  39445. .classed('svg-container', true)
  39446. .style('position', 'relative');
  39447. // Make the graph containers
  39448. // start fresh each time we get here, so we know the order comes out
  39449. // right, rather than enter/exit which can muck up the order
  39450. // TODO: sort out all the ordering so we don't have to
  39451. // explicitly delete anything
  39452. // FIXME: parcoords reuses this object, not the best pattern
  39453. fullLayout._glcontainer = fullLayout._paperdiv.selectAll('.gl-container')
  39454. .data([{}]);
  39455. fullLayout._glcontainer.enter().append('div')
  39456. .classed('gl-container', true);
  39457. fullLayout._paperdiv.selectAll('.main-svg').remove();
  39458. fullLayout._paper = fullLayout._paperdiv.insert('svg', ':first-child')
  39459. .classed('main-svg', true);
  39460. fullLayout._toppaper = fullLayout._paperdiv.append('svg')
  39461. .classed('main-svg', true);
  39462. if(!fullLayout._uid) {
  39463. var otherUids = {};
  39464. d3.selectAll('defs').each(function() {
  39465. if(this.id) otherUids[this.id.split('-')[1]] = 1;
  39466. });
  39467. fullLayout._uid = Lib.randstr(otherUids);
  39468. }
  39469. fullLayout._paperdiv.selectAll('.main-svg')
  39470. .attr(xmlnsNamespaces.svgAttrs);
  39471. fullLayout._defs = fullLayout._paper.append('defs')
  39472. .attr('id', 'defs-' + fullLayout._uid);
  39473. fullLayout._clips = fullLayout._defs.append('g')
  39474. .classed('clips', true);
  39475. fullLayout._topdefs = fullLayout._toppaper.append('defs')
  39476. .attr('id', 'topdefs-' + fullLayout._uid);
  39477. fullLayout._topclips = fullLayout._topdefs.append('g')
  39478. .classed('clips', true);
  39479. fullLayout._bgLayer = fullLayout._paper.append('g')
  39480. .classed('bglayer', true);
  39481. fullLayout._draggers = fullLayout._paper.append('g')
  39482. .classed('draglayer', true);
  39483. // lower shape/image layer - note that this is behind
  39484. // all subplots data/grids but above the backgrounds
  39485. // except inset subplots, whose backgrounds are drawn
  39486. // inside their own group so that they appear above
  39487. // the data for the main subplot
  39488. // lower shapes and images which are fully referenced to
  39489. // a subplot still get drawn within the subplot's group
  39490. // so they will work correctly on insets
  39491. var layerBelow = fullLayout._paper.append('g')
  39492. .classed('layer-below', true);
  39493. fullLayout._imageLowerLayer = layerBelow.append('g')
  39494. .classed('imagelayer', true);
  39495. fullLayout._shapeLowerLayer = layerBelow.append('g')
  39496. .classed('shapelayer', true);
  39497. // single cartesian layer for the whole plot
  39498. fullLayout._cartesianlayer = fullLayout._paper.append('g').classed('cartesianlayer', true);
  39499. // single polar layer for the whole plot
  39500. fullLayout._polarlayer = fullLayout._paper.append('g').classed('polarlayer', true);
  39501. // single ternary layer for the whole plot
  39502. fullLayout._ternarylayer = fullLayout._paper.append('g').classed('ternarylayer', true);
  39503. // single geo layer for the whole plot
  39504. fullLayout._geolayer = fullLayout._paper.append('g').classed('geolayer', true);
  39505. // single pie layer for the whole plot
  39506. fullLayout._pielayer = fullLayout._paper.append('g').classed('pielayer', true);
  39507. // fill in image server scrape-svg
  39508. fullLayout._glimages = fullLayout._paper.append('g').classed('glimages', true);
  39509. // lastly upper shapes, info (legend, annotations) and hover layers go on top
  39510. // these are in a different svg element normally, but get collapsed into a single
  39511. // svg when exporting (after inserting 3D)
  39512. // upper shapes/images are only those drawn above the whole plot, including subplots
  39513. var layerAbove = fullLayout._toppaper.append('g')
  39514. .classed('layer-above', true);
  39515. fullLayout._imageUpperLayer = layerAbove.append('g')
  39516. .classed('imagelayer', true);
  39517. fullLayout._shapeUpperLayer = layerAbove.append('g')
  39518. .classed('shapelayer', true);
  39519. fullLayout._infolayer = fullLayout._toppaper.append('g').classed('infolayer', true);
  39520. fullLayout._menulayer = fullLayout._toppaper.append('g').classed('menulayer', true);
  39521. fullLayout._zoomlayer = fullLayout._toppaper.append('g').classed('zoomlayer', true);
  39522. fullLayout._hoverlayer = fullLayout._toppaper.append('g').classed('hoverlayer', true);
  39523. gd.emit('plotly_framework');
  39524. }
  39525. },{"../components/color":51,"../components/colorbar/connect":53,"../components/drawing":72,"../constants/xmlns_namespaces":150,"../lib":168,"../lib/events":161,"../lib/queue":182,"../lib/svg_text_utils":189,"../plots/cartesian/axes":212,"../plots/cartesian/constants":218,"../plots/cartesian/graph_interact":222,"../plots/plots":245,"../plots/polar/legacy":248,"../registry":257,"./edit_types":195,"./helpers":196,"./manage_arrays":198,"./plot_config":200,"./plot_schema":201,"./subroutines":203,"d3":16,"fast-isnumeric":18,"has-hover":20}],200:[function(_dereq_,module,exports){
  39526. /**
  39527. * Copyright 2012-2019, Plotly, Inc.
  39528. * All rights reserved.
  39529. *
  39530. * This source code is licensed under the MIT license found in the
  39531. * LICENSE file in the root directory of this source tree.
  39532. */
  39533. 'use strict';
  39534. /**
  39535. * This will be transferred over to gd and overridden by
  39536. * config args to Plotly.plot.
  39537. *
  39538. * The defaults are the appropriate settings for plotly.js,
  39539. * so we get the right experience without any config argument.
  39540. *
  39541. * N.B. the config options are not coerced using Lib.coerce so keys
  39542. * like `valType` and `values` are only set for documentation purposes
  39543. * at the moment.
  39544. */
  39545. var configAttributes = {
  39546. staticPlot: {
  39547. valType: 'boolean',
  39548. dflt: false,
  39549. },
  39550. plotlyServerURL: {
  39551. valType: 'string',
  39552. dflt: 'https://plot.ly',
  39553. },
  39554. editable: {
  39555. valType: 'boolean',
  39556. dflt: false,
  39557. },
  39558. edits: {
  39559. annotationPosition: {
  39560. valType: 'boolean',
  39561. dflt: false,
  39562. },
  39563. annotationTail: {
  39564. valType: 'boolean',
  39565. dflt: false,
  39566. },
  39567. annotationText: {
  39568. valType: 'boolean',
  39569. dflt: false,
  39570. },
  39571. axisTitleText: {
  39572. valType: 'boolean',
  39573. dflt: false,
  39574. },
  39575. colorbarPosition: {
  39576. valType: 'boolean',
  39577. dflt: false,
  39578. },
  39579. colorbarTitleText: {
  39580. valType: 'boolean',
  39581. dflt: false,
  39582. },
  39583. legendPosition: {
  39584. valType: 'boolean',
  39585. dflt: false,
  39586. },
  39587. legendText: {
  39588. valType: 'boolean',
  39589. dflt: false,
  39590. },
  39591. shapePosition: {
  39592. valType: 'boolean',
  39593. dflt: false,
  39594. },
  39595. titleText: {
  39596. valType: 'boolean',
  39597. dflt: false,
  39598. }
  39599. },
  39600. autosizable: {
  39601. valType: 'boolean',
  39602. dflt: false,
  39603. },
  39604. responsive: {
  39605. valType: 'boolean',
  39606. dflt: false,
  39607. },
  39608. fillFrame: {
  39609. valType: 'boolean',
  39610. dflt: false,
  39611. },
  39612. frameMargins: {
  39613. valType: 'number',
  39614. dflt: 0,
  39615. min: 0,
  39616. max: 0.5,
  39617. },
  39618. scrollZoom: {
  39619. valType: 'flaglist',
  39620. flags: ['cartesian', 'gl3d', 'geo', 'mapbox'],
  39621. extras: [true, false],
  39622. dflt: 'gl3d+geo+mapbox',
  39623. },
  39624. doubleClick: {
  39625. valType: 'enumerated',
  39626. values: [false, 'reset', 'autosize', 'reset+autosize'],
  39627. dflt: 'reset+autosize',
  39628. },
  39629. showAxisDragHandles: {
  39630. valType: 'boolean',
  39631. dflt: true,
  39632. },
  39633. showAxisRangeEntryBoxes: {
  39634. valType: 'boolean',
  39635. dflt: true,
  39636. },
  39637. showTips: {
  39638. valType: 'boolean',
  39639. dflt: true,
  39640. },
  39641. showLink: {
  39642. valType: 'boolean',
  39643. dflt: false,
  39644. },
  39645. linkText: {
  39646. valType: 'string',
  39647. dflt: 'Edit chart',
  39648. noBlank: true,
  39649. },
  39650. sendData: {
  39651. valType: 'boolean',
  39652. dflt: true,
  39653. },
  39654. showSources: {
  39655. valType: 'any',
  39656. dflt: false,
  39657. },
  39658. displayModeBar: {
  39659. valType: 'enumerated',
  39660. values: ['hover', true, false],
  39661. dflt: 'hover',
  39662. },
  39663. showSendToCloud: {
  39664. valType: 'boolean',
  39665. dflt: false,
  39666. },
  39667. modeBarButtonsToRemove: {
  39668. valType: 'any',
  39669. dflt: [],
  39670. },
  39671. modeBarButtonsToAdd: {
  39672. valType: 'any',
  39673. dflt: [],
  39674. },
  39675. modeBarButtons: {
  39676. valType: 'any',
  39677. dflt: false,
  39678. },
  39679. toImageButtonOptions: {
  39680. valType: 'any',
  39681. dflt: {},
  39682. },
  39683. displaylogo: {
  39684. valType: 'boolean',
  39685. dflt: true,
  39686. },
  39687. watermark: {
  39688. valType: 'boolean',
  39689. dflt: false,
  39690. },
  39691. plotGlPixelRatio: {
  39692. valType: 'number',
  39693. dflt: 2,
  39694. min: 1,
  39695. max: 4,
  39696. },
  39697. setBackground: {
  39698. valType: 'any',
  39699. dflt: 'transparent',
  39700. },
  39701. topojsonURL: {
  39702. valType: 'string',
  39703. noBlank: true,
  39704. dflt: 'https://cdn.plot.ly/',
  39705. },
  39706. mapboxAccessToken: {
  39707. valType: 'string',
  39708. dflt: null,
  39709. },
  39710. logging: {
  39711. valType: 'boolean',
  39712. dflt: 1,
  39713. },
  39714. queueLength: {
  39715. valType: 'integer',
  39716. min: 0,
  39717. dflt: 0,
  39718. },
  39719. globalTransforms: {
  39720. valType: 'any',
  39721. dflt: [],
  39722. },
  39723. locale: {
  39724. valType: 'string',
  39725. dflt: 'en-US',
  39726. },
  39727. locales: {
  39728. valType: 'any',
  39729. dflt: {},
  39730. }
  39731. };
  39732. var dfltConfig = {};
  39733. function crawl(src, target) {
  39734. for(var k in src) {
  39735. var obj = src[k];
  39736. if(obj.valType) {
  39737. target[k] = obj.dflt;
  39738. } else {
  39739. if(!target[k]) {
  39740. target[k] = {};
  39741. }
  39742. crawl(obj, target[k]);
  39743. }
  39744. }
  39745. }
  39746. crawl(configAttributes, dfltConfig);
  39747. module.exports = {
  39748. configAttributes: configAttributes,
  39749. dfltConfig: dfltConfig
  39750. };
  39751. },{}],201:[function(_dereq_,module,exports){
  39752. /**
  39753. * Copyright 2012-2019, Plotly, Inc.
  39754. * All rights reserved.
  39755. *
  39756. * This source code is licensed under the MIT license found in the
  39757. * LICENSE file in the root directory of this source tree.
  39758. */
  39759. 'use strict';
  39760. var Registry = _dereq_('../registry');
  39761. var Lib = _dereq_('../lib');
  39762. var baseAttributes = _dereq_('../plots/attributes');
  39763. var baseLayoutAttributes = _dereq_('../plots/layout_attributes');
  39764. var frameAttributes = _dereq_('../plots/frame_attributes');
  39765. var animationAttributes = _dereq_('../plots/animation_attributes');
  39766. var configAttributes = _dereq_('./plot_config').configAttributes;
  39767. // polar attributes are not part of the Registry yet
  39768. var polarAreaAttrs = _dereq_('../plots/polar/legacy/area_attributes');
  39769. var polarAxisAttrs = _dereq_('../plots/polar/legacy/axis_attributes');
  39770. var editTypes = _dereq_('./edit_types');
  39771. var extendFlat = Lib.extendFlat;
  39772. var extendDeepAll = Lib.extendDeepAll;
  39773. var isPlainObject = Lib.isPlainObject;
  39774. var IS_SUBPLOT_OBJ = '_isSubplotObj';
  39775. var IS_LINKED_TO_ARRAY = '_isLinkedToArray';
  39776. var ARRAY_ATTR_REGEXPS = '_arrayAttrRegexps';
  39777. var DEPRECATED = '_deprecated';
  39778. var UNDERSCORE_ATTRS = [IS_SUBPLOT_OBJ, IS_LINKED_TO_ARRAY, ARRAY_ATTR_REGEXPS, DEPRECATED];
  39779. exports.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ;
  39780. exports.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY;
  39781. exports.DEPRECATED = DEPRECATED;
  39782. exports.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS;
  39783. /** Outputs the full plotly.js plot schema
  39784. *
  39785. * @return {object}
  39786. * - defs
  39787. * - traces
  39788. * - layout
  39789. * - transforms
  39790. * - frames
  39791. * - animations
  39792. * - config
  39793. */
  39794. exports.get = function() {
  39795. var traces = {};
  39796. Registry.allTypes.concat('area').forEach(function(type) {
  39797. traces[type] = getTraceAttributes(type);
  39798. });
  39799. var transforms = {};
  39800. Object.keys(Registry.transformsRegistry).forEach(function(type) {
  39801. transforms[type] = getTransformAttributes(type);
  39802. });
  39803. return {
  39804. defs: {
  39805. valObjects: Lib.valObjectMeta,
  39806. metaKeys: UNDERSCORE_ATTRS.concat(['description', 'role', 'editType', 'impliedEdits']),
  39807. editType: {
  39808. traces: editTypes.traces,
  39809. layout: editTypes.layout
  39810. },
  39811. impliedEdits: {
  39812. }
  39813. },
  39814. traces: traces,
  39815. layout: getLayoutAttributes(),
  39816. transforms: transforms,
  39817. frames: getFramesAttributes(),
  39818. animation: formatAttributes(animationAttributes),
  39819. config: formatAttributes(configAttributes)
  39820. };
  39821. };
  39822. /**
  39823. * Crawl the attribute tree, recursively calling a callback function
  39824. *
  39825. * @param {object} attrs
  39826. * The node of the attribute tree (e.g. the root) from which recursion originates
  39827. * @param {Function} callback
  39828. * A callback function with the signature:
  39829. * @callback callback
  39830. * @param {object} attr an attribute
  39831. * @param {String} attrName name string
  39832. * @param {object[]} attrs all the attributes
  39833. * @param {Number} level the recursion level, 0 at the root
  39834. * @param {String} fullAttrString full attribute name (ie 'marker.line')
  39835. * @param {Number} [specifiedLevel]
  39836. * The level in the tree, in order to let the callback function detect descend or backtrack,
  39837. * typically unsupplied (implied 0), just used by the self-recursive call.
  39838. * The necessity arises because the tree traversal is not controlled by callback return values.
  39839. * The decision to not use callback return values for controlling tree pruning arose from
  39840. * the goal of keeping the crawler backwards compatible. Observe that one of the pruning conditions
  39841. * precedes the callback call.
  39842. * @param {string} [attrString]
  39843. * the path to the current attribute, as an attribute string (ie 'marker.line')
  39844. * typically unsupplied, but you may supply it if you want to disambiguate which attrs tree you
  39845. * are starting from
  39846. *
  39847. * @return {object} transformOut
  39848. * copy of transformIn that contains attribute defaults
  39849. */
  39850. exports.crawl = function(attrs, callback, specifiedLevel, attrString) {
  39851. var level = specifiedLevel || 0;
  39852. attrString = attrString || '';
  39853. Object.keys(attrs).forEach(function(attrName) {
  39854. var attr = attrs[attrName];
  39855. if(UNDERSCORE_ATTRS.indexOf(attrName) !== -1) return;
  39856. var fullAttrString = (attrString ? attrString + '.' : '') + attrName;
  39857. callback(attr, attrName, attrs, level, fullAttrString);
  39858. if(exports.isValObject(attr)) return;
  39859. if(isPlainObject(attr) && attrName !== 'impliedEdits') {
  39860. exports.crawl(attr, callback, level + 1, fullAttrString);
  39861. }
  39862. });
  39863. };
  39864. /** Is object a value object (or a container object)?
  39865. *
  39866. * @param {object} obj
  39867. * @return {boolean}
  39868. * returns true for a valid value object and
  39869. * false for tree nodes in the attribute hierarchy
  39870. */
  39871. exports.isValObject = function(obj) {
  39872. return obj && obj.valType !== undefined;
  39873. };
  39874. /**
  39875. * Find all data array attributes in a given trace object - including
  39876. * `arrayOk` attributes.
  39877. *
  39878. * @param {object} trace
  39879. * full trace object that contains a reference to `_module.attributes`
  39880. *
  39881. * @return {array} arrayAttributes
  39882. * list of array attributes for the given trace
  39883. */
  39884. exports.findArrayAttributes = function(trace) {
  39885. var arrayAttributes = [];
  39886. var stack = [];
  39887. var isArrayStack = [];
  39888. var baseContainer, baseAttrName;
  39889. function callback(attr, attrName, attrs, level) {
  39890. stack = stack.slice(0, level).concat([attrName]);
  39891. isArrayStack = isArrayStack.slice(0, level).concat([attr && attr._isLinkedToArray]);
  39892. var splittableAttr = (
  39893. attr &&
  39894. (attr.valType === 'data_array' || attr.arrayOk === true) &&
  39895. !(stack[level - 1] === 'colorbar' && (attrName === 'ticktext' || attrName === 'tickvals'))
  39896. );
  39897. // Manually exclude 'colorbar.tickvals' and 'colorbar.ticktext' for now
  39898. // which are declared as `valType: 'data_array'` but scale independently of
  39899. // the coordinate arrays.
  39900. //
  39901. // Down the road, we might want to add a schema field (e.g `uncorrelatedArray: true`)
  39902. // to distinguish attributes of the likes.
  39903. if(!splittableAttr) return;
  39904. crawlIntoTrace(baseContainer, 0, '');
  39905. }
  39906. function crawlIntoTrace(container, i, astrPartial) {
  39907. var item = container[stack[i]];
  39908. var newAstrPartial = astrPartial + stack[i];
  39909. if(i === stack.length - 1) {
  39910. if(Lib.isArrayOrTypedArray(item)) {
  39911. arrayAttributes.push(baseAttrName + newAstrPartial);
  39912. }
  39913. }
  39914. else {
  39915. if(isArrayStack[i]) {
  39916. if(Array.isArray(item)) {
  39917. for(var j = 0; j < item.length; j++) {
  39918. if(Lib.isPlainObject(item[j])) {
  39919. crawlIntoTrace(item[j], i + 1, newAstrPartial + '[' + j + '].');
  39920. }
  39921. }
  39922. }
  39923. }
  39924. else if(Lib.isPlainObject(item)) {
  39925. crawlIntoTrace(item, i + 1, newAstrPartial + '.');
  39926. }
  39927. }
  39928. }
  39929. baseContainer = trace;
  39930. baseAttrName = '';
  39931. exports.crawl(baseAttributes, callback);
  39932. if(trace._module && trace._module.attributes) {
  39933. exports.crawl(trace._module.attributes, callback);
  39934. }
  39935. var transforms = trace.transforms;
  39936. if(transforms) {
  39937. for(var i = 0; i < transforms.length; i++) {
  39938. var transform = transforms[i];
  39939. var module = transform._module;
  39940. if(module) {
  39941. baseAttrName = 'transforms[' + i + '].';
  39942. baseContainer = transform;
  39943. exports.crawl(module.attributes, callback);
  39944. }
  39945. }
  39946. }
  39947. return arrayAttributes;
  39948. };
  39949. /*
  39950. * Find the valObject for one attribute in an existing trace
  39951. *
  39952. * @param {object} trace
  39953. * full trace object that contains a reference to `_module.attributes`
  39954. * @param {object} parts
  39955. * an array of parts, like ['transforms', 1, 'value']
  39956. * typically from nestedProperty(...).parts
  39957. *
  39958. * @return {object|false}
  39959. * the valObject for this attribute, or the last found parent
  39960. * in some cases the innermost valObject will not exist, for example
  39961. * `valType: 'any'` attributes where we might set a part of the attribute.
  39962. * In that case, stop at the deepest valObject we *do* find.
  39963. */
  39964. exports.getTraceValObject = function(trace, parts) {
  39965. var head = parts[0];
  39966. var i = 1; // index to start recursing from
  39967. var moduleAttrs, valObject;
  39968. if(head === 'transforms') {
  39969. if(parts.length === 1) {
  39970. return baseAttributes.transforms;
  39971. }
  39972. var transforms = trace.transforms;
  39973. if(!Array.isArray(transforms) || !transforms.length) return false;
  39974. var tNum = parts[1];
  39975. if(!isIndex(tNum) || tNum >= transforms.length) {
  39976. return false;
  39977. }
  39978. moduleAttrs = (Registry.transformsRegistry[transforms[tNum].type] || {}).attributes;
  39979. valObject = moduleAttrs && moduleAttrs[parts[2]];
  39980. i = 3; // start recursing only inside the transform
  39981. }
  39982. else if(trace.type === 'area') {
  39983. valObject = polarAreaAttrs[head];
  39984. }
  39985. else {
  39986. // first look in the module for this trace
  39987. // components have already merged their trace attributes in here
  39988. var _module = trace._module;
  39989. if(!_module) _module = (Registry.modules[trace.type || baseAttributes.type.dflt] || {})._module;
  39990. if(!_module) return false;
  39991. moduleAttrs = _module.attributes;
  39992. valObject = moduleAttrs && moduleAttrs[head];
  39993. // then look in the subplot attributes
  39994. if(!valObject) {
  39995. var subplotModule = _module.basePlotModule;
  39996. if(subplotModule && subplotModule.attributes) {
  39997. valObject = subplotModule.attributes[head];
  39998. }
  39999. }
  40000. // finally look in the global attributes
  40001. if(!valObject) valObject = baseAttributes[head];
  40002. }
  40003. return recurseIntoValObject(valObject, parts, i);
  40004. };
  40005. /*
  40006. * Find the valObject for one layout attribute
  40007. *
  40008. * @param {array} parts
  40009. * an array of parts, like ['annotations', 1, 'x']
  40010. * typically from nestedProperty(...).parts
  40011. *
  40012. * @return {object|false}
  40013. * the valObject for this attribute, or the last found parent
  40014. * in some cases the innermost valObject will not exist, for example
  40015. * `valType: 'any'` attributes where we might set a part of the attribute.
  40016. * In that case, stop at the deepest valObject we *do* find.
  40017. */
  40018. exports.getLayoutValObject = function(fullLayout, parts) {
  40019. var valObject = layoutHeadAttr(fullLayout, parts[0]);
  40020. return recurseIntoValObject(valObject, parts, 1);
  40021. };
  40022. function layoutHeadAttr(fullLayout, head) {
  40023. var i, key, _module, attributes;
  40024. // look for attributes of the subplot types used on the plot
  40025. var basePlotModules = fullLayout._basePlotModules;
  40026. if(basePlotModules) {
  40027. var out;
  40028. for(i = 0; i < basePlotModules.length; i++) {
  40029. _module = basePlotModules[i];
  40030. if(_module.attrRegex && _module.attrRegex.test(head)) {
  40031. // if a module defines overrides, these take precedence
  40032. // initially this is to allow gl2d different editTypes from svg cartesian
  40033. if(_module.layoutAttrOverrides) return _module.layoutAttrOverrides;
  40034. // otherwise take the first attributes we find
  40035. if(!out && _module.layoutAttributes) out = _module.layoutAttributes;
  40036. }
  40037. // a module can also override the behavior of base (and component) module layout attrs
  40038. // again see gl2d for initial use case
  40039. var baseOverrides = _module.baseLayoutAttrOverrides;
  40040. if(baseOverrides && head in baseOverrides) return baseOverrides[head];
  40041. }
  40042. if(out) return out;
  40043. }
  40044. // look for layout attributes contributed by traces on the plot
  40045. var modules = fullLayout._modules;
  40046. if(modules) {
  40047. for(i = 0; i < modules.length; i++) {
  40048. attributes = modules[i].layoutAttributes;
  40049. if(attributes && head in attributes) {
  40050. return attributes[head];
  40051. }
  40052. }
  40053. }
  40054. /*
  40055. * Next look in components.
  40056. * Components that define a schema have already merged this into
  40057. * base and subplot attribute defs, so ignore these.
  40058. * Others (older style) all put all their attributes
  40059. * inside a container matching the module `name`
  40060. * eg `attributes` (array) or `legend` (object)
  40061. */
  40062. for(key in Registry.componentsRegistry) {
  40063. _module = Registry.componentsRegistry[key];
  40064. if(!_module.schema && (head === _module.name)) {
  40065. return _module.layoutAttributes;
  40066. }
  40067. }
  40068. if(head in baseLayoutAttributes) return baseLayoutAttributes[head];
  40069. // Polar doesn't populate _modules or _basePlotModules
  40070. // just fall back on these when the others fail
  40071. if(head === 'radialaxis' || head === 'angularaxis') {
  40072. return polarAxisAttrs[head];
  40073. }
  40074. return polarAxisAttrs.layout[head] || false;
  40075. }
  40076. function recurseIntoValObject(valObject, parts, i) {
  40077. if(!valObject) return false;
  40078. if(valObject._isLinkedToArray) {
  40079. // skip array index, abort if we try to dive into an array without an index
  40080. if(isIndex(parts[i])) i++;
  40081. else if(i < parts.length) return false;
  40082. }
  40083. // now recurse as far as we can. Occasionally we have an attribute
  40084. // setting an internal part below what's in the schema; just return
  40085. // the innermost schema item we find.
  40086. for(; i < parts.length; i++) {
  40087. var newValObject = valObject[parts[i]];
  40088. if(isPlainObject(newValObject)) valObject = newValObject;
  40089. else break;
  40090. if(i === parts.length - 1) break;
  40091. if(valObject._isLinkedToArray) {
  40092. i++;
  40093. if(!isIndex(parts[i])) return false;
  40094. }
  40095. else if(valObject.valType === 'info_array') {
  40096. i++;
  40097. var index = parts[i];
  40098. if(!isIndex(index)) return false;
  40099. var items = valObject.items;
  40100. if(Array.isArray(items)) {
  40101. if(index >= items.length) return false;
  40102. if(valObject.dimensions === 2) {
  40103. i++;
  40104. if(parts.length === i) return valObject;
  40105. var index2 = parts[i];
  40106. if(!isIndex(index2)) return false;
  40107. valObject = items[index][index2];
  40108. }
  40109. else valObject = items[index];
  40110. }
  40111. else {
  40112. valObject = items;
  40113. }
  40114. }
  40115. }
  40116. return valObject;
  40117. }
  40118. // note: this is different from Lib.isIndex, this one doesn't accept numeric
  40119. // strings, only actual numbers.
  40120. function isIndex(val) {
  40121. return val === Math.round(val) && val >= 0;
  40122. }
  40123. function getTraceAttributes(type) {
  40124. var _module, basePlotModule;
  40125. if(type === 'area') {
  40126. _module = { attributes: polarAreaAttrs };
  40127. basePlotModule = {};
  40128. }
  40129. else {
  40130. _module = Registry.modules[type]._module,
  40131. basePlotModule = _module.basePlotModule;
  40132. }
  40133. var attributes = {};
  40134. // make 'type' the first attribute in the object
  40135. attributes.type = null;
  40136. var copyBaseAttributes = extendDeepAll({}, baseAttributes);
  40137. var copyModuleAttributes = extendDeepAll({}, _module.attributes);
  40138. // prune global-level trace attributes that are already defined in a trace
  40139. exports.crawl(copyModuleAttributes, function(attr, attrName, attrs, level, fullAttrString) {
  40140. Lib.nestedProperty(copyBaseAttributes, fullAttrString).set(undefined);
  40141. // Prune undefined attributes
  40142. if(attr === undefined) Lib.nestedProperty(copyModuleAttributes, fullAttrString).set(undefined);
  40143. });
  40144. // base attributes (same for all trace types)
  40145. extendDeepAll(attributes, copyBaseAttributes);
  40146. // module attributes
  40147. extendDeepAll(attributes, copyModuleAttributes);
  40148. // subplot attributes
  40149. if(basePlotModule.attributes) {
  40150. extendDeepAll(attributes, basePlotModule.attributes);
  40151. }
  40152. // 'type' gets overwritten by baseAttributes; reset it here
  40153. attributes.type = type;
  40154. var out = {
  40155. meta: _module.meta || {},
  40156. attributes: formatAttributes(attributes),
  40157. };
  40158. // trace-specific layout attributes
  40159. if(_module.layoutAttributes) {
  40160. var layoutAttributes = {};
  40161. extendDeepAll(layoutAttributes, _module.layoutAttributes);
  40162. out.layoutAttributes = formatAttributes(layoutAttributes);
  40163. }
  40164. return out;
  40165. }
  40166. function getLayoutAttributes() {
  40167. var layoutAttributes = {};
  40168. var key, _module;
  40169. // global layout attributes
  40170. extendDeepAll(layoutAttributes, baseLayoutAttributes);
  40171. // add base plot module layout attributes
  40172. for(key in Registry.subplotsRegistry) {
  40173. _module = Registry.subplotsRegistry[key];
  40174. if(!_module.layoutAttributes) continue;
  40175. if(Array.isArray(_module.attr)) {
  40176. for(var i = 0; i < _module.attr.length; i++) {
  40177. handleBasePlotModule(layoutAttributes, _module, _module.attr[i]);
  40178. }
  40179. } else {
  40180. var astr = _module.attr === 'subplot' ? _module.name : _module.attr;
  40181. handleBasePlotModule(layoutAttributes, _module, astr);
  40182. }
  40183. }
  40184. // polar layout attributes
  40185. layoutAttributes = assignPolarLayoutAttrs(layoutAttributes);
  40186. // add registered components layout attributes
  40187. for(key in Registry.componentsRegistry) {
  40188. _module = Registry.componentsRegistry[key];
  40189. var schema = _module.schema;
  40190. /*
  40191. * Components with defined schema have already been merged in at register time
  40192. * but a few components define attributes that apply only to xaxis
  40193. * not yaxis (rangeselector, rangeslider) - delete from y schema.
  40194. * Note that the input attributes for xaxis/yaxis are the same object
  40195. * so it's not possible to only add them to xaxis from the start.
  40196. * If we ever have such asymmetry the other way, or anywhere else,
  40197. * we will need to extend both this code and mergeComponentAttrsToSubplot
  40198. * (which will not find yaxis only for example)
  40199. */
  40200. if(schema && (schema.subplots || schema.layout)) {
  40201. var subplots = schema.subplots;
  40202. if(subplots && subplots.xaxis && !subplots.yaxis) {
  40203. for(var xkey in subplots.xaxis) delete layoutAttributes.yaxis[xkey];
  40204. }
  40205. }
  40206. // older style without schema need to be explicitly merged in now
  40207. else if(_module.layoutAttributes) {
  40208. insertAttrs(layoutAttributes, _module.layoutAttributes, _module.name);
  40209. }
  40210. }
  40211. return {
  40212. layoutAttributes: formatAttributes(layoutAttributes)
  40213. };
  40214. }
  40215. function getTransformAttributes(type) {
  40216. var _module = Registry.transformsRegistry[type];
  40217. var attributes = extendDeepAll({}, _module.attributes);
  40218. // add registered components transform attributes
  40219. Object.keys(Registry.componentsRegistry).forEach(function(k) {
  40220. var _module = Registry.componentsRegistry[k];
  40221. if(_module.schema && _module.schema.transforms && _module.schema.transforms[type]) {
  40222. Object.keys(_module.schema.transforms[type]).forEach(function(v) {
  40223. insertAttrs(attributes, _module.schema.transforms[type][v], v);
  40224. });
  40225. }
  40226. });
  40227. return {
  40228. attributes: formatAttributes(attributes)
  40229. };
  40230. }
  40231. function getFramesAttributes() {
  40232. var attrs = {
  40233. frames: Lib.extendDeepAll({}, frameAttributes)
  40234. };
  40235. formatAttributes(attrs);
  40236. return attrs.frames;
  40237. }
  40238. function formatAttributes(attrs) {
  40239. mergeValTypeAndRole(attrs);
  40240. formatArrayContainers(attrs);
  40241. stringify(attrs);
  40242. return attrs;
  40243. }
  40244. function mergeValTypeAndRole(attrs) {
  40245. function makeSrcAttr(attrName) {
  40246. return {
  40247. valType: 'string',
  40248. editType: 'none'
  40249. };
  40250. }
  40251. function callback(attr, attrName, attrs) {
  40252. if(exports.isValObject(attr)) {
  40253. if(attr.valType === 'data_array') {
  40254. // all 'data_array' attrs have role 'data'
  40255. attr.role = 'data';
  40256. // all 'data_array' attrs have a corresponding 'src' attr
  40257. attrs[attrName + 'src'] = makeSrcAttr(attrName);
  40258. }
  40259. else if(attr.arrayOk === true) {
  40260. // all 'arrayOk' attrs have a corresponding 'src' attr
  40261. attrs[attrName + 'src'] = makeSrcAttr(attrName);
  40262. }
  40263. }
  40264. else if(isPlainObject(attr)) {
  40265. // all attrs container objects get role 'object'
  40266. attr.role = 'object';
  40267. }
  40268. }
  40269. exports.crawl(attrs, callback);
  40270. }
  40271. function formatArrayContainers(attrs) {
  40272. function callback(attr, attrName, attrs) {
  40273. if(!attr) return;
  40274. var itemName = attr[IS_LINKED_TO_ARRAY];
  40275. if(!itemName) return;
  40276. delete attr[IS_LINKED_TO_ARRAY];
  40277. attrs[attrName] = { items: {} };
  40278. attrs[attrName].items[itemName] = attr;
  40279. attrs[attrName].role = 'object';
  40280. }
  40281. exports.crawl(attrs, callback);
  40282. }
  40283. // this can take around 10ms and should only be run from PlotSchema.get(),
  40284. // to ensure JSON.stringify(PlotSchema.get()) gives the intended result.
  40285. function stringify(attrs) {
  40286. function walk(attr) {
  40287. for(var k in attr) {
  40288. if(isPlainObject(attr[k])) {
  40289. walk(attr[k]);
  40290. } else if(Array.isArray(attr[k])) {
  40291. for(var i = 0; i < attr[k].length; i++) {
  40292. walk(attr[k][i]);
  40293. }
  40294. } else {
  40295. // as JSON.stringify(/test/) // => {}
  40296. if(attr[k] instanceof RegExp) {
  40297. attr[k] = attr[k].toString();
  40298. }
  40299. }
  40300. }
  40301. }
  40302. walk(attrs);
  40303. }
  40304. function assignPolarLayoutAttrs(layoutAttributes) {
  40305. extendFlat(layoutAttributes, {
  40306. radialaxis: polarAxisAttrs.radialaxis,
  40307. angularaxis: polarAxisAttrs.angularaxis
  40308. });
  40309. extendFlat(layoutAttributes, polarAxisAttrs.layout);
  40310. return layoutAttributes;
  40311. }
  40312. function handleBasePlotModule(layoutAttributes, _module, astr) {
  40313. var np = Lib.nestedProperty(layoutAttributes, astr);
  40314. var attrs = extendDeepAll({}, _module.layoutAttributes);
  40315. attrs[IS_SUBPLOT_OBJ] = true;
  40316. np.set(attrs);
  40317. }
  40318. function insertAttrs(baseAttrs, newAttrs, astr) {
  40319. var np = Lib.nestedProperty(baseAttrs, astr);
  40320. np.set(extendDeepAll(np.get() || {}, newAttrs));
  40321. }
  40322. },{"../lib":168,"../plots/animation_attributes":207,"../plots/attributes":209,"../plots/frame_attributes":240,"../plots/layout_attributes":243,"../plots/polar/legacy/area_attributes":246,"../plots/polar/legacy/axis_attributes":247,"../registry":257,"./edit_types":195,"./plot_config":200}],202:[function(_dereq_,module,exports){
  40323. /**
  40324. * Copyright 2012-2019, Plotly, Inc.
  40325. * All rights reserved.
  40326. *
  40327. * This source code is licensed under the MIT license found in the
  40328. * LICENSE file in the root directory of this source tree.
  40329. */
  40330. 'use strict';
  40331. var Lib = _dereq_('../lib');
  40332. var plotAttributes = _dereq_('../plots/attributes');
  40333. var TEMPLATEITEMNAME = 'templateitemname';
  40334. var templateAttrs = {
  40335. name: {
  40336. valType: 'string',
  40337. editType: 'none',
  40338. }
  40339. };
  40340. templateAttrs[TEMPLATEITEMNAME] = {
  40341. valType: 'string',
  40342. editType: 'calc',
  40343. };
  40344. /**
  40345. * templatedArray: decorate an attributes object with templating (and array)
  40346. * properties.
  40347. *
  40348. * @param {string} name: the singular form of the array name. Sets
  40349. * `_isLinkedToArray` to this, so the schema knows to treat this as an array.
  40350. * @param {object} attrs: the item attributes. Since all callers are expected
  40351. * to be constructing this object on the spot, we mutate it here for
  40352. * performance, rather than extending a new object with it.
  40353. *
  40354. * @returns {object}: the decorated `attrs` object
  40355. */
  40356. exports.templatedArray = function(name, attrs) {
  40357. attrs._isLinkedToArray = name;
  40358. attrs.name = templateAttrs.name;
  40359. attrs[TEMPLATEITEMNAME] = templateAttrs[TEMPLATEITEMNAME];
  40360. return attrs;
  40361. };
  40362. /**
  40363. * traceTemplater: logic for matching traces to trace templates
  40364. *
  40365. * @param {object} dataTemplate: collection of {traceType: [{template}, ...]}
  40366. * ie each type the template applies to contains a list of template objects,
  40367. * to be provided cyclically to data traces of that type.
  40368. *
  40369. * @returns {object}: {newTrace}, a function:
  40370. * newTrace(traceIn): that takes the input traceIn, coerces its type, then
  40371. * uses that type to find the next template to apply. returns the output
  40372. * traceOut with template attached, ready to continue supplyDefaults.
  40373. */
  40374. exports.traceTemplater = function(dataTemplate) {
  40375. var traceCounts = {};
  40376. var traceType, typeTemplates;
  40377. for(traceType in dataTemplate) {
  40378. typeTemplates = dataTemplate[traceType];
  40379. if(Array.isArray(typeTemplates) && typeTemplates.length) {
  40380. traceCounts[traceType] = 0;
  40381. }
  40382. }
  40383. function newTrace(traceIn) {
  40384. traceType = Lib.coerce(traceIn, {}, plotAttributes, 'type');
  40385. var traceOut = {type: traceType, _template: null};
  40386. if(traceType in traceCounts) {
  40387. typeTemplates = dataTemplate[traceType];
  40388. // cycle through traces in the template set for this type
  40389. var typei = traceCounts[traceType] % typeTemplates.length;
  40390. traceCounts[traceType]++;
  40391. traceOut._template = typeTemplates[typei];
  40392. }
  40393. else {
  40394. // TODO: anything we should do for types missing from the template?
  40395. // try to apply some other type? Or just bail as we do here?
  40396. // Actually I think yes, we should apply other types; would be nice
  40397. // if all scatter* could inherit from each other, and if histogram
  40398. // could inherit from bar, etc... but how to specify this? And do we
  40399. // compose them, or if a type is present require it to be complete?
  40400. // Actually this could apply to layout too - 3D annotations
  40401. // inheriting from 2D, axes of different types inheriting from each
  40402. // other...
  40403. }
  40404. return traceOut;
  40405. }
  40406. return {
  40407. newTrace: newTrace
  40408. // TODO: function to figure out what's left & what didn't work
  40409. };
  40410. };
  40411. /**
  40412. * newContainer: Create a new sub-container inside `container` and propagate any
  40413. * applicable template to it. If there's no template, still propagates
  40414. * `undefined` so relinkPrivate will not retain an old template!
  40415. *
  40416. * @param {object} container: the outer container, should already have _template
  40417. * if there *is* a template for this plot
  40418. * @param {string} name: the key of the new container to make
  40419. * @param {string} baseName: if applicable, a base attribute to take the
  40420. * template from, ie for xaxis3 the base would be xaxis
  40421. *
  40422. * @returns {object}: an object for inclusion _full*, empty except for the
  40423. * appropriate template piece
  40424. */
  40425. exports.newContainer = function(container, name, baseName) {
  40426. var template = container._template;
  40427. var part = template && (template[name] || (baseName && template[baseName]));
  40428. if(!Lib.isPlainObject(part)) part = null;
  40429. var out = container[name] = {_template: part};
  40430. return out;
  40431. };
  40432. /**
  40433. * arrayTemplater: special logic for templating both defaults and specific items
  40434. * in a container array (annotations etc)
  40435. *
  40436. * @param {object} container: the outer container, should already have _template
  40437. * if there *is* a template for this plot
  40438. * @param {string} name: the name of the array to template (ie 'annotations')
  40439. * will be used to find default ('annotationdefaults' object) and specific
  40440. * ('annotations' array) template specs.
  40441. * @param {string} inclusionAttr: the attribute determining this item's
  40442. * inclusion in the output, usually 'visible' or 'enabled'
  40443. *
  40444. * @returns {object}: {newItem, defaultItems}, both functions:
  40445. * newItem(itemIn): create an output item, bare except for the correct
  40446. * template and name(s), as the base for supplyDefaults
  40447. * defaultItems(): to be called after all newItem calls, return any
  40448. * specific template items that have not already beeen included,
  40449. * also as bare output items ready for supplyDefaults.
  40450. */
  40451. exports.arrayTemplater = function(container, name, inclusionAttr) {
  40452. var template = container._template;
  40453. var defaultsTemplate = template && template[arrayDefaultKey(name)];
  40454. var templateItems = template && template[name];
  40455. if(!Array.isArray(templateItems) || !templateItems.length) {
  40456. templateItems = [];
  40457. }
  40458. var usedNames = {};
  40459. function newItem(itemIn) {
  40460. // include name and templateitemname in the output object for ALL
  40461. // container array items. Note: you could potentially use different
  40462. // name and templateitemname, if you're using one template to make
  40463. // another template. templateitemname would be the name in the original
  40464. // template, and name is the new "subclassed" item name.
  40465. var out = {name: itemIn.name, _input: itemIn};
  40466. var templateItemName = out[TEMPLATEITEMNAME] = itemIn[TEMPLATEITEMNAME];
  40467. // no itemname: use the default template
  40468. if(!validItemName(templateItemName)) {
  40469. out._template = defaultsTemplate;
  40470. return out;
  40471. }
  40472. // look for an item matching this itemname
  40473. // note these do not inherit from the default template, only the item.
  40474. for(var i = 0; i < templateItems.length; i++) {
  40475. var templateItem = templateItems[i];
  40476. if(templateItem.name === templateItemName) {
  40477. // Note: it's OK to use a template item more than once
  40478. // but using it at least once will stop it from generating
  40479. // a default item at the end.
  40480. usedNames[templateItemName] = 1;
  40481. out._template = templateItem;
  40482. return out;
  40483. }
  40484. }
  40485. // Didn't find a matching template item, so since this item is intended
  40486. // to only be modifications it's most likely broken. Hide it unless
  40487. // it's explicitly marked visible - in which case it gets NO template,
  40488. // not even the default.
  40489. out[inclusionAttr] = itemIn[inclusionAttr] || false;
  40490. // special falsy value we can look for in validateTemplate
  40491. out._template = false;
  40492. return out;
  40493. }
  40494. function defaultItems() {
  40495. var out = [];
  40496. for(var i = 0; i < templateItems.length; i++) {
  40497. var templateItem = templateItems[i];
  40498. var name = templateItem.name;
  40499. // only allow named items to be added as defaults,
  40500. // and only allow each name once
  40501. if(validItemName(name) && !usedNames[name]) {
  40502. var outi = {
  40503. _template: templateItem,
  40504. name: name,
  40505. _input: {_templateitemname: name}
  40506. };
  40507. outi[TEMPLATEITEMNAME] = templateItem[TEMPLATEITEMNAME];
  40508. out.push(outi);
  40509. usedNames[name] = 1;
  40510. }
  40511. }
  40512. return out;
  40513. }
  40514. return {
  40515. newItem: newItem,
  40516. defaultItems: defaultItems
  40517. };
  40518. };
  40519. function validItemName(name) {
  40520. return name && typeof name === 'string';
  40521. }
  40522. function arrayDefaultKey(name) {
  40523. var lastChar = name.length - 1;
  40524. if(name.charAt(lastChar) !== 's') {
  40525. Lib.warn('bad argument to arrayDefaultKey: ' + name);
  40526. }
  40527. return name.substr(0, name.length - 1) + 'defaults';
  40528. }
  40529. exports.arrayDefaultKey = arrayDefaultKey;
  40530. /**
  40531. * arrayEditor: helper for editing array items that may have come from
  40532. * template defaults (in which case they will not exist in the input yet)
  40533. *
  40534. * @param {object} parentIn: the input container (eg gd.layout)
  40535. * @param {string} containerStr: the attribute string for the container inside
  40536. * `parentIn`.
  40537. * @param {object} itemOut: the _full* item (eg gd._fullLayout.annotations[0])
  40538. * that we'll be editing. Assumed to have been created by `arrayTemplater`.
  40539. *
  40540. * @returns {object}: {modifyBase, modifyItem, getUpdateObj, applyUpdate}, all functions:
  40541. * modifyBase(attr, value): Add an update that's *not* related to the item.
  40542. * `attr` is the full attribute string.
  40543. * modifyItem(attr, value): Add an update to the item. `attr` is just the
  40544. * portion of the attribute string inside the item.
  40545. * getUpdateObj(): Get the final constructed update object, to use in
  40546. * `restyle` or `relayout`. Also resets the update object in case this
  40547. * update was canceled.
  40548. * applyUpdate(attr, value): optionally add an update `attr: value`,
  40549. * then apply it to `parent` which should be the parent of `containerIn`,
  40550. * ie the object to which `containerStr` is the attribute string.
  40551. */
  40552. exports.arrayEditor = function(parentIn, containerStr, itemOut) {
  40553. var lengthIn = (Lib.nestedProperty(parentIn, containerStr).get() || []).length;
  40554. var index = itemOut._index;
  40555. // Check that we are indeed off the end of this container.
  40556. // Otherwise a devious user could put a key `_templateitemname` in their
  40557. // own input and break lots of things.
  40558. var templateItemName = (index >= lengthIn) && (itemOut._input || {})._templateitemname;
  40559. if(templateItemName) index = lengthIn;
  40560. var itemStr = containerStr + '[' + index + ']';
  40561. var update;
  40562. function resetUpdate() {
  40563. update = {};
  40564. if(templateItemName) {
  40565. update[itemStr] = {};
  40566. update[itemStr][TEMPLATEITEMNAME] = templateItemName;
  40567. }
  40568. }
  40569. resetUpdate();
  40570. function modifyBase(attr, value) {
  40571. update[attr] = value;
  40572. }
  40573. function modifyItem(attr, value) {
  40574. if(templateItemName) {
  40575. // we're making a new object: edit that object
  40576. Lib.nestedProperty(update[itemStr], attr).set(value);
  40577. }
  40578. else {
  40579. // we're editing an existing object: include *just* the edit
  40580. update[itemStr + '.' + attr] = value;
  40581. }
  40582. }
  40583. function getUpdateObj() {
  40584. var updateOut = update;
  40585. resetUpdate();
  40586. return updateOut;
  40587. }
  40588. function applyUpdate(attr, value) {
  40589. if(attr) modifyItem(attr, value);
  40590. var updateToApply = getUpdateObj();
  40591. for(var key in updateToApply) {
  40592. Lib.nestedProperty(parentIn, key).set(updateToApply[key]);
  40593. }
  40594. }
  40595. return {
  40596. modifyBase: modifyBase,
  40597. modifyItem: modifyItem,
  40598. getUpdateObj: getUpdateObj,
  40599. applyUpdate: applyUpdate
  40600. };
  40601. };
  40602. },{"../lib":168,"../plots/attributes":209}],203:[function(_dereq_,module,exports){
  40603. /**
  40604. * Copyright 2012-2019, Plotly, Inc.
  40605. * All rights reserved.
  40606. *
  40607. * This source code is licensed under the MIT license found in the
  40608. * LICENSE file in the root directory of this source tree.
  40609. */
  40610. 'use strict';
  40611. var d3 = _dereq_('d3');
  40612. var Registry = _dereq_('../registry');
  40613. var Plots = _dereq_('../plots/plots');
  40614. var Lib = _dereq_('../lib');
  40615. var clearGlCanvases = _dereq_('../lib/clear_gl_canvases');
  40616. var Color = _dereq_('../components/color');
  40617. var Drawing = _dereq_('../components/drawing');
  40618. var Titles = _dereq_('../components/titles');
  40619. var ModeBar = _dereq_('../components/modebar');
  40620. var Axes = _dereq_('../plots/cartesian/axes');
  40621. var alignmentConstants = _dereq_('../constants/alignment');
  40622. var axisConstraints = _dereq_('../plots/cartesian/constraints');
  40623. var enforceAxisConstraints = axisConstraints.enforce;
  40624. var cleanAxisConstraints = axisConstraints.clean;
  40625. var doAutoRange = _dereq_('../plots/cartesian/autorange').doAutoRange;
  40626. var SVG_TEXT_ANCHOR_START = 'start';
  40627. var SVG_TEXT_ANCHOR_MIDDLE = 'middle';
  40628. var SVG_TEXT_ANCHOR_END = 'end';
  40629. exports.layoutStyles = function(gd) {
  40630. return Lib.syncOrAsync([Plots.doAutoMargin, lsInner], gd);
  40631. };
  40632. function overlappingDomain(xDomain, yDomain, domains) {
  40633. for(var i = 0; i < domains.length; i++) {
  40634. var existingX = domains[i][0];
  40635. var existingY = domains[i][1];
  40636. if(existingX[0] >= xDomain[1] || existingX[1] <= xDomain[0]) {
  40637. continue;
  40638. }
  40639. if(existingY[0] < yDomain[1] && existingY[1] > yDomain[0]) {
  40640. return true;
  40641. }
  40642. }
  40643. return false;
  40644. }
  40645. function lsInner(gd) {
  40646. var fullLayout = gd._fullLayout;
  40647. var gs = fullLayout._size;
  40648. var pad = gs.p;
  40649. var axList = Axes.list(gd, '', true);
  40650. var i, subplot, plotinfo, ax, xa, ya;
  40651. fullLayout._paperdiv.style({
  40652. width: (gd._context.responsive && fullLayout.autosize && !gd._context._hasZeroWidth && !gd.layout.width) ? '100%' : fullLayout.width + 'px',
  40653. height: (gd._context.responsive && fullLayout.autosize && !gd._context._hasZeroHeight && !gd.layout.height) ? '100%' : fullLayout.height + 'px'
  40654. })
  40655. .selectAll('.main-svg')
  40656. .call(Drawing.setSize, fullLayout.width, fullLayout.height);
  40657. gd._context.setBackground(gd, fullLayout.paper_bgcolor);
  40658. exports.drawMainTitle(gd);
  40659. ModeBar.manage(gd);
  40660. // _has('cartesian') means SVG specifically, not GL2D - but GL2D
  40661. // can still get here because it makes some of the SVG structure
  40662. // for shared features like selections.
  40663. if(!fullLayout._has('cartesian')) {
  40664. return gd._promises.length && Promise.all(gd._promises);
  40665. }
  40666. function getLinePosition(ax, counterAx, side) {
  40667. var lwHalf = ax._lw / 2;
  40668. if(ax._id.charAt(0) === 'x') {
  40669. if(!counterAx) return gs.t + gs.h * (1 - (ax.position || 0)) + (lwHalf % 1);
  40670. else if(side === 'top') return counterAx._offset - pad - lwHalf;
  40671. return counterAx._offset + counterAx._length + pad + lwHalf;
  40672. }
  40673. if(!counterAx) return gs.l + gs.w * (ax.position || 0) + (lwHalf % 1);
  40674. else if(side === 'right') return counterAx._offset + counterAx._length + pad + lwHalf;
  40675. return counterAx._offset - pad - lwHalf;
  40676. }
  40677. // some preparation of axis position info
  40678. for(i = 0; i < axList.length; i++) {
  40679. ax = axList[i];
  40680. var counterAx = ax._anchorAxis;
  40681. // clear axis line positions, to be set in the subplot loop below
  40682. ax._linepositions = {};
  40683. // stash crispRounded linewidth so we don't need to pass gd all over the place
  40684. ax._lw = Drawing.crispRound(gd, ax.linewidth, 1);
  40685. // figure out the main axis line and main mirror line position.
  40686. // it's easier to follow the logic if we handle these separately from
  40687. // ax._linepositions, which are only used by mirror=allticks
  40688. // for non-main-subplot ticks, and mirror=all(ticks)? for zero line
  40689. // hiding logic
  40690. ax._mainLinePosition = getLinePosition(ax, counterAx, ax.side);
  40691. ax._mainMirrorPosition = (ax.mirror && counterAx) ?
  40692. getLinePosition(ax, counterAx,
  40693. alignmentConstants.OPPOSITE_SIDE[ax.side]) : null;
  40694. }
  40695. // figure out which backgrounds we need to draw,
  40696. // and in which layers to put them
  40697. var lowerBackgroundIDs = [];
  40698. var backgroundIds = [];
  40699. var lowerDomains = [];
  40700. // no need to draw background when paper and plot color are the same color,
  40701. // activate mode just for large splom (which benefit the most from this
  40702. // optimization), but this could apply to all cartesian subplots.
  40703. var noNeedForBg = (
  40704. Color.opacity(fullLayout.paper_bgcolor) === 1 &&
  40705. Color.opacity(fullLayout.plot_bgcolor) === 1 &&
  40706. fullLayout.paper_bgcolor === fullLayout.plot_bgcolor
  40707. );
  40708. for(subplot in fullLayout._plots) {
  40709. plotinfo = fullLayout._plots[subplot];
  40710. if(plotinfo.mainplot) {
  40711. // mainplot is a reference to the main plot this one is overlaid on
  40712. // so if it exists, this is an overlaid plot and we don't need to
  40713. // give it its own background
  40714. if(plotinfo.bg) {
  40715. plotinfo.bg.remove();
  40716. }
  40717. plotinfo.bg = undefined;
  40718. } else {
  40719. var xDomain = plotinfo.xaxis.domain;
  40720. var yDomain = plotinfo.yaxis.domain;
  40721. var plotgroup = plotinfo.plotgroup;
  40722. if(overlappingDomain(xDomain, yDomain, lowerDomains)) {
  40723. var pgNode = plotgroup.node();
  40724. var plotgroupBg = plotinfo.bg = Lib.ensureSingle(plotgroup, 'rect', 'bg');
  40725. pgNode.insertBefore(plotgroupBg.node(), pgNode.childNodes[0]);
  40726. backgroundIds.push(subplot);
  40727. } else {
  40728. plotgroup.select('rect.bg').remove();
  40729. lowerDomains.push([xDomain, yDomain]);
  40730. if(!noNeedForBg) {
  40731. lowerBackgroundIDs.push(subplot);
  40732. backgroundIds.push(subplot);
  40733. }
  40734. }
  40735. }
  40736. }
  40737. // now create all the lower-layer backgrounds at once now that
  40738. // we have the list of subplots that need them
  40739. var lowerBackgrounds = fullLayout._bgLayer.selectAll('.bg')
  40740. .data(lowerBackgroundIDs);
  40741. lowerBackgrounds.enter().append('rect')
  40742. .classed('bg', true);
  40743. lowerBackgrounds.exit().remove();
  40744. lowerBackgrounds.each(function(subplot) {
  40745. fullLayout._plots[subplot].bg = d3.select(this);
  40746. });
  40747. // style all backgrounds
  40748. for(i = 0; i < backgroundIds.length; i++) {
  40749. plotinfo = fullLayout._plots[backgroundIds[i]];
  40750. xa = plotinfo.xaxis;
  40751. ya = plotinfo.yaxis;
  40752. if(plotinfo.bg) {
  40753. plotinfo.bg
  40754. .call(Drawing.setRect,
  40755. xa._offset - pad, ya._offset - pad,
  40756. xa._length + 2 * pad, ya._length + 2 * pad)
  40757. .call(Color.fill, fullLayout.plot_bgcolor)
  40758. .style('stroke-width', 0);
  40759. }
  40760. }
  40761. if(!fullLayout._hasOnlyLargeSploms) {
  40762. for(subplot in fullLayout._plots) {
  40763. plotinfo = fullLayout._plots[subplot];
  40764. xa = plotinfo.xaxis;
  40765. ya = plotinfo.yaxis;
  40766. // Clip so that data only shows up on the plot area.
  40767. var clipId = plotinfo.clipId = 'clip' + fullLayout._uid + subplot + 'plot';
  40768. var plotClip = Lib.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) {
  40769. s.classed('plotclip', true)
  40770. .append('rect');
  40771. });
  40772. plotinfo.clipRect = plotClip.select('rect').attr({
  40773. width: xa._length,
  40774. height: ya._length
  40775. });
  40776. Drawing.setTranslate(plotinfo.plot, xa._offset, ya._offset);
  40777. var plotClipId;
  40778. var layerClipId;
  40779. if(plotinfo._hasClipOnAxisFalse) {
  40780. plotClipId = null;
  40781. layerClipId = clipId;
  40782. } else {
  40783. plotClipId = clipId;
  40784. layerClipId = null;
  40785. }
  40786. Drawing.setClipUrl(plotinfo.plot, plotClipId, gd);
  40787. // stash layer clipId value (null or same as clipId)
  40788. // to DRY up Drawing.setClipUrl calls on trace-module and trace layers
  40789. // downstream
  40790. plotinfo.layerClipId = layerClipId;
  40791. }
  40792. }
  40793. var xLinesXLeft, xLinesXRight, xLinesYBottom, xLinesYTop,
  40794. leftYLineWidth, rightYLineWidth;
  40795. var yLinesYBottom, yLinesYTop, yLinesXLeft, yLinesXRight,
  40796. connectYBottom, connectYTop;
  40797. var extraSubplot;
  40798. function xLinePath(y) {
  40799. return 'M' + xLinesXLeft + ',' + y + 'H' + xLinesXRight;
  40800. }
  40801. function xLinePathFree(y) {
  40802. return 'M' + xa._offset + ',' + y + 'h' + xa._length;
  40803. }
  40804. function yLinePath(x) {
  40805. return 'M' + x + ',' + yLinesYTop + 'V' + yLinesYBottom;
  40806. }
  40807. function yLinePathFree(x) {
  40808. return 'M' + x + ',' + ya._offset + 'v' + ya._length;
  40809. }
  40810. function mainPath(ax, pathFn, pathFnFree) {
  40811. if(!ax.showline || subplot !== ax._mainSubplot) return '';
  40812. if(!ax._anchorAxis) return pathFnFree(ax._mainLinePosition);
  40813. var out = pathFn(ax._mainLinePosition);
  40814. if(ax.mirror) out += pathFn(ax._mainMirrorPosition);
  40815. return out;
  40816. }
  40817. for(subplot in fullLayout._plots) {
  40818. plotinfo = fullLayout._plots[subplot];
  40819. xa = plotinfo.xaxis;
  40820. ya = plotinfo.yaxis;
  40821. /*
  40822. * x lines get longer where they meet y lines, to make a crisp corner.
  40823. * The x lines get the padding (margin.pad) plus the y line width to
  40824. * fill up the corner nicely. Free x lines are excluded - they always
  40825. * span exactly the data area of the plot
  40826. *
  40827. * | XXXXX
  40828. * | XXXXX
  40829. * |
  40830. * +------
  40831. * x1
  40832. * -----
  40833. * x2
  40834. */
  40835. var xPath = 'M0,0';
  40836. if(shouldShowLinesOrTicks(xa, subplot)) {
  40837. leftYLineWidth = findCounterAxisLineWidth(xa, 'left', ya, axList);
  40838. xLinesXLeft = xa._offset - (leftYLineWidth ? (pad + leftYLineWidth) : 0);
  40839. rightYLineWidth = findCounterAxisLineWidth(xa, 'right', ya, axList);
  40840. xLinesXRight = xa._offset + xa._length + (rightYLineWidth ? (pad + rightYLineWidth) : 0);
  40841. xLinesYBottom = getLinePosition(xa, ya, 'bottom');
  40842. xLinesYTop = getLinePosition(xa, ya, 'top');
  40843. // save axis line positions for extra ticks to reference
  40844. // each subplot that gets ticks from "allticks" gets an entry:
  40845. // [left or bottom, right or top]
  40846. extraSubplot = (!xa._anchorAxis || subplot !== xa._mainSubplot);
  40847. if(extraSubplot && (xa.mirror === 'allticks' || xa.mirror === 'all')) {
  40848. xa._linepositions[subplot] = [xLinesYBottom, xLinesYTop];
  40849. }
  40850. xPath = mainPath(xa, xLinePath, xLinePathFree);
  40851. if(extraSubplot && xa.showline && (xa.mirror === 'all' || xa.mirror === 'allticks')) {
  40852. xPath += xLinePath(xLinesYBottom) + xLinePath(xLinesYTop);
  40853. }
  40854. plotinfo.xlines
  40855. .style('stroke-width', xa._lw + 'px')
  40856. .call(Color.stroke, xa.showline ?
  40857. xa.linecolor : 'rgba(0,0,0,0)');
  40858. }
  40859. plotinfo.xlines.attr('d', xPath);
  40860. /*
  40861. * y lines that meet x axes get longer only by margin.pad, because
  40862. * the x axes fill in the corner space. Free y axes, like free x axes,
  40863. * always span exactly the data area of the plot
  40864. *
  40865. * | | XXXX
  40866. * y2| y1| XXXX
  40867. * | | XXXX
  40868. * |
  40869. * +-----
  40870. */
  40871. var yPath = 'M0,0';
  40872. if(shouldShowLinesOrTicks(ya, subplot)) {
  40873. connectYBottom = findCounterAxisLineWidth(ya, 'bottom', xa, axList);
  40874. yLinesYBottom = ya._offset + ya._length + (connectYBottom ? pad : 0);
  40875. connectYTop = findCounterAxisLineWidth(ya, 'top', xa, axList);
  40876. yLinesYTop = ya._offset - (connectYTop ? pad : 0);
  40877. yLinesXLeft = getLinePosition(ya, xa, 'left');
  40878. yLinesXRight = getLinePosition(ya, xa, 'right');
  40879. extraSubplot = (!ya._anchorAxis || subplot !== ya._mainSubplot);
  40880. if(extraSubplot && (ya.mirror === 'allticks' || ya.mirror === 'all')) {
  40881. ya._linepositions[subplot] = [yLinesXLeft, yLinesXRight];
  40882. }
  40883. yPath = mainPath(ya, yLinePath, yLinePathFree);
  40884. if(extraSubplot && ya.showline && (ya.mirror === 'all' || ya.mirror === 'allticks')) {
  40885. yPath += yLinePath(yLinesXLeft) + yLinePath(yLinesXRight);
  40886. }
  40887. plotinfo.ylines
  40888. .style('stroke-width', ya._lw + 'px')
  40889. .call(Color.stroke, ya.showline ?
  40890. ya.linecolor : 'rgba(0,0,0,0)');
  40891. }
  40892. plotinfo.ylines.attr('d', yPath);
  40893. }
  40894. Axes.makeClipPaths(gd);
  40895. return gd._promises.length && Promise.all(gd._promises);
  40896. }
  40897. function shouldShowLinesOrTicks(ax, subplot) {
  40898. return (ax.ticks || ax.showline) &&
  40899. (subplot === ax._mainSubplot || ax.mirror === 'all' || ax.mirror === 'allticks');
  40900. }
  40901. /*
  40902. * should we draw a line on counterAx at this side of ax?
  40903. * It's assumed that counterAx is known to overlay the subplot we're working on
  40904. * but it may not be its main axis.
  40905. */
  40906. function shouldShowLineThisSide(ax, side, counterAx) {
  40907. // does counterAx get a line at all?
  40908. if(!counterAx.showline || !counterAx._lw) return false;
  40909. // are we drawing *all* lines for counterAx?
  40910. if(counterAx.mirror === 'all' || counterAx.mirror === 'allticks') return true;
  40911. var anchorAx = counterAx._anchorAxis;
  40912. // is this a free axis? free axes can only have a subplot side-line with all(ticks)? mirroring
  40913. if(!anchorAx) return false;
  40914. // in order to handle cases where the user forgot to anchor this axis correctly
  40915. // (because its default anchor has the same domain on the relevant end)
  40916. // check whether the relevant position is the same.
  40917. var sideIndex = alignmentConstants.FROM_BL[side];
  40918. if(counterAx.side === side) {
  40919. return anchorAx.domain[sideIndex] === ax.domain[sideIndex];
  40920. }
  40921. return counterAx.mirror && anchorAx.domain[1 - sideIndex] === ax.domain[1 - sideIndex];
  40922. }
  40923. /*
  40924. * Is there another axis intersecting `side` end of `ax`?
  40925. * First look at `counterAx` (the axis for this subplot),
  40926. * then at all other potential counteraxes on or overlaying this subplot.
  40927. * Take the line width from the first one that has a line.
  40928. */
  40929. function findCounterAxisLineWidth(ax, side, counterAx, axList) {
  40930. if(shouldShowLineThisSide(ax, side, counterAx)) {
  40931. return counterAx._lw;
  40932. }
  40933. for(var i = 0; i < axList.length; i++) {
  40934. var axi = axList[i];
  40935. if(axi._mainAxis === counterAx._mainAxis && shouldShowLineThisSide(ax, side, axi)) {
  40936. return axi._lw;
  40937. }
  40938. }
  40939. return 0;
  40940. }
  40941. exports.drawMainTitle = function(gd) {
  40942. var fullLayout = gd._fullLayout;
  40943. var textAnchor = getMainTitleTextAnchor(fullLayout);
  40944. var dy = getMainTitleDy(fullLayout);
  40945. Titles.draw(gd, 'gtitle', {
  40946. propContainer: fullLayout,
  40947. propName: 'title.text',
  40948. placeholder: fullLayout._dfltTitle.plot,
  40949. attributes: {
  40950. x: getMainTitleX(fullLayout, textAnchor),
  40951. y: getMainTitleY(fullLayout, dy),
  40952. 'text-anchor': textAnchor,
  40953. dy: dy
  40954. }
  40955. });
  40956. };
  40957. function getMainTitleX(fullLayout, textAnchor) {
  40958. var title = fullLayout.title;
  40959. var gs = fullLayout._size;
  40960. var hPadShift = 0;
  40961. if(textAnchor === SVG_TEXT_ANCHOR_START) {
  40962. hPadShift = title.pad.l;
  40963. } else if(textAnchor === SVG_TEXT_ANCHOR_END) {
  40964. hPadShift = -title.pad.r;
  40965. }
  40966. switch(title.xref) {
  40967. case 'paper':
  40968. return gs.l + gs.w * title.x + hPadShift;
  40969. case 'container':
  40970. default:
  40971. return fullLayout.width * title.x + hPadShift;
  40972. }
  40973. }
  40974. function getMainTitleY(fullLayout, dy) {
  40975. var title = fullLayout.title;
  40976. var gs = fullLayout._size;
  40977. var vPadShift = 0;
  40978. if(dy === '0em' || !dy) {
  40979. vPadShift = -title.pad.b;
  40980. } else if(dy === alignmentConstants.CAP_SHIFT + 'em') {
  40981. vPadShift = title.pad.t;
  40982. }
  40983. if(title.y === 'auto') {
  40984. return gs.t / 2;
  40985. } else {
  40986. switch(title.yref) {
  40987. case 'paper':
  40988. return gs.t + gs.h - gs.h * title.y + vPadShift;
  40989. case 'container':
  40990. default:
  40991. return fullLayout.height - fullLayout.height * title.y + vPadShift;
  40992. }
  40993. }
  40994. }
  40995. function getMainTitleTextAnchor(fullLayout) {
  40996. var title = fullLayout.title;
  40997. var textAnchor = SVG_TEXT_ANCHOR_MIDDLE;
  40998. if(Lib.isRightAnchor(title)) {
  40999. textAnchor = SVG_TEXT_ANCHOR_END;
  41000. } else if(Lib.isLeftAnchor(title)) {
  41001. textAnchor = SVG_TEXT_ANCHOR_START;
  41002. }
  41003. return textAnchor;
  41004. }
  41005. function getMainTitleDy(fullLayout) {
  41006. var title = fullLayout.title;
  41007. var dy = '0em';
  41008. if(Lib.isTopAnchor(title)) {
  41009. dy = alignmentConstants.CAP_SHIFT + 'em';
  41010. } else if(Lib.isMiddleAnchor(title)) {
  41011. dy = alignmentConstants.MID_SHIFT + 'em';
  41012. }
  41013. return dy;
  41014. }
  41015. exports.doTraceStyle = function(gd) {
  41016. var calcdata = gd.calcdata;
  41017. var editStyleCalls = [];
  41018. var i;
  41019. for(i = 0; i < calcdata.length; i++) {
  41020. var cd = calcdata[i];
  41021. var cd0 = cd[0] || {};
  41022. var trace = cd0.trace || {};
  41023. var _module = trace._module || {};
  41024. // See if we need to do arraysToCalcdata
  41025. // call it regardless of what change we made, in case
  41026. // supplyDefaults brought in an array that was already
  41027. // in gd.data but not in gd._fullData previously
  41028. var arraysToCalcdata = _module.arraysToCalcdata;
  41029. if(arraysToCalcdata) arraysToCalcdata(cd, trace);
  41030. var editStyle = _module.editStyle;
  41031. if(editStyle) editStyleCalls.push({fn: editStyle, cd0: cd0});
  41032. }
  41033. if(editStyleCalls.length) {
  41034. for(i = 0; i < editStyleCalls.length; i++) {
  41035. var edit = editStyleCalls[i];
  41036. edit.fn(gd, edit.cd0);
  41037. }
  41038. clearGlCanvases(gd);
  41039. exports.redrawReglTraces(gd);
  41040. }
  41041. Plots.style(gd);
  41042. Registry.getComponentMethod('legend', 'draw')(gd);
  41043. return Plots.previousPromises(gd);
  41044. };
  41045. exports.doColorBars = function(gd) {
  41046. for(var i = 0; i < gd.calcdata.length; i++) {
  41047. var cdi0 = gd.calcdata[i][0];
  41048. if((cdi0.t || {}).cb) {
  41049. var trace = cdi0.trace;
  41050. var cb = cdi0.t.cb;
  41051. if(Registry.traceIs(trace, 'contour')) {
  41052. cb.line({
  41053. width: trace.contours.showlines !== false ?
  41054. trace.line.width : 0,
  41055. dash: trace.line.dash,
  41056. color: trace.contours.coloring === 'line' ?
  41057. cb._opts.line.color : trace.line.color
  41058. });
  41059. }
  41060. var moduleOpts = trace._module.colorbar;
  41061. var containerName = moduleOpts.container;
  41062. var opts = (containerName ? trace[containerName] : trace).colorbar;
  41063. cb.options(opts)();
  41064. }
  41065. }
  41066. return Plots.previousPromises(gd);
  41067. };
  41068. // force plot() to redo the layout and replot with the modified layout
  41069. exports.layoutReplot = function(gd) {
  41070. var layout = gd.layout;
  41071. gd.layout = undefined;
  41072. return Registry.call('plot', gd, '', layout);
  41073. };
  41074. exports.doLegend = function(gd) {
  41075. Registry.getComponentMethod('legend', 'draw')(gd);
  41076. return Plots.previousPromises(gd);
  41077. };
  41078. exports.doTicksRelayout = function(gd) {
  41079. Axes.draw(gd, 'redraw');
  41080. if(gd._fullLayout._hasOnlyLargeSploms) {
  41081. Registry.subplotsRegistry.splom.updateGrid(gd);
  41082. clearGlCanvases(gd);
  41083. exports.redrawReglTraces(gd);
  41084. }
  41085. exports.drawMainTitle(gd);
  41086. return Plots.previousPromises(gd);
  41087. };
  41088. exports.doModeBar = function(gd) {
  41089. var fullLayout = gd._fullLayout;
  41090. ModeBar.manage(gd);
  41091. for(var i = 0; i < fullLayout._basePlotModules.length; i++) {
  41092. var updateFx = fullLayout._basePlotModules[i].updateFx;
  41093. if(updateFx) updateFx(gd);
  41094. }
  41095. return Plots.previousPromises(gd);
  41096. };
  41097. exports.doCamera = function(gd) {
  41098. var fullLayout = gd._fullLayout;
  41099. var sceneIds = fullLayout._subplots.gl3d;
  41100. for(var i = 0; i < sceneIds.length; i++) {
  41101. var sceneLayout = fullLayout[sceneIds[i]];
  41102. var scene = sceneLayout._scene;
  41103. scene.setCamera(sceneLayout.camera);
  41104. }
  41105. };
  41106. exports.drawData = function(gd) {
  41107. var fullLayout = gd._fullLayout;
  41108. var calcdata = gd.calcdata;
  41109. var i;
  41110. // remove old colorbars explicitly
  41111. for(i = 0; i < calcdata.length; i++) {
  41112. var trace = calcdata[i][0].trace;
  41113. if(trace.visible !== true || !trace._module.colorbar) {
  41114. fullLayout._infolayer.select('.cb' + trace.uid).remove();
  41115. }
  41116. }
  41117. clearGlCanvases(gd);
  41118. // loop over the base plot modules present on graph
  41119. var basePlotModules = fullLayout._basePlotModules;
  41120. for(i = 0; i < basePlotModules.length; i++) {
  41121. basePlotModules[i].plot(gd);
  41122. }
  41123. exports.redrawReglTraces(gd);
  41124. // styling separate from drawing
  41125. Plots.style(gd);
  41126. // show annotations and shapes
  41127. Registry.getComponentMethod('shapes', 'draw')(gd);
  41128. Registry.getComponentMethod('annotations', 'draw')(gd);
  41129. // Mark the first render as complete
  41130. fullLayout._replotting = false;
  41131. return Plots.previousPromises(gd);
  41132. };
  41133. // Draw (or redraw) all regl-based traces in one go,
  41134. // useful during drag and selection where buffers of targeted traces are updated,
  41135. // but all traces need to be redrawn following clearGlCanvases.
  41136. //
  41137. // Note that _module.plot for regl trace does NOT draw things
  41138. // on the canvas, they only update the buffers.
  41139. // Drawing is perform here.
  41140. //
  41141. // TODO try adding per-subplot option using gl.SCISSOR_TEST for
  41142. // non-overlaying, disjoint subplots.
  41143. //
  41144. // TODO try to include parcoords in here.
  41145. // https://github.com/plotly/plotly.js/issues/3069
  41146. exports.redrawReglTraces = function(gd) {
  41147. var fullLayout = gd._fullLayout;
  41148. if(fullLayout._has('regl')) {
  41149. var fullData = gd._fullData;
  41150. var cartesianIds = [];
  41151. var polarIds = [];
  41152. var i, sp;
  41153. if(fullLayout._hasOnlyLargeSploms) {
  41154. fullLayout._splomGrid.draw();
  41155. }
  41156. // N.B.
  41157. // - Loop over fullData (not _splomScenes) to preserve splom trace-to-trace ordering
  41158. // - Fill list if subplot ids (instead of fullLayout._subplots) to handle cases where all traces
  41159. // of a given module are `visible !== true`
  41160. for(i = 0; i < fullData.length; i++) {
  41161. var trace = fullData[i];
  41162. if(trace.visible === true) {
  41163. if(trace.type === 'splom') {
  41164. fullLayout._splomScenes[trace.uid].draw();
  41165. } else if(trace.type === 'scattergl') {
  41166. Lib.pushUnique(cartesianIds, trace.xaxis + trace.yaxis);
  41167. } else if(trace.type === 'scatterpolargl') {
  41168. Lib.pushUnique(polarIds, trace.subplot);
  41169. }
  41170. }
  41171. }
  41172. for(i = 0; i < cartesianIds.length; i++) {
  41173. sp = fullLayout._plots[cartesianIds[i]];
  41174. if(sp._scene) sp._scene.draw();
  41175. }
  41176. for(i = 0; i < polarIds.length; i++) {
  41177. sp = fullLayout[polarIds[i]]._subplot;
  41178. if(sp._scene) sp._scene.draw();
  41179. }
  41180. }
  41181. };
  41182. exports.doAutoRangeAndConstraints = function(gd) {
  41183. var axList = Axes.list(gd, '', true);
  41184. for(var i = 0; i < axList.length; i++) {
  41185. var ax = axList[i];
  41186. cleanAxisConstraints(gd, ax);
  41187. // in case margins changed, update scale
  41188. ax.setScale();
  41189. doAutoRange(gd, ax);
  41190. }
  41191. enforceAxisConstraints(gd);
  41192. };
  41193. // An initial paint must be completed before these components can be
  41194. // correctly sized and the whole plot re-margined. fullLayout._replotting must
  41195. // be set to false before these will work properly.
  41196. exports.finalDraw = function(gd) {
  41197. Registry.getComponentMethod('shapes', 'draw')(gd);
  41198. Registry.getComponentMethod('images', 'draw')(gd);
  41199. Registry.getComponentMethod('annotations', 'draw')(gd);
  41200. // TODO: rangesliders really belong in marginPushers but they need to be
  41201. // drawn after data - can we at least get the margin pushing part separated
  41202. // out and done earlier?
  41203. Registry.getComponentMethod('rangeslider', 'draw')(gd);
  41204. // TODO: rangeselector only needs to be here (in addition to drawMarginPushers)
  41205. // because the margins need to be fully determined before we can call
  41206. // autorange and update axis ranges (which rangeselector needs to know which
  41207. // button is active). Can we break out its automargin step from its draw step?
  41208. Registry.getComponentMethod('rangeselector', 'draw')(gd);
  41209. };
  41210. exports.drawMarginPushers = function(gd) {
  41211. Registry.getComponentMethod('legend', 'draw')(gd);
  41212. Registry.getComponentMethod('rangeselector', 'draw')(gd);
  41213. Registry.getComponentMethod('sliders', 'draw')(gd);
  41214. Registry.getComponentMethod('updatemenus', 'draw')(gd);
  41215. };
  41216. },{"../components/color":51,"../components/drawing":72,"../components/modebar":110,"../components/titles":139,"../constants/alignment":146,"../lib":168,"../lib/clear_gl_canvases":157,"../plots/cartesian/autorange":211,"../plots/cartesian/axes":212,"../plots/cartesian/constraints":220,"../plots/plots":245,"../registry":257,"d3":16}],204:[function(_dereq_,module,exports){
  41217. /**
  41218. * Copyright 2012-2019, Plotly, Inc.
  41219. * All rights reserved.
  41220. *
  41221. * This source code is licensed under the MIT license found in the
  41222. * LICENSE file in the root directory of this source tree.
  41223. */
  41224. 'use strict';
  41225. var Lib = _dereq_('../lib');
  41226. var isPlainObject = Lib.isPlainObject;
  41227. var PlotSchema = _dereq_('./plot_schema');
  41228. var Plots = _dereq_('../plots/plots');
  41229. var plotAttributes = _dereq_('../plots/attributes');
  41230. var Template = _dereq_('./plot_template');
  41231. var dfltConfig = _dereq_('./plot_config').dfltConfig;
  41232. /**
  41233. * Plotly.makeTemplate: create a template off an existing figure to reuse
  41234. * style attributes on other figures.
  41235. *
  41236. * Note: separated from the rest of templates because otherwise we get circular
  41237. * references due to PlotSchema.
  41238. *
  41239. * @param {object|DOM element|string} figure: The figure to base the template on
  41240. * should contain a trace array `figure.data`
  41241. * and a layout object `figure.layout`
  41242. * @returns {object} template: the extracted template - can then be used as
  41243. * `layout.template` in another figure.
  41244. */
  41245. exports.makeTemplate = function(figure) {
  41246. figure = Lib.isPlainObject(figure) ? figure : Lib.getGraphDiv(figure);
  41247. figure = Lib.extendDeep({_context: dfltConfig}, {data: figure.data, layout: figure.layout});
  41248. Plots.supplyDefaults(figure);
  41249. var data = figure.data || [];
  41250. var layout = figure.layout || {};
  41251. // copy over a few items to help follow the schema
  41252. layout._basePlotModules = figure._fullLayout._basePlotModules;
  41253. layout._modules = figure._fullLayout._modules;
  41254. var template = {
  41255. data: {},
  41256. layout: {}
  41257. };
  41258. /*
  41259. * Note: we do NOT validate template values, we just take what's in the
  41260. * user inputs data and layout, not the validated values in fullData and
  41261. * fullLayout. Even if we were to validate here, there's no guarantee that
  41262. * these values would still be valid when applied to a new figure, which
  41263. * may contain different trace modes, different axes, etc. So it's
  41264. * important that when applying a template we still validate the template
  41265. * values, rather than just using them as defaults.
  41266. */
  41267. data.forEach(function(trace) {
  41268. // TODO: What if no style info is extracted for this trace. We may
  41269. // not want an empty object as the null value.
  41270. // TODO: allow transforms to contribute to templates?
  41271. // as it stands they are ignored, which may be for the best...
  41272. var traceTemplate = {};
  41273. walkStyleKeys(trace, traceTemplate, getTraceInfo.bind(null, trace));
  41274. var traceType = Lib.coerce(trace, {}, plotAttributes, 'type');
  41275. var typeTemplates = template.data[traceType];
  41276. if(!typeTemplates) typeTemplates = template.data[traceType] = [];
  41277. typeTemplates.push(traceTemplate);
  41278. });
  41279. walkStyleKeys(layout, template.layout, getLayoutInfo.bind(null, layout));
  41280. /*
  41281. * Compose the new template with an existing one to the same effect
  41282. *
  41283. * NOTE: there's a possibility of slightly different behavior: if the plot
  41284. * has an invalid value and the old template has a valid value for the same
  41285. * attribute, the plot will use the old template value but this routine
  41286. * will pull the invalid value (resulting in the original default).
  41287. * In the general case it's not possible to solve this with a single value,
  41288. * since valid options can be context-dependent. It could be solved with
  41289. * a *list* of values, but that would be huge complexity for little gain.
  41290. */
  41291. delete template.layout.template;
  41292. var oldTemplate = layout.template;
  41293. if(isPlainObject(oldTemplate)) {
  41294. var oldLayoutTemplate = oldTemplate.layout;
  41295. var i, traceType, oldTypeTemplates, oldTypeLen, typeTemplates, typeLen;
  41296. if(isPlainObject(oldLayoutTemplate)) {
  41297. mergeTemplates(oldLayoutTemplate, template.layout);
  41298. }
  41299. var oldDataTemplate = oldTemplate.data;
  41300. if(isPlainObject(oldDataTemplate)) {
  41301. for(traceType in template.data) {
  41302. oldTypeTemplates = oldDataTemplate[traceType];
  41303. if(Array.isArray(oldTypeTemplates)) {
  41304. typeTemplates = template.data[traceType];
  41305. typeLen = typeTemplates.length;
  41306. oldTypeLen = oldTypeTemplates.length;
  41307. for(i = 0; i < typeLen; i++) {
  41308. mergeTemplates(oldTypeTemplates[i % oldTypeLen], typeTemplates[i]);
  41309. }
  41310. for(i = typeLen; i < oldTypeLen; i++) {
  41311. typeTemplates.push(Lib.extendDeep({}, oldTypeTemplates[i]));
  41312. }
  41313. }
  41314. }
  41315. for(traceType in oldDataTemplate) {
  41316. if(!(traceType in template.data)) {
  41317. template.data[traceType] = Lib.extendDeep([], oldDataTemplate[traceType]);
  41318. }
  41319. }
  41320. }
  41321. }
  41322. return template;
  41323. };
  41324. function mergeTemplates(oldTemplate, newTemplate) {
  41325. // we don't care about speed here, just make sure we have a totally
  41326. // distinct object from the previous template
  41327. oldTemplate = Lib.extendDeep({}, oldTemplate);
  41328. // sort keys so we always get annotationdefaults before annotations etc
  41329. // so arrayTemplater will work right
  41330. var oldKeys = Object.keys(oldTemplate).sort();
  41331. var i, j;
  41332. function mergeOne(oldVal, newVal, key) {
  41333. if(isPlainObject(newVal) && isPlainObject(oldVal)) {
  41334. mergeTemplates(oldVal, newVal);
  41335. }
  41336. else if(Array.isArray(newVal) && Array.isArray(oldVal)) {
  41337. // Note: omitted `inclusionAttr` from arrayTemplater here,
  41338. // it's irrelevant as we only want the resulting `_template`.
  41339. var templater = Template.arrayTemplater({_template: oldTemplate}, key);
  41340. for(j = 0; j < newVal.length; j++) {
  41341. var item = newVal[j];
  41342. var oldItem = templater.newItem(item)._template;
  41343. if(oldItem) mergeTemplates(oldItem, item);
  41344. }
  41345. var defaultItems = templater.defaultItems();
  41346. for(j = 0; j < defaultItems.length; j++) newVal.push(defaultItems[j]._template);
  41347. // templateitemname only applies to receiving plots
  41348. for(j = 0; j < newVal.length; j++) delete newVal[j].templateitemname;
  41349. }
  41350. }
  41351. for(i = 0; i < oldKeys.length; i++) {
  41352. var key = oldKeys[i];
  41353. var oldVal = oldTemplate[key];
  41354. if(key in newTemplate) {
  41355. mergeOne(oldVal, newTemplate[key], key);
  41356. }
  41357. else newTemplate[key] = oldVal;
  41358. // if this is a base key from the old template (eg xaxis), look for
  41359. // extended keys (eg xaxis2) in the new template to merge into
  41360. if(getBaseKey(key) === key) {
  41361. for(var key2 in newTemplate) {
  41362. var baseKey2 = getBaseKey(key2);
  41363. if(key2 !== baseKey2 && baseKey2 === key && !(key2 in oldTemplate)) {
  41364. mergeOne(oldVal, newTemplate[key2], key);
  41365. }
  41366. }
  41367. }
  41368. }
  41369. }
  41370. function getBaseKey(key) {
  41371. return key.replace(/[0-9]+$/, '');
  41372. }
  41373. function walkStyleKeys(parent, templateOut, getAttributeInfo, path, basePath) {
  41374. var pathAttr = basePath && getAttributeInfo(basePath);
  41375. for(var key in parent) {
  41376. var child = parent[key];
  41377. var nextPath = getNextPath(parent, key, path);
  41378. var nextBasePath = getNextPath(parent, key, basePath);
  41379. var attr = getAttributeInfo(nextBasePath);
  41380. if(!attr) {
  41381. var baseKey = getBaseKey(key);
  41382. if(baseKey !== key) {
  41383. nextBasePath = getNextPath(parent, baseKey, basePath);
  41384. attr = getAttributeInfo(nextBasePath);
  41385. }
  41386. }
  41387. // we'll get an attr if path starts with a valid part, then has an
  41388. // invalid ending. Make sure we got all the way to the end.
  41389. if(pathAttr && (pathAttr === attr)) continue;
  41390. if(!attr || attr._noTemplating ||
  41391. attr.valType === 'data_array' ||
  41392. (attr.arrayOk && Array.isArray(child))
  41393. ) {
  41394. continue;
  41395. }
  41396. if(!attr.valType && isPlainObject(child)) {
  41397. walkStyleKeys(child, templateOut, getAttributeInfo, nextPath, nextBasePath);
  41398. }
  41399. else if(attr._isLinkedToArray && Array.isArray(child)) {
  41400. var dfltDone = false;
  41401. var namedIndex = 0;
  41402. var usedNames = {};
  41403. for(var i = 0; i < child.length; i++) {
  41404. var item = child[i];
  41405. if(isPlainObject(item)) {
  41406. var name = item.name;
  41407. if(name) {
  41408. if(!usedNames[name]) {
  41409. // named array items: allow all attributes except data arrays
  41410. walkStyleKeys(item, templateOut, getAttributeInfo,
  41411. getNextPath(child, namedIndex, nextPath),
  41412. getNextPath(child, namedIndex, nextBasePath));
  41413. namedIndex++;
  41414. usedNames[name] = 1;
  41415. }
  41416. }
  41417. else if(!dfltDone) {
  41418. var dfltKey = Template.arrayDefaultKey(key);
  41419. var dfltPath = getNextPath(parent, dfltKey, path);
  41420. // getAttributeInfo will fail if we try to use dfltKey directly.
  41421. // Instead put this item into the next array element, then
  41422. // pull it out and move it to dfltKey.
  41423. var pathInArray = getNextPath(child, namedIndex, nextPath);
  41424. walkStyleKeys(item, templateOut, getAttributeInfo, pathInArray,
  41425. getNextPath(child, namedIndex, nextBasePath));
  41426. var itemPropInArray = Lib.nestedProperty(templateOut, pathInArray);
  41427. var dfltProp = Lib.nestedProperty(templateOut, dfltPath);
  41428. dfltProp.set(itemPropInArray.get());
  41429. itemPropInArray.set(null);
  41430. dfltDone = true;
  41431. }
  41432. }
  41433. }
  41434. }
  41435. else {
  41436. var templateProp = Lib.nestedProperty(templateOut, nextPath);
  41437. templateProp.set(child);
  41438. }
  41439. }
  41440. }
  41441. function getLayoutInfo(layout, path) {
  41442. return PlotSchema.getLayoutValObject(
  41443. layout, Lib.nestedProperty({}, path).parts
  41444. );
  41445. }
  41446. function getTraceInfo(trace, path) {
  41447. return PlotSchema.getTraceValObject(
  41448. trace, Lib.nestedProperty({}, path).parts
  41449. );
  41450. }
  41451. function getNextPath(parent, key, path) {
  41452. var nextPath;
  41453. if(!path) nextPath = key;
  41454. else if(Array.isArray(parent)) nextPath = path + '[' + key + ']';
  41455. else nextPath = path + '.' + key;
  41456. return nextPath;
  41457. }
  41458. /**
  41459. * validateTemplate: Test for consistency between the given figure and
  41460. * a template, either already included in the figure or given separately.
  41461. * Note that not every issue we identify here is necessarily a problem,
  41462. * it depends on what you're using the template for.
  41463. *
  41464. * @param {object|DOM element} figure: the plot, with {data, layout} members,
  41465. * to test the template against
  41466. * @param {Optional(object)} template: the template, with its own {data, layout},
  41467. * to test. If omitted, we will look for a template already attached as the
  41468. * plot's `layout.template` attribute.
  41469. *
  41470. * @returns {array} array of error objects each containing:
  41471. * - {string} code
  41472. * error code ('missing', 'unused', 'reused', 'noLayout', 'noData')
  41473. * - {string} msg
  41474. * a full readable description of the issue.
  41475. */
  41476. exports.validateTemplate = function(figureIn, template) {
  41477. var figure = Lib.extendDeep({}, {
  41478. _context: dfltConfig,
  41479. data: figureIn.data,
  41480. layout: figureIn.layout
  41481. });
  41482. var layout = figure.layout || {};
  41483. if(!isPlainObject(template)) template = layout.template || {};
  41484. var layoutTemplate = template.layout;
  41485. var dataTemplate = template.data;
  41486. var errorList = [];
  41487. figure.layout = layout;
  41488. figure.layout.template = template;
  41489. Plots.supplyDefaults(figure);
  41490. var fullLayout = figure._fullLayout;
  41491. var fullData = figure._fullData;
  41492. var layoutPaths = {};
  41493. function crawlLayoutForContainers(obj, paths) {
  41494. for(var key in obj) {
  41495. if(key.charAt(0) !== '_' && isPlainObject(obj[key])) {
  41496. var baseKey = getBaseKey(key);
  41497. var nextPaths = [];
  41498. var i;
  41499. for(i = 0; i < paths.length; i++) {
  41500. nextPaths.push(getNextPath(obj, key, paths[i]));
  41501. if(baseKey !== key) nextPaths.push(getNextPath(obj, baseKey, paths[i]));
  41502. }
  41503. for(i = 0; i < nextPaths.length; i++) {
  41504. layoutPaths[nextPaths[i]] = 1;
  41505. }
  41506. crawlLayoutForContainers(obj[key], nextPaths);
  41507. }
  41508. }
  41509. }
  41510. function crawlLayoutTemplateForContainers(obj, path) {
  41511. for(var key in obj) {
  41512. if(key.indexOf('defaults') === -1 && isPlainObject(obj[key])) {
  41513. var nextPath = getNextPath(obj, key, path);
  41514. if(layoutPaths[nextPath]) {
  41515. crawlLayoutTemplateForContainers(obj[key], nextPath);
  41516. }
  41517. else {
  41518. errorList.push({code: 'unused', path: nextPath});
  41519. }
  41520. }
  41521. }
  41522. }
  41523. if(!isPlainObject(layoutTemplate)) {
  41524. errorList.push({code: 'layout'});
  41525. }
  41526. else {
  41527. crawlLayoutForContainers(fullLayout, ['layout']);
  41528. crawlLayoutTemplateForContainers(layoutTemplate, 'layout');
  41529. }
  41530. if(!isPlainObject(dataTemplate)) {
  41531. errorList.push({code: 'data'});
  41532. }
  41533. else {
  41534. var typeCount = {};
  41535. var traceType;
  41536. for(var i = 0; i < fullData.length; i++) {
  41537. var fullTrace = fullData[i];
  41538. traceType = fullTrace.type;
  41539. typeCount[traceType] = (typeCount[traceType] || 0) + 1;
  41540. if(!fullTrace._fullInput._template) {
  41541. // this takes care of the case of traceType in the data but not
  41542. // the template
  41543. errorList.push({
  41544. code: 'missing',
  41545. index: fullTrace._fullInput.index,
  41546. traceType: traceType
  41547. });
  41548. }
  41549. }
  41550. for(traceType in dataTemplate) {
  41551. var templateCount = dataTemplate[traceType].length;
  41552. var dataCount = typeCount[traceType] || 0;
  41553. if(templateCount > dataCount) {
  41554. errorList.push({
  41555. code: 'unused',
  41556. traceType: traceType,
  41557. templateCount: templateCount,
  41558. dataCount: dataCount
  41559. });
  41560. }
  41561. else if(dataCount > templateCount) {
  41562. errorList.push({
  41563. code: 'reused',
  41564. traceType: traceType,
  41565. templateCount: templateCount,
  41566. dataCount: dataCount
  41567. });
  41568. }
  41569. }
  41570. }
  41571. // _template: false is when someone tried to modify an array item
  41572. // but there was no template with matching name
  41573. function crawlForMissingTemplates(obj, path) {
  41574. for(var key in obj) {
  41575. if(key.charAt(0) === '_') continue;
  41576. var val = obj[key];
  41577. var nextPath = getNextPath(obj, key, path);
  41578. if(isPlainObject(val)) {
  41579. if(Array.isArray(obj) && val._template === false && val.templateitemname) {
  41580. errorList.push({
  41581. code: 'missing',
  41582. path: nextPath,
  41583. templateitemname: val.templateitemname
  41584. });
  41585. }
  41586. crawlForMissingTemplates(val, nextPath);
  41587. }
  41588. else if(Array.isArray(val) && hasPlainObject(val)) {
  41589. crawlForMissingTemplates(val, nextPath);
  41590. }
  41591. }
  41592. }
  41593. crawlForMissingTemplates({data: fullData, layout: fullLayout}, '');
  41594. if(errorList.length) return errorList.map(format);
  41595. };
  41596. function hasPlainObject(arr) {
  41597. for(var i = 0; i < arr.length; i++) {
  41598. if(isPlainObject(arr[i])) return true;
  41599. }
  41600. }
  41601. function format(opts) {
  41602. var msg;
  41603. switch(opts.code) {
  41604. case 'data':
  41605. msg = 'The template has no key data.';
  41606. break;
  41607. case 'layout':
  41608. msg = 'The template has no key layout.';
  41609. break;
  41610. case 'missing':
  41611. if(opts.path) {
  41612. msg = 'There are no templates for item ' + opts.path +
  41613. ' with name ' + opts.templateitemname;
  41614. }
  41615. else {
  41616. msg = 'There are no templates for trace ' + opts.index +
  41617. ', of type ' + opts.traceType + '.';
  41618. }
  41619. break;
  41620. case 'unused':
  41621. if(opts.path) {
  41622. msg = 'The template item at ' + opts.path +
  41623. ' was not used in constructing the plot.';
  41624. }
  41625. else if(opts.dataCount) {
  41626. msg = 'Some of the templates of type ' + opts.traceType +
  41627. ' were not used. The template has ' + opts.templateCount +
  41628. ' traces, the data only has ' + opts.dataCount +
  41629. ' of this type.';
  41630. }
  41631. else {
  41632. msg = 'The template has ' + opts.templateCount +
  41633. ' traces of type ' + opts.traceType +
  41634. ' but there are none in the data.';
  41635. }
  41636. break;
  41637. case 'reused':
  41638. msg = 'Some of the templates of type ' + opts.traceType +
  41639. ' were used more than once. The template has ' +
  41640. opts.templateCount + ' traces, the data has ' +
  41641. opts.dataCount + ' of this type.';
  41642. break;
  41643. }
  41644. opts.msg = msg;
  41645. return opts;
  41646. }
  41647. },{"../lib":168,"../plots/attributes":209,"../plots/plots":245,"./plot_config":200,"./plot_schema":201,"./plot_template":202}],205:[function(_dereq_,module,exports){
  41648. /**
  41649. * Copyright 2012-2019, Plotly, Inc.
  41650. * All rights reserved.
  41651. *
  41652. * This source code is licensed under the MIT license found in the
  41653. * LICENSE file in the root directory of this source tree.
  41654. */
  41655. 'use strict';
  41656. var plotApi = _dereq_('./plot_api');
  41657. var Lib = _dereq_('../lib');
  41658. var helpers = _dereq_('../snapshot/helpers');
  41659. var toSVG = _dereq_('../snapshot/tosvg');
  41660. var svgToImg = _dereq_('../snapshot/svgtoimg');
  41661. var attrs = {
  41662. format: {
  41663. valType: 'enumerated',
  41664. values: ['png', 'jpeg', 'webp', 'svg'],
  41665. dflt: 'png',
  41666. },
  41667. width: {
  41668. valType: 'number',
  41669. min: 1,
  41670. },
  41671. height: {
  41672. valType: 'number',
  41673. min: 1,
  41674. },
  41675. scale: {
  41676. valType: 'number',
  41677. min: 0,
  41678. dflt: 1,
  41679. },
  41680. setBackground: {
  41681. valType: 'any',
  41682. dflt: false,
  41683. },
  41684. imageDataOnly: {
  41685. valType: 'boolean',
  41686. dflt: false,
  41687. }
  41688. };
  41689. var IMAGE_URL_PREFIX = /^data:image\/\w+;base64,/;
  41690. /** Plotly.toImage
  41691. *
  41692. * @param {object | string | HTML div} gd
  41693. * can either be a data/layout/config object
  41694. * or an existing graph <div>
  41695. * or an id to an existing graph <div>
  41696. * @param {object} opts (see above)
  41697. * @return {promise}
  41698. */
  41699. function toImage(gd, opts) {
  41700. opts = opts || {};
  41701. var data;
  41702. var layout;
  41703. var config;
  41704. if(Lib.isPlainObject(gd)) {
  41705. data = gd.data || [];
  41706. layout = gd.layout || {};
  41707. config = gd.config || {};
  41708. } else {
  41709. gd = Lib.getGraphDiv(gd);
  41710. data = Lib.extendDeep([], gd.data);
  41711. layout = Lib.extendDeep({}, gd.layout);
  41712. config = gd._context;
  41713. }
  41714. function isImpliedOrValid(attr) {
  41715. return !(attr in opts) || Lib.validate(opts[attr], attrs[attr]);
  41716. }
  41717. if(!isImpliedOrValid('width') || !isImpliedOrValid('height')) {
  41718. throw new Error('Height and width should be pixel values.');
  41719. }
  41720. if(!isImpliedOrValid('format')) {
  41721. throw new Error('Image format is not jpeg, png, svg or webp.');
  41722. }
  41723. var fullOpts = {};
  41724. function coerce(attr, dflt) {
  41725. return Lib.coerce(opts, fullOpts, attrs, attr, dflt);
  41726. }
  41727. var format = coerce('format');
  41728. var width = coerce('width');
  41729. var height = coerce('height');
  41730. var scale = coerce('scale');
  41731. var setBackground = coerce('setBackground');
  41732. var imageDataOnly = coerce('imageDataOnly');
  41733. // put the cloned div somewhere off screen before attaching to DOM
  41734. var clonedGd = document.createElement('div');
  41735. clonedGd.style.position = 'absolute';
  41736. clonedGd.style.left = '-5000px';
  41737. document.body.appendChild(clonedGd);
  41738. // extend layout with image options
  41739. var layoutImage = Lib.extendFlat({}, layout);
  41740. if(width) layoutImage.width = width;
  41741. if(height) layoutImage.height = height;
  41742. // extend config for static plot
  41743. var configImage = Lib.extendFlat({}, config, {
  41744. _exportedPlot: true,
  41745. staticPlot: true,
  41746. setBackground: setBackground
  41747. });
  41748. var redrawFunc = helpers.getRedrawFunc(clonedGd);
  41749. function wait() {
  41750. return new Promise(function(resolve) {
  41751. setTimeout(resolve, helpers.getDelay(clonedGd._fullLayout));
  41752. });
  41753. }
  41754. function convert() {
  41755. return new Promise(function(resolve, reject) {
  41756. var svg = toSVG(clonedGd, format, scale);
  41757. var width = clonedGd._fullLayout.width;
  41758. var height = clonedGd._fullLayout.height;
  41759. plotApi.purge(clonedGd);
  41760. document.body.removeChild(clonedGd);
  41761. if(format === 'svg') {
  41762. if(imageDataOnly) {
  41763. return resolve(svg);
  41764. } else {
  41765. return resolve('data:image/svg+xml,' + encodeURIComponent(svg));
  41766. }
  41767. }
  41768. var canvas = document.createElement('canvas');
  41769. canvas.id = Lib.randstr();
  41770. svgToImg({
  41771. format: format,
  41772. width: width,
  41773. height: height,
  41774. scale: scale,
  41775. canvas: canvas,
  41776. svg: svg,
  41777. // ask svgToImg to return a Promise
  41778. // rather than EventEmitter
  41779. // leave EventEmitter for backward
  41780. // compatibility
  41781. promise: true
  41782. })
  41783. .then(resolve)
  41784. .catch(reject);
  41785. });
  41786. }
  41787. function urlToImageData(url) {
  41788. if(imageDataOnly) {
  41789. return url.replace(IMAGE_URL_PREFIX, '');
  41790. } else {
  41791. return url;
  41792. }
  41793. }
  41794. return new Promise(function(resolve, reject) {
  41795. plotApi.plot(clonedGd, data, layoutImage, configImage)
  41796. .then(redrawFunc)
  41797. .then(wait)
  41798. .then(convert)
  41799. .then(function(url) { resolve(urlToImageData(url)); })
  41800. .catch(function(err) { reject(err); });
  41801. });
  41802. }
  41803. module.exports = toImage;
  41804. },{"../lib":168,"../snapshot/helpers":261,"../snapshot/svgtoimg":263,"../snapshot/tosvg":265,"./plot_api":199}],206:[function(_dereq_,module,exports){
  41805. /**
  41806. * Copyright 2012-2019, Plotly, Inc.
  41807. * All rights reserved.
  41808. *
  41809. * This source code is licensed under the MIT license found in the
  41810. * LICENSE file in the root directory of this source tree.
  41811. */
  41812. 'use strict';
  41813. var Lib = _dereq_('../lib');
  41814. var Plots = _dereq_('../plots/plots');
  41815. var PlotSchema = _dereq_('./plot_schema');
  41816. var dfltConfig = _dereq_('./plot_config').dfltConfig;
  41817. var isPlainObject = Lib.isPlainObject;
  41818. var isArray = Array.isArray;
  41819. var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
  41820. /**
  41821. * Validate a data array and layout object.
  41822. *
  41823. * @param {array} data
  41824. * @param {object} layout
  41825. *
  41826. * @return {array} array of error objects each containing:
  41827. * - {string} code
  41828. * error code ('object', 'array', 'schema', 'unused', 'invisible' or 'value')
  41829. * - {string} container
  41830. * container where the error occurs ('data' or 'layout')
  41831. * - {number} trace
  41832. * trace index of the 'data' container where the error occurs
  41833. * - {array} path
  41834. * nested path to the key that causes the error
  41835. * - {string} astr
  41836. * attribute string variant of 'path' compatible with Plotly.restyle and
  41837. * Plotly.relayout.
  41838. * - {string} msg
  41839. * error message (shown in console in logger config argument is enable)
  41840. */
  41841. module.exports = function validate(data, layout) {
  41842. var schema = PlotSchema.get();
  41843. var errorList = [];
  41844. var gd = {_context: Lib.extendFlat({}, dfltConfig)};
  41845. var dataIn, layoutIn;
  41846. if(isArray(data)) {
  41847. gd.data = Lib.extendDeep([], data);
  41848. dataIn = data;
  41849. }
  41850. else {
  41851. gd.data = [];
  41852. dataIn = [];
  41853. errorList.push(format('array', 'data'));
  41854. }
  41855. if(isPlainObject(layout)) {
  41856. gd.layout = Lib.extendDeep({}, layout);
  41857. layoutIn = layout;
  41858. }
  41859. else {
  41860. gd.layout = {};
  41861. layoutIn = {};
  41862. if(arguments.length > 1) {
  41863. errorList.push(format('object', 'layout'));
  41864. }
  41865. }
  41866. // N.B. dataIn and layoutIn are in general not the same as
  41867. // gd.data and gd.layout after supplyDefaults as some attributes
  41868. // in gd.data and gd.layout (still) get mutated during this step.
  41869. Plots.supplyDefaults(gd);
  41870. var dataOut = gd._fullData;
  41871. var len = dataIn.length;
  41872. for(var i = 0; i < len; i++) {
  41873. var traceIn = dataIn[i];
  41874. var base = ['data', i];
  41875. if(!isPlainObject(traceIn)) {
  41876. errorList.push(format('object', base));
  41877. continue;
  41878. }
  41879. var traceOut = dataOut[i];
  41880. var traceType = traceOut.type;
  41881. var traceSchema = schema.traces[traceType].attributes;
  41882. // PlotSchema does something fancy with trace 'type', reset it here
  41883. // to make the trace schema compatible with Lib.validate.
  41884. traceSchema.type = {
  41885. valType: 'enumerated',
  41886. values: [traceType]
  41887. };
  41888. if(traceOut.visible === false && traceIn.visible !== false) {
  41889. errorList.push(format('invisible', base));
  41890. }
  41891. crawl(traceIn, traceOut, traceSchema, errorList, base);
  41892. var transformsIn = traceIn.transforms;
  41893. var transformsOut = traceOut.transforms;
  41894. if(transformsIn) {
  41895. if(!isArray(transformsIn)) {
  41896. errorList.push(format('array', base, ['transforms']));
  41897. }
  41898. base.push('transforms');
  41899. for(var j = 0; j < transformsIn.length; j++) {
  41900. var path = ['transforms', j];
  41901. var transformType = transformsIn[j].type;
  41902. if(!isPlainObject(transformsIn[j])) {
  41903. errorList.push(format('object', base, path));
  41904. continue;
  41905. }
  41906. var transformSchema = schema.transforms[transformType] ?
  41907. schema.transforms[transformType].attributes :
  41908. {};
  41909. // add 'type' to transform schema to validate the transform type
  41910. transformSchema.type = {
  41911. valType: 'enumerated',
  41912. values: Object.keys(schema.transforms)
  41913. };
  41914. crawl(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path);
  41915. }
  41916. }
  41917. }
  41918. var layoutOut = gd._fullLayout;
  41919. var layoutSchema = fillLayoutSchema(schema, dataOut);
  41920. crawl(layoutIn, layoutOut, layoutSchema, errorList, 'layout');
  41921. // return undefined if no validation errors were found
  41922. return (errorList.length === 0) ? void(0) : errorList;
  41923. };
  41924. function crawl(objIn, objOut, schema, list, base, path) {
  41925. path = path || [];
  41926. var keys = Object.keys(objIn);
  41927. for(var i = 0; i < keys.length; i++) {
  41928. var k = keys[i];
  41929. // transforms are handled separately
  41930. if(k === 'transforms') continue;
  41931. var p = path.slice();
  41932. p.push(k);
  41933. var valIn = objIn[k];
  41934. var valOut = objOut[k];
  41935. var nestedSchema = getNestedSchema(schema, k);
  41936. var isInfoArray = (nestedSchema || {}).valType === 'info_array';
  41937. var isColorscale = (nestedSchema || {}).valType === 'colorscale';
  41938. var items = (nestedSchema || {}).items;
  41939. if(!isInSchema(schema, k)) {
  41940. list.push(format('schema', base, p));
  41941. }
  41942. else if(isPlainObject(valIn) && isPlainObject(valOut)) {
  41943. crawl(valIn, valOut, nestedSchema, list, base, p);
  41944. }
  41945. else if(isInfoArray && isArray(valIn)) {
  41946. if(valIn.length > valOut.length) {
  41947. list.push(format('unused', base, p.concat(valOut.length)));
  41948. }
  41949. var len = valOut.length;
  41950. var arrayItems = Array.isArray(items);
  41951. if(arrayItems) len = Math.min(len, items.length);
  41952. var m, n, item, valInPart, valOutPart;
  41953. if(nestedSchema.dimensions === 2) {
  41954. for(n = 0; n < len; n++) {
  41955. if(isArray(valIn[n])) {
  41956. if(valIn[n].length > valOut[n].length) {
  41957. list.push(format('unused', base, p.concat(n, valOut[n].length)));
  41958. }
  41959. var len2 = valOut[n].length;
  41960. for(m = 0; m < (arrayItems ? Math.min(len2, items[n].length) : len2); m++) {
  41961. item = arrayItems ? items[n][m] : items;
  41962. valInPart = valIn[n][m];
  41963. valOutPart = valOut[n][m];
  41964. if(!Lib.validate(valInPart, item)) {
  41965. list.push(format('value', base, p.concat(n, m), valInPart));
  41966. }
  41967. else if(valOutPart !== valInPart && valOutPart !== +valInPart) {
  41968. list.push(format('dynamic', base, p.concat(n, m), valInPart, valOutPart));
  41969. }
  41970. }
  41971. }
  41972. else {
  41973. list.push(format('array', base, p.concat(n), valIn[n]));
  41974. }
  41975. }
  41976. }
  41977. else {
  41978. for(n = 0; n < len; n++) {
  41979. item = arrayItems ? items[n] : items;
  41980. valInPart = valIn[n];
  41981. valOutPart = valOut[n];
  41982. if(!Lib.validate(valInPart, item)) {
  41983. list.push(format('value', base, p.concat(n), valInPart));
  41984. }
  41985. else if(valOutPart !== valInPart && valOutPart !== +valInPart) {
  41986. list.push(format('dynamic', base, p.concat(n), valInPart, valOutPart));
  41987. }
  41988. }
  41989. }
  41990. }
  41991. else if(nestedSchema.items && !isInfoArray && isArray(valIn)) {
  41992. var _nestedSchema = items[Object.keys(items)[0]];
  41993. var indexList = [];
  41994. var j, _p;
  41995. // loop over valOut items while keeping track of their
  41996. // corresponding input container index (given by _index)
  41997. for(j = 0; j < valOut.length; j++) {
  41998. var _index = valOut[j]._index || j;
  41999. _p = p.slice();
  42000. _p.push(_index);
  42001. if(isPlainObject(valIn[_index]) && isPlainObject(valOut[j])) {
  42002. indexList.push(_index);
  42003. var valInj = valIn[_index];
  42004. var valOutj = valOut[j];
  42005. if(isPlainObject(valInj) && valInj.visible !== false && valOutj.visible === false) {
  42006. list.push(format('invisible', base, _p));
  42007. }
  42008. else crawl(valInj, valOutj, _nestedSchema, list, base, _p);
  42009. }
  42010. }
  42011. // loop over valIn to determine where it went wrong for some items
  42012. for(j = 0; j < valIn.length; j++) {
  42013. _p = p.slice();
  42014. _p.push(j);
  42015. if(!isPlainObject(valIn[j])) {
  42016. list.push(format('object', base, _p, valIn[j]));
  42017. }
  42018. else if(indexList.indexOf(j) === -1) {
  42019. list.push(format('unused', base, _p));
  42020. }
  42021. }
  42022. }
  42023. else if(!isPlainObject(valIn) && isPlainObject(valOut)) {
  42024. list.push(format('object', base, p, valIn));
  42025. }
  42026. else if(!isArrayOrTypedArray(valIn) && isArrayOrTypedArray(valOut) && !isInfoArray && !isColorscale) {
  42027. list.push(format('array', base, p, valIn));
  42028. }
  42029. else if(!(k in objOut)) {
  42030. list.push(format('unused', base, p, valIn));
  42031. }
  42032. else if(!Lib.validate(valIn, nestedSchema)) {
  42033. list.push(format('value', base, p, valIn));
  42034. }
  42035. else if(nestedSchema.valType === 'enumerated' &&
  42036. ((nestedSchema.coerceNumber && valIn !== +valOut) || valIn !== valOut)
  42037. ) {
  42038. list.push(format('dynamic', base, p, valIn, valOut));
  42039. }
  42040. }
  42041. return list;
  42042. }
  42043. // the 'full' layout schema depends on the traces types presents
  42044. function fillLayoutSchema(schema, dataOut) {
  42045. var layoutSchema = schema.layout.layoutAttributes;
  42046. for(var i = 0; i < dataOut.length; i++) {
  42047. var traceOut = dataOut[i];
  42048. var traceSchema = schema.traces[traceOut.type];
  42049. var traceLayoutAttr = traceSchema.layoutAttributes;
  42050. if(traceLayoutAttr) {
  42051. if(traceOut.subplot) {
  42052. Lib.extendFlat(layoutSchema[traceSchema.attributes.subplot.dflt], traceLayoutAttr);
  42053. } else {
  42054. Lib.extendFlat(layoutSchema, traceLayoutAttr);
  42055. }
  42056. }
  42057. }
  42058. return layoutSchema;
  42059. }
  42060. // validation error codes
  42061. var code2msgFunc = {
  42062. object: function(base, astr) {
  42063. var prefix;
  42064. if(base === 'layout' && astr === '') prefix = 'The layout argument';
  42065. else if(base[0] === 'data' && astr === '') {
  42066. prefix = 'Trace ' + base[1] + ' in the data argument';
  42067. }
  42068. else prefix = inBase(base) + 'key ' + astr;
  42069. return prefix + ' must be linked to an object container';
  42070. },
  42071. array: function(base, astr) {
  42072. var prefix;
  42073. if(base === 'data') prefix = 'The data argument';
  42074. else prefix = inBase(base) + 'key ' + astr;
  42075. return prefix + ' must be linked to an array container';
  42076. },
  42077. schema: function(base, astr) {
  42078. return inBase(base) + 'key ' + astr + ' is not part of the schema';
  42079. },
  42080. unused: function(base, astr, valIn) {
  42081. var target = isPlainObject(valIn) ? 'container' : 'key';
  42082. return inBase(base) + target + ' ' + astr + ' did not get coerced';
  42083. },
  42084. dynamic: function(base, astr, valIn, valOut) {
  42085. return [
  42086. inBase(base) + 'key',
  42087. astr,
  42088. '(set to \'' + valIn + '\')',
  42089. 'got reset to',
  42090. '\'' + valOut + '\'',
  42091. 'during defaults.'
  42092. ].join(' ');
  42093. },
  42094. invisible: function(base, astr) {
  42095. return (
  42096. astr ? (inBase(base) + 'item ' + astr) : ('Trace ' + base[1])
  42097. ) + ' got defaulted to be not visible';
  42098. },
  42099. value: function(base, astr, valIn) {
  42100. return [
  42101. inBase(base) + 'key ' + astr,
  42102. 'is set to an invalid value (' + valIn + ')'
  42103. ].join(' ');
  42104. }
  42105. };
  42106. function inBase(base) {
  42107. if(isArray(base)) return 'In data trace ' + base[1] + ', ';
  42108. return 'In ' + base + ', ';
  42109. }
  42110. function format(code, base, path, valIn, valOut) {
  42111. path = path || '';
  42112. var container, trace;
  42113. // container is either 'data' or 'layout
  42114. // trace is the trace index if 'data', null otherwise
  42115. if(isArray(base)) {
  42116. container = base[0];
  42117. trace = base[1];
  42118. }
  42119. else {
  42120. container = base;
  42121. trace = null;
  42122. }
  42123. var astr = convertPathToAttributeString(path);
  42124. var msg = code2msgFunc[code](base, astr, valIn, valOut);
  42125. // log to console if logger config option is enabled
  42126. Lib.log(msg);
  42127. return {
  42128. code: code,
  42129. container: container,
  42130. trace: trace,
  42131. path: path,
  42132. astr: astr,
  42133. msg: msg
  42134. };
  42135. }
  42136. function isInSchema(schema, key) {
  42137. var parts = splitKey(key);
  42138. var keyMinusId = parts.keyMinusId;
  42139. var id = parts.id;
  42140. if((keyMinusId in schema) && schema[keyMinusId]._isSubplotObj && id) {
  42141. return true;
  42142. }
  42143. return (key in schema);
  42144. }
  42145. function getNestedSchema(schema, key) {
  42146. if(key in schema) return schema[key];
  42147. var parts = splitKey(key);
  42148. return schema[parts.keyMinusId];
  42149. }
  42150. var idRegex = Lib.counterRegex('([a-z]+)');
  42151. function splitKey(key) {
  42152. var idMatch = key.match(idRegex);
  42153. return {
  42154. keyMinusId: idMatch && idMatch[1],
  42155. id: idMatch && idMatch[2]
  42156. };
  42157. }
  42158. function convertPathToAttributeString(path) {
  42159. if(!isArray(path)) return String(path);
  42160. var astr = '';
  42161. for(var i = 0; i < path.length; i++) {
  42162. var p = path[i];
  42163. if(typeof p === 'number') {
  42164. astr = astr.substr(0, astr.length - 1) + '[' + p + ']';
  42165. }
  42166. else {
  42167. astr += p;
  42168. }
  42169. if(i < path.length - 1) astr += '.';
  42170. }
  42171. return astr;
  42172. }
  42173. },{"../lib":168,"../plots/plots":245,"./plot_config":200,"./plot_schema":201}],207:[function(_dereq_,module,exports){
  42174. /**
  42175. * Copyright 2012-2019, Plotly, Inc.
  42176. * All rights reserved.
  42177. *
  42178. * This source code is licensed under the MIT license found in the
  42179. * LICENSE file in the root directory of this source tree.
  42180. */
  42181. 'use strict';
  42182. module.exports = {
  42183. mode: {
  42184. valType: 'enumerated',
  42185. dflt: 'afterall',
  42186. values: ['immediate', 'next', 'afterall'],
  42187. },
  42188. direction: {
  42189. valType: 'enumerated',
  42190. values: ['forward', 'reverse'],
  42191. dflt: 'forward',
  42192. },
  42193. fromcurrent: {
  42194. valType: 'boolean',
  42195. dflt: false,
  42196. },
  42197. frame: {
  42198. duration: {
  42199. valType: 'number',
  42200. min: 0,
  42201. dflt: 500,
  42202. },
  42203. redraw: {
  42204. valType: 'boolean',
  42205. dflt: true,
  42206. },
  42207. },
  42208. transition: {
  42209. duration: {
  42210. valType: 'number',
  42211. min: 0,
  42212. dflt: 500,
  42213. editType: 'none',
  42214. },
  42215. easing: {
  42216. valType: 'enumerated',
  42217. dflt: 'cubic-in-out',
  42218. values: [
  42219. 'linear',
  42220. 'quad',
  42221. 'cubic',
  42222. 'sin',
  42223. 'exp',
  42224. 'circle',
  42225. 'elastic',
  42226. 'back',
  42227. 'bounce',
  42228. 'linear-in',
  42229. 'quad-in',
  42230. 'cubic-in',
  42231. 'sin-in',
  42232. 'exp-in',
  42233. 'circle-in',
  42234. 'elastic-in',
  42235. 'back-in',
  42236. 'bounce-in',
  42237. 'linear-out',
  42238. 'quad-out',
  42239. 'cubic-out',
  42240. 'sin-out',
  42241. 'exp-out',
  42242. 'circle-out',
  42243. 'elastic-out',
  42244. 'back-out',
  42245. 'bounce-out',
  42246. 'linear-in-out',
  42247. 'quad-in-out',
  42248. 'cubic-in-out',
  42249. 'sin-in-out',
  42250. 'exp-in-out',
  42251. 'circle-in-out',
  42252. 'elastic-in-out',
  42253. 'back-in-out',
  42254. 'bounce-in-out'
  42255. ],
  42256. editType: 'none',
  42257. },
  42258. ordering: {
  42259. valType: 'enumerated',
  42260. values: ['layout first', 'traces first'],
  42261. dflt: 'layout first',
  42262. editType: 'none',
  42263. }
  42264. }
  42265. };
  42266. },{}],208:[function(_dereq_,module,exports){
  42267. /**
  42268. * Copyright 2012-2019, Plotly, Inc.
  42269. * All rights reserved.
  42270. *
  42271. * This source code is licensed under the MIT license found in the
  42272. * LICENSE file in the root directory of this source tree.
  42273. */
  42274. 'use strict';
  42275. var Lib = _dereq_('../lib');
  42276. var Template = _dereq_('../plot_api/plot_template');
  42277. /** Convenience wrapper for making array container logic DRY and consistent
  42278. *
  42279. * @param {object} parentObjIn
  42280. * user input object where the container in question is linked
  42281. * (i.e. either a user trace object or the user layout object)
  42282. *
  42283. * @param {object} parentObjOut
  42284. * full object where the coerced container will be linked
  42285. * (i.e. either a full trace object or the full layout object)
  42286. *
  42287. * @param {object} opts
  42288. * options object:
  42289. * - name {string}
  42290. * name of the key linking the container in question
  42291. * - inclusionAttr {string}
  42292. * name of the item attribute for inclusion/exclusion. Default is 'visible'.
  42293. * Since inclusion is true, use eg 'enabled' instead of 'disabled'.
  42294. * - handleItemDefaults {function}
  42295. * defaults method to be called on each item in the array container in question
  42296. *
  42297. * Its arguments are:
  42298. * - itemIn {object} item in user layout
  42299. * - itemOut {object} item in full layout
  42300. * - parentObj {object} (as in closure)
  42301. * - opts {object} (as in closure)
  42302. * N.B.
  42303. *
  42304. * - opts is passed to handleItemDefaults so it can also store
  42305. * links to supplementary data (e.g. fullData for layout components)
  42306. *
  42307. */
  42308. module.exports = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) {
  42309. var name = opts.name;
  42310. var inclusionAttr = opts.inclusionAttr || 'visible';
  42311. var previousContOut = parentObjOut[name];
  42312. var contIn = Lib.isArrayOrTypedArray(parentObjIn[name]) ? parentObjIn[name] : [];
  42313. var contOut = parentObjOut[name] = [];
  42314. var templater = Template.arrayTemplater(parentObjOut, name, inclusionAttr);
  42315. var i, itemOut;
  42316. for(i = 0; i < contIn.length; i++) {
  42317. var itemIn = contIn[i];
  42318. if(!Lib.isPlainObject(itemIn)) {
  42319. itemOut = templater.newItem({});
  42320. itemOut[inclusionAttr] = false;
  42321. }
  42322. else {
  42323. itemOut = templater.newItem(itemIn);
  42324. }
  42325. itemOut._index = i;
  42326. if(itemOut[inclusionAttr] !== false) {
  42327. opts.handleItemDefaults(itemIn, itemOut, parentObjOut, opts);
  42328. }
  42329. contOut.push(itemOut);
  42330. }
  42331. var defaultItems = templater.defaultItems();
  42332. for(i = 0; i < defaultItems.length; i++) {
  42333. itemOut = defaultItems[i];
  42334. itemOut._index = contOut.length;
  42335. opts.handleItemDefaults({}, itemOut, parentObjOut, opts, {});
  42336. contOut.push(itemOut);
  42337. }
  42338. // in case this array gets its defaults rebuilt independent of the whole layout,
  42339. // relink the private keys just for this array.
  42340. if(Lib.isArrayOrTypedArray(previousContOut)) {
  42341. var len = Math.min(previousContOut.length, contOut.length);
  42342. for(i = 0; i < len; i++) {
  42343. Lib.relinkPrivateKeys(contOut[i], previousContOut[i]);
  42344. }
  42345. }
  42346. return contOut;
  42347. };
  42348. },{"../lib":168,"../plot_api/plot_template":202}],209:[function(_dereq_,module,exports){
  42349. /**
  42350. * Copyright 2012-2019, Plotly, Inc.
  42351. * All rights reserved.
  42352. *
  42353. * This source code is licensed under the MIT license found in the
  42354. * LICENSE file in the root directory of this source tree.
  42355. */
  42356. 'use strict';
  42357. var fxAttrs = _dereq_('../components/fx/attributes');
  42358. module.exports = {
  42359. type: {
  42360. valType: 'enumerated',
  42361. values: [], // listed dynamically
  42362. dflt: 'scatter',
  42363. editType: 'calc+clearAxisTypes',
  42364. _noTemplating: true // we handle this at a higher level
  42365. },
  42366. visible: {
  42367. valType: 'enumerated',
  42368. values: [true, false, 'legendonly'],
  42369. dflt: true,
  42370. editType: 'calc',
  42371. },
  42372. showlegend: {
  42373. valType: 'boolean',
  42374. dflt: true,
  42375. editType: 'style',
  42376. },
  42377. legendgroup: {
  42378. valType: 'string',
  42379. dflt: '',
  42380. editType: 'style',
  42381. },
  42382. opacity: {
  42383. valType: 'number',
  42384. min: 0,
  42385. max: 1,
  42386. dflt: 1,
  42387. editType: 'style',
  42388. },
  42389. name: {
  42390. valType: 'string',
  42391. editType: 'style',
  42392. },
  42393. uid: {
  42394. valType: 'string',
  42395. editType: 'plot',
  42396. anim: true,
  42397. },
  42398. ids: {
  42399. valType: 'data_array',
  42400. editType: 'calc',
  42401. anim: true,
  42402. },
  42403. customdata: {
  42404. valType: 'data_array',
  42405. editType: 'calc',
  42406. },
  42407. // N.B. these cannot be 'data_array' as they do not have the same length as
  42408. // other data arrays and arrayOk attributes in general
  42409. //
  42410. // Maybe add another valType:
  42411. // https://github.com/plotly/plotly.js/issues/1894
  42412. selectedpoints: {
  42413. valType: 'any',
  42414. editType: 'calc',
  42415. },
  42416. hoverinfo: {
  42417. valType: 'flaglist',
  42418. flags: ['x', 'y', 'z', 'text', 'name'],
  42419. extras: ['all', 'none', 'skip'],
  42420. arrayOk: true,
  42421. dflt: 'all',
  42422. editType: 'none',
  42423. },
  42424. hoverlabel: fxAttrs.hoverlabel,
  42425. stream: {
  42426. token: {
  42427. valType: 'string',
  42428. noBlank: true,
  42429. strict: true,
  42430. editType: 'calc',
  42431. },
  42432. maxpoints: {
  42433. valType: 'number',
  42434. min: 0,
  42435. max: 10000,
  42436. dflt: 500,
  42437. editType: 'calc',
  42438. },
  42439. editType: 'calc'
  42440. },
  42441. transforms: {
  42442. _isLinkedToArray: 'transform',
  42443. editType: 'calc',
  42444. },
  42445. uirevision: {
  42446. valType: 'any',
  42447. editType: 'none',
  42448. }
  42449. };
  42450. },{"../components/fx/attributes":81}],210:[function(_dereq_,module,exports){
  42451. /**
  42452. * Copyright 2012-2019, Plotly, Inc.
  42453. * All rights reserved.
  42454. *
  42455. * This source code is licensed under the MIT license found in the
  42456. * LICENSE file in the root directory of this source tree.
  42457. */
  42458. 'use strict';
  42459. module.exports = {
  42460. xaxis: {
  42461. valType: 'subplotid',
  42462. dflt: 'x',
  42463. editType: 'calc+clearAxisTypes',
  42464. },
  42465. yaxis: {
  42466. valType: 'subplotid',
  42467. dflt: 'y',
  42468. editType: 'calc+clearAxisTypes',
  42469. }
  42470. };
  42471. },{}],211:[function(_dereq_,module,exports){
  42472. /**
  42473. * Copyright 2012-2019, Plotly, Inc.
  42474. * All rights reserved.
  42475. *
  42476. * This source code is licensed under the MIT license found in the
  42477. * LICENSE file in the root directory of this source tree.
  42478. */
  42479. 'use strict';
  42480. var isNumeric = _dereq_('fast-isnumeric');
  42481. var Lib = _dereq_('../../lib');
  42482. var FP_SAFE = _dereq_('../../constants/numerical').FP_SAFE;
  42483. var Registry = _dereq_('../../registry');
  42484. module.exports = {
  42485. getAutoRange: getAutoRange,
  42486. makePadFn: makePadFn,
  42487. doAutoRange: doAutoRange,
  42488. findExtremes: findExtremes,
  42489. concatExtremes: concatExtremes
  42490. };
  42491. /**
  42492. * getAutoRange
  42493. *
  42494. * Collects all _extremes values corresponding to a given axis
  42495. * and computes its auto range.
  42496. *
  42497. * Note that getAutoRange uses return values from findExtremes.
  42498. *
  42499. * @param {object} gd:
  42500. * graph div object with filled-in fullData and fullLayout, in particular
  42501. * with filled-in '_extremes' containers:
  42502. * {
  42503. * val: calcdata value,
  42504. * pad: extra pixels beyond this value,
  42505. * extrapad: bool, does this point want 5% extra padding
  42506. * }
  42507. * @param {object} ax:
  42508. * full axis object, in particular with filled-in '_traceIndices'
  42509. * and '_annIndices' / '_shapeIndices' if applicable
  42510. * @return {array}
  42511. * an array of [min, max]. These are calcdata for log and category axes
  42512. * and data for linear and date axes.
  42513. *
  42514. * TODO: we want to change log to data as well, but it's hard to do this
  42515. * maintaining backward compatibility. category will always have to use calcdata
  42516. * though, because otherwise values between categories (or outside all categories)
  42517. * would be impossible.
  42518. */
  42519. function getAutoRange(gd, ax) {
  42520. var i, j;
  42521. var newRange = [];
  42522. var getPad = makePadFn(ax);
  42523. var extremes = concatExtremes(gd, ax);
  42524. var minArray = extremes.min;
  42525. var maxArray = extremes.max;
  42526. if(minArray.length === 0 || maxArray.length === 0) {
  42527. return Lib.simpleMap(ax.range, ax.r2l);
  42528. }
  42529. var minmin = minArray[0].val;
  42530. var maxmax = maxArray[0].val;
  42531. for(i = 1; i < minArray.length; i++) {
  42532. if(minmin !== maxmax) break;
  42533. minmin = Math.min(minmin, minArray[i].val);
  42534. }
  42535. for(i = 1; i < maxArray.length; i++) {
  42536. if(minmin !== maxmax) break;
  42537. maxmax = Math.max(maxmax, maxArray[i].val);
  42538. }
  42539. var axReverse = false;
  42540. if(ax.range) {
  42541. var rng = Lib.simpleMap(ax.range, ax.r2l);
  42542. axReverse = rng[1] < rng[0];
  42543. }
  42544. // one-time setting to easily reverse the axis
  42545. // when plotting from code
  42546. if(ax.autorange === 'reversed') {
  42547. axReverse = true;
  42548. ax.autorange = true;
  42549. }
  42550. var rangeMode = ax.rangemode;
  42551. var toZero = rangeMode === 'tozero';
  42552. var nonNegative = rangeMode === 'nonnegative';
  42553. var axLen = ax._length;
  42554. // don't allow padding to reduce the data to < 10% of the length
  42555. var minSpan = axLen / 10;
  42556. var mbest = 0;
  42557. var minpt, maxpt, minbest, maxbest, dp, dv;
  42558. for(i = 0; i < minArray.length; i++) {
  42559. minpt = minArray[i];
  42560. for(j = 0; j < maxArray.length; j++) {
  42561. maxpt = maxArray[j];
  42562. dv = maxpt.val - minpt.val;
  42563. if(dv > 0) {
  42564. dp = axLen - getPad(minpt) - getPad(maxpt);
  42565. if(dp > minSpan) {
  42566. if(dv / dp > mbest) {
  42567. minbest = minpt;
  42568. maxbest = maxpt;
  42569. mbest = dv / dp;
  42570. }
  42571. }
  42572. else if(dv / axLen > mbest) {
  42573. // in case of padding longer than the axis
  42574. // at least include the unpadded data values.
  42575. minbest = {val: minpt.val, pad: 0};
  42576. maxbest = {val: maxpt.val, pad: 0};
  42577. mbest = dv / axLen;
  42578. }
  42579. }
  42580. }
  42581. }
  42582. function getMaxPad(prev, pt) {
  42583. return Math.max(prev, getPad(pt));
  42584. }
  42585. if(minmin === maxmax) {
  42586. var lower = minmin - 1;
  42587. var upper = minmin + 1;
  42588. if(toZero) {
  42589. if(minmin === 0) {
  42590. // The only value we have on this axis is 0, and we want to
  42591. // autorange so zero is one end.
  42592. // In principle this could be [0, 1] or [-1, 0] but usually
  42593. // 'tozero' pins 0 to the low end, so follow that.
  42594. newRange = [0, 1];
  42595. }
  42596. else {
  42597. var maxPad = (minmin > 0 ? maxArray : minArray).reduce(getMaxPad, 0);
  42598. // we're pushing a single value away from the edge due to its
  42599. // padding, with the other end clamped at zero
  42600. // 0.5 means don't push it farther than the center.
  42601. var rangeEnd = minmin / (1 - Math.min(0.5, maxPad / axLen));
  42602. newRange = minmin > 0 ? [0, rangeEnd] : [rangeEnd, 0];
  42603. }
  42604. } else if(nonNegative) {
  42605. newRange = [Math.max(0, lower), Math.max(1, upper)];
  42606. } else {
  42607. newRange = [lower, upper];
  42608. }
  42609. }
  42610. else {
  42611. if(toZero) {
  42612. if(minbest.val >= 0) {
  42613. minbest = {val: 0, pad: 0};
  42614. }
  42615. if(maxbest.val <= 0) {
  42616. maxbest = {val: 0, pad: 0};
  42617. }
  42618. }
  42619. else if(nonNegative) {
  42620. if(minbest.val - mbest * getPad(minbest) < 0) {
  42621. minbest = {val: 0, pad: 0};
  42622. }
  42623. if(maxbest.val <= 0) {
  42624. maxbest = {val: 1, pad: 0};
  42625. }
  42626. }
  42627. // in case it changed again...
  42628. mbest = (maxbest.val - minbest.val) /
  42629. (axLen - getPad(minbest) - getPad(maxbest));
  42630. newRange = [
  42631. minbest.val - mbest * getPad(minbest),
  42632. maxbest.val + mbest * getPad(maxbest)
  42633. ];
  42634. }
  42635. // maintain reversal
  42636. if(axReverse) newRange.reverse();
  42637. return Lib.simpleMap(newRange, ax.l2r || Number);
  42638. }
  42639. /*
  42640. * calculate the pixel padding for ax._min and ax._max entries with
  42641. * optional extrapad as 5% of the total axis length
  42642. */
  42643. function makePadFn(ax) {
  42644. // 5% padding for points that specify extrapad: true
  42645. var extrappad = ax._length / 20;
  42646. // domain-constrained axes: base extrappad on the unconstrained
  42647. // domain so it's consistent as the domain changes
  42648. if((ax.constrain === 'domain') && ax._inputDomain) {
  42649. extrappad *= (ax._inputDomain[1] - ax._inputDomain[0]) /
  42650. (ax.domain[1] - ax.domain[0]);
  42651. }
  42652. return function getPad(pt) { return pt.pad + (pt.extrapad ? extrappad : 0); };
  42653. }
  42654. function concatExtremes(gd, ax) {
  42655. var axId = ax._id;
  42656. var fullData = gd._fullData;
  42657. var fullLayout = gd._fullLayout;
  42658. var minArray = [];
  42659. var maxArray = [];
  42660. var i, j, d;
  42661. function _concat(cont, indices) {
  42662. for(i = 0; i < indices.length; i++) {
  42663. var item = cont[indices[i]];
  42664. var extremes = (item._extremes || {})[axId];
  42665. if(item.visible === true && extremes) {
  42666. for(j = 0; j < extremes.min.length; j++) {
  42667. d = extremes.min[j];
  42668. collapseMinArray(minArray, d.val, d.pad, {extrapad: d.extrapad});
  42669. }
  42670. for(j = 0; j < extremes.max.length; j++) {
  42671. d = extremes.max[j];
  42672. collapseMaxArray(maxArray, d.val, d.pad, {extrapad: d.extrapad});
  42673. }
  42674. }
  42675. }
  42676. }
  42677. _concat(fullData, ax._traceIndices);
  42678. _concat(fullLayout.annotations || [], ax._annIndices || []);
  42679. _concat(fullLayout.shapes || [], ax._shapeIndices || []);
  42680. return {min: minArray, max: maxArray};
  42681. }
  42682. function doAutoRange(gd, ax) {
  42683. if(ax.autorange) {
  42684. ax.range = getAutoRange(gd, ax);
  42685. ax._r = ax.range.slice();
  42686. ax._rl = Lib.simpleMap(ax._r, ax.r2l);
  42687. // doAutoRange will get called on fullLayout,
  42688. // but we want to report its results back to layout
  42689. var axIn = ax._input;
  42690. // before we edit _input, store preGUI values
  42691. var edits = {};
  42692. edits[ax._attr + '.range'] = ax.range;
  42693. edits[ax._attr + '.autorange'] = ax.autorange;
  42694. Registry.call('_storeDirectGUIEdit', gd.layout, gd._fullLayout._preGUI, edits);
  42695. axIn.range = ax.range.slice();
  42696. axIn.autorange = ax.autorange;
  42697. }
  42698. var anchorAx = ax._anchorAxis;
  42699. if(anchorAx && anchorAx.rangeslider) {
  42700. var axeRangeOpts = anchorAx.rangeslider[ax._name];
  42701. if(axeRangeOpts) {
  42702. if(axeRangeOpts.rangemode === 'auto') {
  42703. axeRangeOpts.range = getAutoRange(gd, ax);
  42704. }
  42705. }
  42706. anchorAx._input.rangeslider[ax._name] = Lib.extendFlat({}, axeRangeOpts);
  42707. }
  42708. }
  42709. /**
  42710. * findExtremes
  42711. *
  42712. * Find min/max extremes of an array of coordinates on a given axis.
  42713. *
  42714. * Note that findExtremes is called during `calc`, when we don't yet know the axis
  42715. * length; all the inputs should be based solely on the trace data, nothing
  42716. * about the axis layout.
  42717. *
  42718. * Note that `ppad` and `vpad` as well as their asymmetric variants refer to
  42719. * the before and after padding of the passed `data` array, not to the whole axis.
  42720. *
  42721. * @param {object} ax: full axis object
  42722. * relies on
  42723. * - ax.type
  42724. * - ax._m (just its sign)
  42725. * - ax.d2l
  42726. * @param {array} data:
  42727. * array of numbers (i.e. already run though ax.d2c)
  42728. * @param {object} opts:
  42729. * available keys are:
  42730. * vpad: (number or number array) pad values (data value +-vpad)
  42731. * ppad: (number or number array) pad pixels (pixel location +-ppad)
  42732. * ppadplus, ppadminus, vpadplus, vpadminus:
  42733. * separate padding for each side, overrides symmetric
  42734. * padded: (boolean) add 5% padding to both ends
  42735. * (unless one end is overridden by tozero)
  42736. * tozero: (boolean) make sure to include zero if axis is linear,
  42737. * and make it a tight bound if possible
  42738. *
  42739. * @return {object}
  42740. * - min {array of objects}
  42741. * - max {array of objects}
  42742. * each object item has fields:
  42743. * - val {number}
  42744. * - pad {number}
  42745. * - extrappad {number}
  42746. * - opts {object}: a ref to the passed "options" object
  42747. */
  42748. function findExtremes(ax, data, opts) {
  42749. if(!opts) opts = {};
  42750. if(!ax._m) ax.setScale();
  42751. var minArray = [];
  42752. var maxArray = [];
  42753. var len = data.length;
  42754. var extrapad = opts.padded || false;
  42755. var tozero = opts.tozero && (ax.type === 'linear' || ax.type === '-');
  42756. var isLog = ax.type === 'log';
  42757. var hasArrayOption = false;
  42758. var i, v, di, dmin, dmax, ppadiplus, ppadiminus, vmin, vmax;
  42759. function makePadAccessor(item) {
  42760. if(Array.isArray(item)) {
  42761. hasArrayOption = true;
  42762. return function(i) { return Math.max(Number(item[i]||0), 0); };
  42763. }
  42764. else {
  42765. var v = Math.max(Number(item||0), 0);
  42766. return function() { return v; };
  42767. }
  42768. }
  42769. var ppadplus = makePadAccessor((ax._m > 0 ?
  42770. opts.ppadplus : opts.ppadminus) || opts.ppad || 0);
  42771. var ppadminus = makePadAccessor((ax._m > 0 ?
  42772. opts.ppadminus : opts.ppadplus) || opts.ppad || 0);
  42773. var vpadplus = makePadAccessor(opts.vpadplus || opts.vpad);
  42774. var vpadminus = makePadAccessor(opts.vpadminus || opts.vpad);
  42775. if(!hasArrayOption) {
  42776. // with no arrays other than `data` we don't need to consider
  42777. // every point, only the extreme data points
  42778. vmin = Infinity;
  42779. vmax = -Infinity;
  42780. if(isLog) {
  42781. for(i = 0; i < len; i++) {
  42782. v = data[i];
  42783. // data is not linearized yet so we still have to filter out negative logs
  42784. if(v < vmin && v > 0) vmin = v;
  42785. if(v > vmax && v < FP_SAFE) vmax = v;
  42786. }
  42787. } else {
  42788. for(i = 0; i < len; i++) {
  42789. v = data[i];
  42790. if(v < vmin && v > -FP_SAFE) vmin = v;
  42791. if(v > vmax && v < FP_SAFE) vmax = v;
  42792. }
  42793. }
  42794. data = [vmin, vmax];
  42795. len = 2;
  42796. }
  42797. var collapseOpts = {tozero: tozero, extrapad: extrapad};
  42798. function addItem(i) {
  42799. di = data[i];
  42800. if(!isNumeric(di)) return;
  42801. ppadiplus = ppadplus(i);
  42802. ppadiminus = ppadminus(i);
  42803. vmin = di - vpadminus(i);
  42804. vmax = di + vpadplus(i);
  42805. // special case for log axes: if vpad makes this object span
  42806. // more than an order of mag, clip it to one order. This is so
  42807. // we don't have non-positive errors or absurdly large lower
  42808. // range due to rounding errors
  42809. if(isLog && vmin < vmax / 10) vmin = vmax / 10;
  42810. dmin = ax.c2l(vmin);
  42811. dmax = ax.c2l(vmax);
  42812. if(tozero) {
  42813. dmin = Math.min(0, dmin);
  42814. dmax = Math.max(0, dmax);
  42815. }
  42816. if(goodNumber(dmin)) {
  42817. collapseMinArray(minArray, dmin, ppadiminus, collapseOpts);
  42818. }
  42819. if(goodNumber(dmax)) {
  42820. collapseMaxArray(maxArray, dmax, ppadiplus, collapseOpts);
  42821. }
  42822. }
  42823. // For efficiency covering monotonic or near-monotonic data,
  42824. // check a few points at both ends first and then sweep
  42825. // through the middle
  42826. var iMax = Math.min(6, len);
  42827. for(i = 0; i < iMax; i++) addItem(i);
  42828. for(i = len - 1; i >= iMax; i--) addItem(i);
  42829. return {
  42830. min: minArray,
  42831. max: maxArray,
  42832. opts: opts
  42833. };
  42834. }
  42835. function collapseMinArray(array, newVal, newPad, opts) {
  42836. collapseArray(array, newVal, newPad, opts, lessOrEqual);
  42837. }
  42838. function collapseMaxArray(array, newVal, newPad, opts) {
  42839. collapseArray(array, newVal, newPad, opts, greaterOrEqual);
  42840. }
  42841. /**
  42842. * collapseArray
  42843. *
  42844. * Takes items from 'array' and compares them to 'newVal', 'newPad'.
  42845. *
  42846. * @param {array} array:
  42847. * current set of min or max extremes
  42848. * @param {number} newVal:
  42849. * new value to compare against
  42850. * @param {number} newPad:
  42851. * pad value associated with 'newVal'
  42852. * @param {object} opts:
  42853. * - tozero {boolean}
  42854. * - extrapad {number}
  42855. * @param {function} atLeastAsExtreme:
  42856. * comparison function, use
  42857. * - lessOrEqual for min 'array' and
  42858. * - greaterOrEqual for max 'array'
  42859. *
  42860. * In practice, 'array' is either
  42861. * - 'extremes[ax._id].min' or
  42862. * - 'extremes[ax._id].max
  42863. * found in traces and layout items that affect autorange.
  42864. *
  42865. * Since we don't yet know the relationship between pixels and values
  42866. * (that's what we're trying to figure out!) AND we don't yet know how
  42867. * many pixels `extrapad` represents (it's going to be 5% of the length,
  42868. * but we don't want to have to redo calc just because length changed)
  42869. * two point must satisfy three criteria simultaneously for one to supersede the other:
  42870. * - at least as extreme a `val`
  42871. * - at least as big a `pad`
  42872. * - an unpadded point cannot supersede a padded point, but any other combination can
  42873. *
  42874. * Then:
  42875. * - If the item supersedes the new point, set includeThis false
  42876. * - If the new pt supersedes the item, delete it from 'array'
  42877. */
  42878. function collapseArray(array, newVal, newPad, opts, atLeastAsExtreme) {
  42879. var tozero = opts.tozero;
  42880. var extrapad = opts.extrapad;
  42881. var includeThis = true;
  42882. for(var j = 0; j < array.length && includeThis; j++) {
  42883. var v = array[j];
  42884. if(atLeastAsExtreme(v.val, newVal) && v.pad >= newPad && (v.extrapad || !extrapad)) {
  42885. includeThis = false;
  42886. break;
  42887. } else if(atLeastAsExtreme(newVal, v.val) && v.pad <= newPad && (extrapad || !v.extrapad)) {
  42888. array.splice(j, 1);
  42889. j--;
  42890. }
  42891. }
  42892. if(includeThis) {
  42893. var clipAtZero = (tozero && newVal === 0);
  42894. array.push({
  42895. val: newVal,
  42896. pad: clipAtZero ? 0 : newPad,
  42897. extrapad: clipAtZero ? false : extrapad
  42898. });
  42899. }
  42900. }
  42901. // In order to stop overflow errors, don't consider points
  42902. // too close to the limits of js floating point
  42903. function goodNumber(v) {
  42904. return isNumeric(v) && Math.abs(v) < FP_SAFE;
  42905. }
  42906. function lessOrEqual(v0, v1) { return v0 <= v1; }
  42907. function greaterOrEqual(v0, v1) { return v0 >= v1; }
  42908. },{"../../constants/numerical":149,"../../lib":168,"../../registry":257,"fast-isnumeric":18}],212:[function(_dereq_,module,exports){
  42909. /**
  42910. * Copyright 2012-2019, Plotly, Inc.
  42911. * All rights reserved.
  42912. *
  42913. * This source code is licensed under the MIT license found in the
  42914. * LICENSE file in the root directory of this source tree.
  42915. */
  42916. 'use strict';
  42917. var d3 = _dereq_('d3');
  42918. var isNumeric = _dereq_('fast-isnumeric');
  42919. var Plots = _dereq_('../../plots/plots');
  42920. var Registry = _dereq_('../../registry');
  42921. var Lib = _dereq_('../../lib');
  42922. var svgTextUtils = _dereq_('../../lib/svg_text_utils');
  42923. var Titles = _dereq_('../../components/titles');
  42924. var Color = _dereq_('../../components/color');
  42925. var Drawing = _dereq_('../../components/drawing');
  42926. var axAttrs = _dereq_('./layout_attributes');
  42927. var cleanTicks = _dereq_('./clean_ticks');
  42928. var constants = _dereq_('../../constants/numerical');
  42929. var ONEAVGYEAR = constants.ONEAVGYEAR;
  42930. var ONEAVGMONTH = constants.ONEAVGMONTH;
  42931. var ONEDAY = constants.ONEDAY;
  42932. var ONEHOUR = constants.ONEHOUR;
  42933. var ONEMIN = constants.ONEMIN;
  42934. var ONESEC = constants.ONESEC;
  42935. var MINUS_SIGN = constants.MINUS_SIGN;
  42936. var BADNUM = constants.BADNUM;
  42937. var MID_SHIFT = _dereq_('../../constants/alignment').MID_SHIFT;
  42938. var LINE_SPACING = _dereq_('../../constants/alignment').LINE_SPACING;
  42939. var axes = module.exports = {};
  42940. axes.setConvert = _dereq_('./set_convert');
  42941. var autoType = _dereq_('./axis_autotype');
  42942. var axisIds = _dereq_('./axis_ids');
  42943. axes.id2name = axisIds.id2name;
  42944. axes.name2id = axisIds.name2id;
  42945. axes.cleanId = axisIds.cleanId;
  42946. axes.list = axisIds.list;
  42947. axes.listIds = axisIds.listIds;
  42948. axes.getFromId = axisIds.getFromId;
  42949. axes.getFromTrace = axisIds.getFromTrace;
  42950. var autorange = _dereq_('./autorange');
  42951. axes.getAutoRange = autorange.getAutoRange;
  42952. axes.findExtremes = autorange.findExtremes;
  42953. /*
  42954. * find the list of possible axes to reference with an xref or yref attribute
  42955. * and coerce it to that list
  42956. *
  42957. * attr: the attribute we're generating a reference for. Should end in 'x' or 'y'
  42958. * but can be prefixed, like 'ax' for annotation's arrow x
  42959. * dflt: the default to coerce to, or blank to use the first axis (falling back on
  42960. * extraOption if there is no axis)
  42961. * extraOption: aside from existing axes with this letter, what non-axis value is allowed?
  42962. * Only required if it's different from `dflt`
  42963. */
  42964. axes.coerceRef = function(containerIn, containerOut, gd, attr, dflt, extraOption) {
  42965. var axLetter = attr.charAt(attr.length - 1);
  42966. var axlist = gd._fullLayout._subplots[axLetter + 'axis'];
  42967. var refAttr = attr + 'ref';
  42968. var attrDef = {};
  42969. if(!dflt) dflt = axlist[0] || extraOption;
  42970. if(!extraOption) extraOption = dflt;
  42971. // data-ref annotations are not supported in gl2d yet
  42972. attrDef[refAttr] = {
  42973. valType: 'enumerated',
  42974. values: axlist.concat(extraOption ? [extraOption] : []),
  42975. dflt: dflt
  42976. };
  42977. // xref, yref
  42978. return Lib.coerce(containerIn, containerOut, attrDef, refAttr);
  42979. };
  42980. /*
  42981. * coerce position attributes (range-type) that can be either on axes or absolute
  42982. * (paper or pixel) referenced. The biggest complication here is that we don't know
  42983. * before looking at the axis whether the value must be a number or not (it may be
  42984. * a date string), so we can't use the regular valType='number' machinery
  42985. *
  42986. * axRef (string): the axis this position is referenced to, or:
  42987. * paper: fraction of the plot area
  42988. * pixel: pixels relative to some starting position
  42989. * attr (string): the attribute in containerOut we are coercing
  42990. * dflt (number): the default position, as a fraction or pixels. If the attribute
  42991. * is to be axis-referenced, this will be converted to an axis data value
  42992. *
  42993. * Also cleans the values, since the attribute definition itself has to say
  42994. * valType: 'any' to handle date axes. This allows us to accept:
  42995. * - for category axes: category names, and convert them here into serial numbers.
  42996. * Note that this will NOT work for axis range endpoints, because we don't know
  42997. * the category list yet (it's set by ax.makeCalcdata during calc)
  42998. * but it works for component (note, shape, images) positions.
  42999. * - for date axes: JS Dates or milliseconds, and convert to date strings
  43000. * - for other types: coerce them to numbers
  43001. */
  43002. axes.coercePosition = function(containerOut, gd, coerce, axRef, attr, dflt) {
  43003. var cleanPos, pos;
  43004. if(axRef === 'paper' || axRef === 'pixel') {
  43005. cleanPos = Lib.ensureNumber;
  43006. pos = coerce(attr, dflt);
  43007. } else {
  43008. var ax = axes.getFromId(gd, axRef);
  43009. dflt = ax.fraction2r(dflt);
  43010. pos = coerce(attr, dflt);
  43011. cleanPos = ax.cleanPos;
  43012. }
  43013. containerOut[attr] = cleanPos(pos);
  43014. };
  43015. axes.cleanPosition = function(pos, gd, axRef) {
  43016. var cleanPos = (axRef === 'paper' || axRef === 'pixel') ?
  43017. Lib.ensureNumber :
  43018. axes.getFromId(gd, axRef).cleanPos;
  43019. return cleanPos(pos);
  43020. };
  43021. axes.redrawComponents = function(gd, axIds) {
  43022. axIds = axIds ? axIds : axes.listIds(gd);
  43023. var fullLayout = gd._fullLayout;
  43024. function _redrawOneComp(moduleName, methodName, stashName, shortCircuit) {
  43025. var method = Registry.getComponentMethod(moduleName, methodName);
  43026. var stash = {};
  43027. for(var i = 0; i < axIds.length; i++) {
  43028. var ax = fullLayout[axes.id2name(axIds[i])];
  43029. var indices = ax[stashName];
  43030. for(var j = 0; j < indices.length; j++) {
  43031. var ind = indices[j];
  43032. if(!stash[ind]) {
  43033. method(gd, ind);
  43034. stash[ind] = 1;
  43035. // once is enough for images (which doesn't use the `i` arg anyway)
  43036. if(shortCircuit) return;
  43037. }
  43038. }
  43039. }
  43040. }
  43041. // annotations and shapes 'draw' method is slow,
  43042. // use the finer-grained 'drawOne' method instead
  43043. _redrawOneComp('annotations', 'drawOne', '_annIndices');
  43044. _redrawOneComp('shapes', 'drawOne', '_shapeIndices');
  43045. _redrawOneComp('images', 'draw', '_imgIndices', true);
  43046. };
  43047. var getDataConversions = axes.getDataConversions = function(gd, trace, target, targetArray) {
  43048. var ax;
  43049. // If target points to an axis, use the type we already have for that
  43050. // axis to find the data type. Otherwise use the values to autotype.
  43051. var d2cTarget = (target === 'x' || target === 'y' || target === 'z') ?
  43052. target :
  43053. targetArray;
  43054. // In the case of an array target, make a mock data array
  43055. // and call supplyDefaults to the data type and
  43056. // setup the data-to-calc method.
  43057. if(Array.isArray(d2cTarget)) {
  43058. ax = {
  43059. type: autoType(targetArray),
  43060. _categories: []
  43061. };
  43062. axes.setConvert(ax);
  43063. // build up ax._categories (usually done during ax.makeCalcdata()
  43064. if(ax.type === 'category') {
  43065. for(var i = 0; i < targetArray.length; i++) {
  43066. ax.d2c(targetArray[i]);
  43067. }
  43068. }
  43069. // TODO what to do for transforms?
  43070. } else {
  43071. ax = axes.getFromTrace(gd, trace, d2cTarget);
  43072. }
  43073. // if 'target' has corresponding axis
  43074. // -> use setConvert method
  43075. if(ax) return {d2c: ax.d2c, c2d: ax.c2d};
  43076. // special case for 'ids'
  43077. // -> cast to String
  43078. if(d2cTarget === 'ids') return {d2c: toString, c2d: toString};
  43079. // otherwise (e.g. numeric-array of 'marker.color' or 'marker.size')
  43080. // -> cast to Number
  43081. return {d2c: toNum, c2d: toNum};
  43082. };
  43083. function toNum(v) { return +v; }
  43084. function toString(v) { return String(v); }
  43085. axes.getDataToCoordFunc = function(gd, trace, target, targetArray) {
  43086. return getDataConversions(gd, trace, target, targetArray).d2c;
  43087. };
  43088. // get counteraxis letter for this axis (name or id)
  43089. // this can also be used as the id for default counter axis
  43090. axes.counterLetter = function(id) {
  43091. var axLetter = id.charAt(0);
  43092. if(axLetter === 'x') return 'y';
  43093. if(axLetter === 'y') return 'x';
  43094. };
  43095. // incorporate a new minimum difference and first tick into
  43096. // forced
  43097. // note that _forceTick0 is linearized, so needs to be turned into
  43098. // a range value for setting tick0
  43099. axes.minDtick = function(ax, newDiff, newFirst, allow) {
  43100. // doesn't make sense to do forced min dTick on log or category axes,
  43101. // and the plot itself may decide to cancel (ie non-grouped bars)
  43102. if(['log', 'category', 'multicategory'].indexOf(ax.type) !== -1 || !allow) {
  43103. ax._minDtick = 0;
  43104. }
  43105. // undefined means there's nothing there yet
  43106. else if(ax._minDtick === undefined) {
  43107. ax._minDtick = newDiff;
  43108. ax._forceTick0 = newFirst;
  43109. }
  43110. else if(ax._minDtick) {
  43111. // existing minDtick is an integer multiple of newDiff
  43112. // (within rounding err)
  43113. // and forceTick0 can be shifted to newFirst
  43114. if((ax._minDtick / newDiff + 1e-6) % 1 < 2e-6 &&
  43115. (((newFirst - ax._forceTick0) / newDiff % 1) +
  43116. 1.000001) % 1 < 2e-6) {
  43117. ax._minDtick = newDiff;
  43118. ax._forceTick0 = newFirst;
  43119. }
  43120. // if the converse is true (newDiff is a multiple of minDtick and
  43121. // newFirst can be shifted to forceTick0) then do nothing - same
  43122. // forcing stands. Otherwise, cancel forced minimum
  43123. else if((newDiff / ax._minDtick + 1e-6) % 1 > 2e-6 ||
  43124. (((newFirst - ax._forceTick0) / ax._minDtick % 1) +
  43125. 1.000001) % 1 > 2e-6) {
  43126. ax._minDtick = 0;
  43127. }
  43128. }
  43129. };
  43130. // save a copy of the initial axis ranges in fullLayout
  43131. // use them in mode bar and dblclick events
  43132. axes.saveRangeInitial = function(gd, overwrite) {
  43133. var axList = axes.list(gd, '', true);
  43134. var hasOneAxisChanged = false;
  43135. for(var i = 0; i < axList.length; i++) {
  43136. var ax = axList[i];
  43137. var isNew = (ax._rangeInitial === undefined);
  43138. var hasChanged = isNew || !(
  43139. ax.range[0] === ax._rangeInitial[0] &&
  43140. ax.range[1] === ax._rangeInitial[1]
  43141. );
  43142. if((isNew && ax.autorange === false) || (overwrite && hasChanged)) {
  43143. ax._rangeInitial = ax.range.slice();
  43144. hasOneAxisChanged = true;
  43145. }
  43146. }
  43147. return hasOneAxisChanged;
  43148. };
  43149. // save a copy of the initial spike visibility
  43150. axes.saveShowSpikeInitial = function(gd, overwrite) {
  43151. var axList = axes.list(gd, '', true);
  43152. var hasOneAxisChanged = false;
  43153. var allSpikesEnabled = 'on';
  43154. for(var i = 0; i < axList.length; i++) {
  43155. var ax = axList[i];
  43156. var isNew = (ax._showSpikeInitial === undefined);
  43157. var hasChanged = isNew || !(ax.showspikes === ax._showspikes);
  43158. if(isNew || (overwrite && hasChanged)) {
  43159. ax._showSpikeInitial = ax.showspikes;
  43160. hasOneAxisChanged = true;
  43161. }
  43162. if(allSpikesEnabled === 'on' && !ax.showspikes) {
  43163. allSpikesEnabled = 'off';
  43164. }
  43165. }
  43166. gd._fullLayout._cartesianSpikesEnabled = allSpikesEnabled;
  43167. return hasOneAxisChanged;
  43168. };
  43169. axes.autoBin = function(data, ax, nbins, is2d, calendar, size) {
  43170. var dataMin = Lib.aggNums(Math.min, null, data);
  43171. var dataMax = Lib.aggNums(Math.max, null, data);
  43172. if(ax.type === 'category' || ax.type === 'multicategory') {
  43173. return {
  43174. start: dataMin - 0.5,
  43175. end: dataMax + 0.5,
  43176. size: Math.max(1, Math.round(size) || 1),
  43177. _dataSpan: dataMax - dataMin,
  43178. };
  43179. }
  43180. if(!calendar) calendar = ax.calendar;
  43181. // piggyback off tick code to make "nice" bin sizes and edges
  43182. var dummyAx;
  43183. if(ax.type === 'log') {
  43184. dummyAx = {
  43185. type: 'linear',
  43186. range: [dataMin, dataMax]
  43187. };
  43188. } else {
  43189. dummyAx = {
  43190. type: ax.type,
  43191. range: Lib.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar),
  43192. calendar: calendar
  43193. };
  43194. }
  43195. axes.setConvert(dummyAx);
  43196. size = size && cleanTicks.dtick(size, dummyAx.type);
  43197. if(size) {
  43198. dummyAx.dtick = size;
  43199. dummyAx.tick0 = cleanTicks.tick0(undefined, dummyAx.type, calendar);
  43200. }
  43201. else {
  43202. var size0;
  43203. if(nbins) size0 = ((dataMax - dataMin) / nbins);
  43204. else {
  43205. // totally auto: scale off std deviation so the highest bin is
  43206. // somewhat taller than the total number of bins, but don't let
  43207. // the size get smaller than the 'nice' rounded down minimum
  43208. // difference between values
  43209. var distinctData = Lib.distinctVals(data);
  43210. var msexp = Math.pow(10, Math.floor(
  43211. Math.log(distinctData.minDiff) / Math.LN10));
  43212. var minSize = msexp * Lib.roundUp(
  43213. distinctData.minDiff / msexp, [0.9, 1.9, 4.9, 9.9], true);
  43214. size0 = Math.max(minSize, 2 * Lib.stdev(data) /
  43215. Math.pow(data.length, is2d ? 0.25 : 0.4));
  43216. // fallback if ax.d2c output BADNUMs
  43217. // e.g. when user try to plot categorical bins
  43218. // on a layout.xaxis.type: 'linear'
  43219. if(!isNumeric(size0)) size0 = 1;
  43220. }
  43221. axes.autoTicks(dummyAx, size0);
  43222. }
  43223. var finalSize = dummyAx.dtick;
  43224. var binStart = axes.tickIncrement(
  43225. axes.tickFirst(dummyAx), finalSize, 'reverse', calendar);
  43226. var binEnd, bincount;
  43227. // check for too many data points right at the edges of bins
  43228. // (>50% within 1% of bin edges) or all data points integral
  43229. // and offset the bins accordingly
  43230. if(typeof finalSize === 'number') {
  43231. binStart = autoShiftNumericBins(binStart, data, dummyAx, dataMin, dataMax);
  43232. bincount = 1 + Math.floor((dataMax - binStart) / finalSize);
  43233. binEnd = binStart + bincount * finalSize;
  43234. }
  43235. else {
  43236. // month ticks - should be the only nonlinear kind we have at this point.
  43237. // dtick (as supplied by axes.autoTick) only has nonlinear values on
  43238. // date and log axes, but even if you display a histogram on a log axis
  43239. // we bin it on a linear axis (which one could argue against, but that's
  43240. // a separate issue)
  43241. if(dummyAx.dtick.charAt(0) === 'M') {
  43242. binStart = autoShiftMonthBins(binStart, data, finalSize, dataMin, calendar);
  43243. }
  43244. // calculate the endpoint for nonlinear ticks - you have to
  43245. // just increment until you're done
  43246. binEnd = binStart;
  43247. bincount = 0;
  43248. while(binEnd <= dataMax) {
  43249. binEnd = axes.tickIncrement(binEnd, finalSize, false, calendar);
  43250. bincount++;
  43251. }
  43252. }
  43253. return {
  43254. start: ax.c2r(binStart, 0, calendar),
  43255. end: ax.c2r(binEnd, 0, calendar),
  43256. size: finalSize,
  43257. _dataSpan: dataMax - dataMin
  43258. };
  43259. };
  43260. function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) {
  43261. var edgecount = 0;
  43262. var midcount = 0;
  43263. var intcount = 0;
  43264. var blankCount = 0;
  43265. function nearEdge(v) {
  43266. // is a value within 1% of a bin edge?
  43267. return (1 + (v - binStart) * 100 / ax.dtick) % 100 < 2;
  43268. }
  43269. for(var i = 0; i < data.length; i++) {
  43270. if(data[i] % 1 === 0) intcount++;
  43271. else if(!isNumeric(data[i])) blankCount++;
  43272. if(nearEdge(data[i])) edgecount++;
  43273. if(nearEdge(data[i] + ax.dtick / 2)) midcount++;
  43274. }
  43275. var dataCount = data.length - blankCount;
  43276. if(intcount === dataCount && ax.type !== 'date') {
  43277. // all integers: if bin size is <1, it's because
  43278. // that was specifically requested (large nbins)
  43279. // so respect that... but center the bins containing
  43280. // integers on those integers
  43281. if(ax.dtick < 1) {
  43282. binStart = dataMin - 0.5 * ax.dtick;
  43283. }
  43284. // otherwise start half an integer down regardless of
  43285. // the bin size, just enough to clear up endpoint
  43286. // ambiguity about which integers are in which bins.
  43287. else {
  43288. binStart -= 0.5;
  43289. if(binStart + ax.dtick < dataMin) binStart += ax.dtick;
  43290. }
  43291. }
  43292. else if(midcount < dataCount * 0.1) {
  43293. if(edgecount > dataCount * 0.3 ||
  43294. nearEdge(dataMin) || nearEdge(dataMax)) {
  43295. // lots of points at the edge, not many in the middle
  43296. // shift half a bin
  43297. var binshift = ax.dtick / 2;
  43298. binStart += (binStart + binshift < dataMin) ? binshift : -binshift;
  43299. }
  43300. }
  43301. return binStart;
  43302. }
  43303. function autoShiftMonthBins(binStart, data, dtick, dataMin, calendar) {
  43304. var stats = Lib.findExactDates(data, calendar);
  43305. // number of data points that needs to be an exact value
  43306. // to shift that increment to (near) the bin center
  43307. var threshold = 0.8;
  43308. if(stats.exactDays > threshold) {
  43309. var numMonths = Number(dtick.substr(1));
  43310. if((stats.exactYears > threshold) && (numMonths % 12 === 0)) {
  43311. // The exact middle of a non-leap-year is 1.5 days into July
  43312. // so if we start the bins here, all but leap years will
  43313. // get hover-labeled as exact years.
  43314. binStart = axes.tickIncrement(binStart, 'M6', 'reverse') + ONEDAY * 1.5;
  43315. }
  43316. else if(stats.exactMonths > threshold) {
  43317. // Months are not as clean, but if we shift half the *longest*
  43318. // month (31/2 days) then 31-day months will get labeled exactly
  43319. // and shorter months will get labeled with the correct month
  43320. // but shifted 12-36 hours into it.
  43321. binStart = axes.tickIncrement(binStart, 'M1', 'reverse') + ONEDAY * 15.5;
  43322. }
  43323. else {
  43324. // Shifting half a day is exact, but since these are month bins it
  43325. // will always give a somewhat odd-looking label, until we do something
  43326. // smarter like showing the bin boundaries (or the bounds of the actual
  43327. // data in each bin)
  43328. binStart -= ONEDAY / 2;
  43329. }
  43330. var nextBinStart = axes.tickIncrement(binStart, dtick);
  43331. if(nextBinStart <= dataMin) return nextBinStart;
  43332. }
  43333. return binStart;
  43334. }
  43335. // ----------------------------------------------------
  43336. // Ticks and grids
  43337. // ----------------------------------------------------
  43338. // ensure we have tick0, dtick, and tick rounding calculated
  43339. axes.prepTicks = function(ax) {
  43340. var rng = Lib.simpleMap(ax.range, ax.r2l);
  43341. // calculate max number of (auto) ticks to display based on plot size
  43342. if(ax.tickmode === 'auto' || !ax.dtick) {
  43343. var nt = ax.nticks;
  43344. var minPx;
  43345. if(!nt) {
  43346. if(ax.type === 'category' || ax.type === 'multicategory') {
  43347. minPx = ax.tickfont ? (ax.tickfont.size || 12) * 1.2 : 15;
  43348. nt = ax._length / minPx;
  43349. } else {
  43350. minPx = ax._id.charAt(0) === 'y' ? 40 : 80;
  43351. nt = Lib.constrain(ax._length / minPx, 4, 9) + 1;
  43352. }
  43353. // radial axes span half their domain,
  43354. // multiply nticks value by two to get correct number of auto ticks.
  43355. if(ax._name === 'radialaxis') nt *= 2;
  43356. }
  43357. // add a couple of extra digits for filling in ticks when we
  43358. // have explicit tickvals without tick text
  43359. if(ax.tickmode === 'array') nt *= 100;
  43360. axes.autoTicks(ax, Math.abs(rng[1] - rng[0]) / nt);
  43361. // check for a forced minimum dtick
  43362. if(ax._minDtick > 0 && ax.dtick < ax._minDtick * 2) {
  43363. ax.dtick = ax._minDtick;
  43364. ax.tick0 = ax.l2r(ax._forceTick0);
  43365. }
  43366. }
  43367. // check for missing tick0
  43368. if(!ax.tick0) {
  43369. ax.tick0 = (ax.type === 'date') ? '2000-01-01' : 0;
  43370. }
  43371. // ensure we don't try to make ticks below our minimum precision
  43372. // see https://github.com/plotly/plotly.js/issues/2892
  43373. if(ax.type === 'date' && ax.dtick < 0.1) ax.dtick = 0.1;
  43374. // now figure out rounding of tick values
  43375. autoTickRound(ax);
  43376. };
  43377. // calculate the ticks: text, values, positioning
  43378. // if ticks are set to automatic, determine the right values (tick0,dtick)
  43379. // in any case, set tickround to # of digits to round tick labels to,
  43380. // or codes to this effect for log and date scales
  43381. axes.calcTicks = function calcTicks(ax) {
  43382. axes.prepTicks(ax);
  43383. var rng = Lib.simpleMap(ax.range, ax.r2l);
  43384. // now that we've figured out the auto values for formatting
  43385. // in case we're missing some ticktext, we can break out for array ticks
  43386. if(ax.tickmode === 'array') return arrayTicks(ax);
  43387. // find the first tick
  43388. ax._tmin = axes.tickFirst(ax);
  43389. // add a tiny bit so we get ticks which may have rounded out
  43390. var startTick = rng[0] * 1.0001 - rng[1] * 0.0001;
  43391. var endTick = rng[1] * 1.0001 - rng[0] * 0.0001;
  43392. // check for reversed axis
  43393. var axrev = (rng[1] < rng[0]);
  43394. // No visible ticks? Quit.
  43395. // I've only seen this on category axes with all categories off the edge.
  43396. if((ax._tmin < startTick) !== axrev) return [];
  43397. // return the full set of tick vals
  43398. var vals = [];
  43399. if(ax.type === 'category' || ax.type === 'multicategory') {
  43400. endTick = (axrev) ? Math.max(-0.5, endTick) :
  43401. Math.min(ax._categories.length - 0.5, endTick);
  43402. }
  43403. var xPrevious = null;
  43404. var maxTicks = Math.max(1000, ax._length || 0);
  43405. for(var x = ax._tmin;
  43406. (axrev) ? (x >= endTick) : (x <= endTick);
  43407. x = axes.tickIncrement(x, ax.dtick, axrev, ax.calendar)) {
  43408. // prevent infinite loops - no more than one tick per pixel,
  43409. // and make sure each value is different from the previous
  43410. if(vals.length > maxTicks || x === xPrevious) break;
  43411. xPrevious = x;
  43412. vals.push(x);
  43413. }
  43414. // If same angle over a full circle, the last tick vals is a duplicate.
  43415. // TODO must do something similar for angular date axes.
  43416. if(isAngular(ax) && Math.abs(rng[1] - rng[0]) === 360) {
  43417. vals.pop();
  43418. }
  43419. // save the last tick as well as first, so we can
  43420. // show the exponent only on the last one
  43421. ax._tmax = vals[vals.length - 1];
  43422. // for showing the rest of a date when the main tick label is only the
  43423. // latter part: ax._prevDateHead holds what we showed most recently.
  43424. // Start with it cleared and mark that we're in calcTicks (ie calculating a
  43425. // whole string of these so we should care what the previous date head was!)
  43426. ax._prevDateHead = '';
  43427. ax._inCalcTicks = true;
  43428. var ticksOut = new Array(vals.length);
  43429. for(var i = 0; i < vals.length; i++) ticksOut[i] = axes.tickText(ax, vals[i]);
  43430. ax._inCalcTicks = false;
  43431. return ticksOut;
  43432. };
  43433. function arrayTicks(ax) {
  43434. var vals = ax.tickvals;
  43435. var text = ax.ticktext;
  43436. var ticksOut = new Array(vals.length);
  43437. var rng = Lib.simpleMap(ax.range, ax.r2l);
  43438. var r0expanded = rng[0] * 1.0001 - rng[1] * 0.0001;
  43439. var r1expanded = rng[1] * 1.0001 - rng[0] * 0.0001;
  43440. var tickMin = Math.min(r0expanded, r1expanded);
  43441. var tickMax = Math.max(r0expanded, r1expanded);
  43442. var j = 0;
  43443. // without a text array, just format the given values as any other ticks
  43444. // except with more precision to the numbers
  43445. if(!Array.isArray(text)) text = [];
  43446. // make sure showing ticks doesn't accidentally add new categories
  43447. // TODO multicategory, if we allow ticktext / tickvals
  43448. var tickVal2l = ax.type === 'category' ? ax.d2l_noadd : ax.d2l;
  43449. // array ticks on log axes always show the full number
  43450. // (if no explicit ticktext overrides it)
  43451. if(ax.type === 'log' && String(ax.dtick).charAt(0) !== 'L') {
  43452. ax.dtick = 'L' + Math.pow(10, Math.floor(Math.min(ax.range[0], ax.range[1])) - 1);
  43453. }
  43454. for(var i = 0; i < vals.length; i++) {
  43455. var vali = tickVal2l(vals[i]);
  43456. if(vali > tickMin && vali < tickMax) {
  43457. if(text[i] === undefined) ticksOut[j] = axes.tickText(ax, vali);
  43458. else ticksOut[j] = tickTextObj(ax, vali, String(text[i]));
  43459. j++;
  43460. }
  43461. }
  43462. if(j < vals.length) ticksOut.splice(j, vals.length - j);
  43463. return ticksOut;
  43464. }
  43465. var roundBase10 = [2, 5, 10];
  43466. var roundBase24 = [1, 2, 3, 6, 12];
  43467. var roundBase60 = [1, 2, 5, 10, 15, 30];
  43468. // 2&3 day ticks are weird, but need something btwn 1&7
  43469. var roundDays = [1, 2, 3, 7, 14];
  43470. // approx. tick positions for log axes, showing all (1) and just 1, 2, 5 (2)
  43471. // these don't have to be exact, just close enough to round to the right value
  43472. var roundLog1 = [-0.046, 0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1];
  43473. var roundLog2 = [-0.301, 0, 0.301, 0.699, 1];
  43474. // N.B. `thetaunit; 'radians' angular axes must be converted to degrees
  43475. var roundAngles = [15, 30, 45, 90, 180];
  43476. function roundDTick(roughDTick, base, roundingSet) {
  43477. return base * Lib.roundUp(roughDTick / base, roundingSet);
  43478. }
  43479. // autoTicks: calculate best guess at pleasant ticks for this axis
  43480. // inputs:
  43481. // ax - an axis object
  43482. // roughDTick - rough tick spacing (to be turned into a nice round number)
  43483. // outputs (into ax):
  43484. // tick0: starting point for ticks (not necessarily on the graph)
  43485. // usually 0 for numeric (=10^0=1 for log) or jan 1, 2000 for dates
  43486. // dtick: the actual, nice round tick spacing, usually a little larger than roughDTick
  43487. // if the ticks are spaced linearly (linear scale, categories,
  43488. // log with only full powers, date ticks < month),
  43489. // this will just be a number
  43490. // months: M#
  43491. // years: M# where # is 12*number of years
  43492. // log with linear ticks: L# where # is the linear tick spacing
  43493. // log showing powers plus some intermediates:
  43494. // D1 shows all digits, D2 shows 2 and 5
  43495. axes.autoTicks = function(ax, roughDTick) {
  43496. var base;
  43497. function getBase(v) {
  43498. return Math.pow(v, Math.floor(Math.log(roughDTick) / Math.LN10));
  43499. }
  43500. if(ax.type === 'date') {
  43501. ax.tick0 = Lib.dateTick0(ax.calendar);
  43502. // the criteria below are all based on the rough spacing we calculate
  43503. // being > half of the final unit - so precalculate twice the rough val
  43504. var roughX2 = 2 * roughDTick;
  43505. if(roughX2 > ONEAVGYEAR) {
  43506. roughDTick /= ONEAVGYEAR;
  43507. base = getBase(10);
  43508. ax.dtick = 'M' + (12 * roundDTick(roughDTick, base, roundBase10));
  43509. }
  43510. else if(roughX2 > ONEAVGMONTH) {
  43511. roughDTick /= ONEAVGMONTH;
  43512. ax.dtick = 'M' + roundDTick(roughDTick, 1, roundBase24);
  43513. }
  43514. else if(roughX2 > ONEDAY) {
  43515. ax.dtick = roundDTick(roughDTick, ONEDAY, roundDays);
  43516. // get week ticks on sunday
  43517. // this will also move the base tick off 2000-01-01 if dtick is
  43518. // 2 or 3 days... but that's a weird enough case that we'll ignore it.
  43519. ax.tick0 = Lib.dateTick0(ax.calendar, true);
  43520. }
  43521. else if(roughX2 > ONEHOUR) {
  43522. ax.dtick = roundDTick(roughDTick, ONEHOUR, roundBase24);
  43523. }
  43524. else if(roughX2 > ONEMIN) {
  43525. ax.dtick = roundDTick(roughDTick, ONEMIN, roundBase60);
  43526. }
  43527. else if(roughX2 > ONESEC) {
  43528. ax.dtick = roundDTick(roughDTick, ONESEC, roundBase60);
  43529. }
  43530. else {
  43531. // milliseconds
  43532. base = getBase(10);
  43533. ax.dtick = roundDTick(roughDTick, base, roundBase10);
  43534. }
  43535. }
  43536. else if(ax.type === 'log') {
  43537. ax.tick0 = 0;
  43538. var rng = Lib.simpleMap(ax.range, ax.r2l);
  43539. if(roughDTick > 0.7) {
  43540. // only show powers of 10
  43541. ax.dtick = Math.ceil(roughDTick);
  43542. }
  43543. else if(Math.abs(rng[1] - rng[0]) < 1) {
  43544. // span is less than one power of 10
  43545. var nt = 1.5 * Math.abs((rng[1] - rng[0]) / roughDTick);
  43546. // ticks on a linear scale, labeled fully
  43547. roughDTick = Math.abs(Math.pow(10, rng[1]) -
  43548. Math.pow(10, rng[0])) / nt;
  43549. base = getBase(10);
  43550. ax.dtick = 'L' + roundDTick(roughDTick, base, roundBase10);
  43551. }
  43552. else {
  43553. // include intermediates between powers of 10,
  43554. // labeled with small digits
  43555. // ax.dtick = "D2" (show 2 and 5) or "D1" (show all digits)
  43556. ax.dtick = (roughDTick > 0.3) ? 'D2' : 'D1';
  43557. }
  43558. }
  43559. else if(ax.type === 'category' || ax.type === 'multicategory') {
  43560. ax.tick0 = 0;
  43561. ax.dtick = Math.ceil(Math.max(roughDTick, 1));
  43562. }
  43563. else if(isAngular(ax)) {
  43564. ax.tick0 = 0;
  43565. base = 1;
  43566. ax.dtick = roundDTick(roughDTick, base, roundAngles);
  43567. }
  43568. else {
  43569. // auto ticks always start at 0
  43570. ax.tick0 = 0;
  43571. base = getBase(10);
  43572. ax.dtick = roundDTick(roughDTick, base, roundBase10);
  43573. }
  43574. // prevent infinite loops
  43575. if(ax.dtick === 0) ax.dtick = 1;
  43576. // TODO: this is from log axis histograms with autorange off
  43577. if(!isNumeric(ax.dtick) && typeof ax.dtick !== 'string') {
  43578. var olddtick = ax.dtick;
  43579. ax.dtick = 1;
  43580. throw 'ax.dtick error: ' + String(olddtick);
  43581. }
  43582. };
  43583. // after dtick is already known, find tickround = precision
  43584. // to display in tick labels
  43585. // for numeric ticks, integer # digits after . to round to
  43586. // for date ticks, the last date part to show (y,m,d,H,M,S)
  43587. // or an integer # digits past seconds
  43588. function autoTickRound(ax) {
  43589. var dtick = ax.dtick;
  43590. ax._tickexponent = 0;
  43591. if(!isNumeric(dtick) && typeof dtick !== 'string') {
  43592. dtick = 1;
  43593. }
  43594. if(ax.type === 'category' || ax.type === 'multicategory') {
  43595. ax._tickround = null;
  43596. }
  43597. if(ax.type === 'date') {
  43598. // If tick0 is unusual, give tickround a bit more information
  43599. // not necessarily *all* the information in tick0 though, if it's really odd
  43600. // minimal string length for tick0: 'd' is 10, 'M' is 16, 'S' is 19
  43601. // take off a leading minus (year < 0) and i (intercalary month) so length is consistent
  43602. var tick0ms = ax.r2l(ax.tick0);
  43603. var tick0str = ax.l2r(tick0ms).replace(/(^-|i)/g, '');
  43604. var tick0len = tick0str.length;
  43605. if(String(dtick).charAt(0) === 'M') {
  43606. // any tick0 more specific than a year: alway show the full date
  43607. if(tick0len > 10 || tick0str.substr(5) !== '01-01') ax._tickround = 'd';
  43608. // show the month unless ticks are full multiples of a year
  43609. else ax._tickround = (+(dtick.substr(1)) % 12 === 0) ? 'y' : 'm';
  43610. }
  43611. else if((dtick >= ONEDAY && tick0len <= 10) || (dtick >= ONEDAY * 15)) ax._tickround = 'd';
  43612. else if((dtick >= ONEMIN && tick0len <= 16) || (dtick >= ONEHOUR)) ax._tickround = 'M';
  43613. else if((dtick >= ONESEC && tick0len <= 19) || (dtick >= ONEMIN)) ax._tickround = 'S';
  43614. else {
  43615. // tickround is a number of digits of fractional seconds
  43616. // of any two adjacent ticks, at least one will have the maximum fractional digits
  43617. // of all possible ticks - so take the max. length of tick0 and the next one
  43618. var tick1len = ax.l2r(tick0ms + dtick).replace(/^-/, '').length;
  43619. ax._tickround = Math.max(tick0len, tick1len) - 20;
  43620. // We shouldn't get here... but in case there's a situation I'm
  43621. // not thinking of where tick0str and tick1str are identical or
  43622. // something, fall back on maximum precision
  43623. if(ax._tickround < 0) ax._tickround = 4;
  43624. }
  43625. }
  43626. else if(isNumeric(dtick) || dtick.charAt(0) === 'L') {
  43627. // linear or log (except D1, D2)
  43628. var rng = ax.range.map(ax.r2d || Number);
  43629. if(!isNumeric(dtick)) dtick = Number(dtick.substr(1));
  43630. // 2 digits past largest digit of dtick
  43631. ax._tickround = 2 - Math.floor(Math.log(dtick) / Math.LN10 + 0.01);
  43632. var maxend = Math.max(Math.abs(rng[0]), Math.abs(rng[1]));
  43633. var rangeexp = Math.floor(Math.log(maxend) / Math.LN10 + 0.01);
  43634. if(Math.abs(rangeexp) > 3) {
  43635. if(isSIFormat(ax.exponentformat) && !beyondSI(rangeexp)) {
  43636. ax._tickexponent = 3 * Math.round((rangeexp - 1) / 3);
  43637. }
  43638. else ax._tickexponent = rangeexp;
  43639. }
  43640. }
  43641. // D1 or D2 (log)
  43642. else ax._tickround = null;
  43643. }
  43644. // months and years don't have constant millisecond values
  43645. // (but a year is always 12 months so we only need months)
  43646. // log-scale ticks are also not consistently spaced, except
  43647. // for pure powers of 10
  43648. // numeric ticks always have constant differences, other datetime ticks
  43649. // can all be calculated as constant number of milliseconds
  43650. axes.tickIncrement = function(x, dtick, axrev, calendar) {
  43651. var axSign = axrev ? -1 : 1;
  43652. // includes linear, all dates smaller than month, and pure 10^n in log
  43653. if(isNumeric(dtick)) return x + axSign * dtick;
  43654. // everything else is a string, one character plus a number
  43655. var tType = dtick.charAt(0);
  43656. var dtSigned = axSign * Number(dtick.substr(1));
  43657. // Dates: months (or years - see Lib.incrementMonth)
  43658. if(tType === 'M') return Lib.incrementMonth(x, dtSigned, calendar);
  43659. // Log scales: Linear, Digits
  43660. else if(tType === 'L') return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10;
  43661. // log10 of 2,5,10, or all digits (logs just have to be
  43662. // close enough to round)
  43663. else if(tType === 'D') {
  43664. var tickset = (dtick === 'D2') ? roundLog2 : roundLog1;
  43665. var x2 = x + axSign * 0.01;
  43666. var frac = Lib.roundUp(Lib.mod(x2, 1), tickset, axrev);
  43667. return Math.floor(x2) +
  43668. Math.log(d3.round(Math.pow(10, frac), 1)) / Math.LN10;
  43669. }
  43670. else throw 'unrecognized dtick ' + String(dtick);
  43671. };
  43672. // calculate the first tick on an axis
  43673. axes.tickFirst = function(ax) {
  43674. var r2l = ax.r2l || Number;
  43675. var rng = Lib.simpleMap(ax.range, r2l);
  43676. var axrev = rng[1] < rng[0];
  43677. var sRound = axrev ? Math.floor : Math.ceil;
  43678. // add a tiny extra bit to make sure we get ticks
  43679. // that may have been rounded out
  43680. var r0 = rng[0] * 1.0001 - rng[1] * 0.0001;
  43681. var dtick = ax.dtick;
  43682. var tick0 = r2l(ax.tick0);
  43683. if(isNumeric(dtick)) {
  43684. var tmin = sRound((r0 - tick0) / dtick) * dtick + tick0;
  43685. // make sure no ticks outside the category list
  43686. if(ax.type === 'category' || ax.type === 'multicategory') {
  43687. tmin = Lib.constrain(tmin, 0, ax._categories.length - 1);
  43688. }
  43689. return tmin;
  43690. }
  43691. var tType = dtick.charAt(0);
  43692. var dtNum = Number(dtick.substr(1));
  43693. // Dates: months (or years)
  43694. if(tType === 'M') {
  43695. var cnt = 0;
  43696. var t0 = tick0;
  43697. var t1, mult, newDTick;
  43698. // This algorithm should work for *any* nonlinear (but close to linear!)
  43699. // tick spacing. Limit to 10 iterations, for gregorian months it's normally <=3.
  43700. while(cnt < 10) {
  43701. t1 = axes.tickIncrement(t0, dtick, axrev, ax.calendar);
  43702. if((t1 - r0) * (t0 - r0) <= 0) {
  43703. // t1 and t0 are on opposite sides of r0! we've succeeded!
  43704. if(axrev) return Math.min(t0, t1);
  43705. return Math.max(t0, t1);
  43706. }
  43707. mult = (r0 - ((t0 + t1) / 2)) / (t1 - t0);
  43708. newDTick = tType + ((Math.abs(Math.round(mult)) || 1) * dtNum);
  43709. t0 = axes.tickIncrement(t0, newDTick, mult < 0 ? !axrev : axrev, ax.calendar);
  43710. cnt++;
  43711. }
  43712. Lib.error('tickFirst did not converge', ax);
  43713. return t0;
  43714. }
  43715. // Log scales: Linear, Digits
  43716. else if(tType === 'L') {
  43717. return Math.log(sRound(
  43718. (Math.pow(10, r0) - tick0) / dtNum) * dtNum + tick0) / Math.LN10;
  43719. }
  43720. else if(tType === 'D') {
  43721. var tickset = (dtick === 'D2') ? roundLog2 : roundLog1;
  43722. var frac = Lib.roundUp(Lib.mod(r0, 1), tickset, axrev);
  43723. return Math.floor(r0) +
  43724. Math.log(d3.round(Math.pow(10, frac), 1)) / Math.LN10;
  43725. }
  43726. else throw 'unrecognized dtick ' + String(dtick);
  43727. };
  43728. // draw the text for one tick.
  43729. // px,py are the location on gd.paper
  43730. // prefix is there so the x axis ticks can be dropped a line
  43731. // ax is the axis layout, x is the tick value
  43732. // hover is a (truthy) flag for whether to show numbers with a bit
  43733. // more precision for hovertext
  43734. axes.tickText = function(ax, x, hover) {
  43735. var out = tickTextObj(ax, x);
  43736. var arrayMode = ax.tickmode === 'array';
  43737. var extraPrecision = hover || arrayMode;
  43738. var axType = ax.type;
  43739. // TODO multicategory, if we allow ticktext / tickvals
  43740. var tickVal2l = axType === 'category' ? ax.d2l_noadd : ax.d2l;
  43741. var i;
  43742. if(arrayMode && Array.isArray(ax.ticktext)) {
  43743. var rng = Lib.simpleMap(ax.range, ax.r2l);
  43744. var minDiff = Math.abs(rng[1] - rng[0]) / 10000;
  43745. for(i = 0; i < ax.ticktext.length; i++) {
  43746. if(Math.abs(x - tickVal2l(ax.tickvals[i])) < minDiff) break;
  43747. }
  43748. if(i < ax.ticktext.length) {
  43749. out.text = String(ax.ticktext[i]);
  43750. return out;
  43751. }
  43752. }
  43753. function isHidden(showAttr) {
  43754. if(showAttr === undefined) return true;
  43755. if(hover) return showAttr === 'none';
  43756. var firstOrLast = {
  43757. first: ax._tmin,
  43758. last: ax._tmax
  43759. }[showAttr];
  43760. return showAttr !== 'all' && x !== firstOrLast;
  43761. }
  43762. var hideexp = hover ?
  43763. 'never' :
  43764. ax.exponentformat !== 'none' && isHidden(ax.showexponent) ? 'hide' : '';
  43765. if(axType === 'date') formatDate(ax, out, hover, extraPrecision);
  43766. else if(axType === 'log') formatLog(ax, out, hover, extraPrecision, hideexp);
  43767. else if(axType === 'category') formatCategory(ax, out);
  43768. else if(axType === 'multicategory') formatMultiCategory(ax, out, hover);
  43769. else if(isAngular(ax)) formatAngle(ax, out, hover, extraPrecision, hideexp);
  43770. else formatLinear(ax, out, hover, extraPrecision, hideexp);
  43771. // add prefix and suffix
  43772. if(ax.tickprefix && !isHidden(ax.showtickprefix)) out.text = ax.tickprefix + out.text;
  43773. if(ax.ticksuffix && !isHidden(ax.showticksuffix)) out.text += ax.ticksuffix;
  43774. // Setup ticks and grid lines boundaries
  43775. // at 1/2 a 'category' to the left/bottom
  43776. if(ax.tickson === 'boundaries' || ax.showdividers) {
  43777. var inbounds = function(v) {
  43778. var p = ax.l2p(v);
  43779. return p >= 0 && p <= ax._length ? v : null;
  43780. };
  43781. out.xbnd = [
  43782. inbounds(out.x - 0.5),
  43783. inbounds(out.x + ax.dtick - 0.5)
  43784. ];
  43785. }
  43786. return out;
  43787. };
  43788. /**
  43789. * create text for a hover label on this axis, with special handling of
  43790. * log axes (where negative values can't be displayed but can appear in hover text)
  43791. *
  43792. * @param {object} ax: the axis to format text for
  43793. * @param {number} val: calcdata value to format
  43794. * @param {Optional(number)} val2: a second value to display
  43795. *
  43796. * @returns {string} `val` formatted as a string appropriate to this axis, or
  43797. * `val` and `val2` as a range (ie '<val> - <val2>') if `val2` is provided and
  43798. * it's different from `val`.
  43799. */
  43800. axes.hoverLabelText = function(ax, val, val2) {
  43801. if(val2 !== BADNUM && val2 !== val) {
  43802. return axes.hoverLabelText(ax, val) + ' - ' + axes.hoverLabelText(ax, val2);
  43803. }
  43804. var logOffScale = (ax.type === 'log' && val <= 0);
  43805. var tx = axes.tickText(ax, ax.c2l(logOffScale ? -val : val), 'hover').text;
  43806. if(logOffScale) {
  43807. return val === 0 ? '0' : MINUS_SIGN + tx;
  43808. }
  43809. // TODO: should we do something special if the axis calendar and
  43810. // the data calendar are different? Somehow display both dates with
  43811. // their system names? Right now it will just display in the axis calendar
  43812. // but users could add the other one as text.
  43813. return tx;
  43814. };
  43815. function tickTextObj(ax, x, text) {
  43816. var tf = ax.tickfont || {};
  43817. return {
  43818. x: x,
  43819. dx: 0,
  43820. dy: 0,
  43821. text: text || '',
  43822. fontSize: tf.size,
  43823. font: tf.family,
  43824. fontColor: tf.color
  43825. };
  43826. }
  43827. function formatDate(ax, out, hover, extraPrecision) {
  43828. var tr = ax._tickround;
  43829. var fmt = (hover && ax.hoverformat) || axes.getTickFormat(ax);
  43830. if(extraPrecision) {
  43831. // second or sub-second precision: extra always shows max digits.
  43832. // for other fields, extra precision just adds one field.
  43833. if(isNumeric(tr)) tr = 4;
  43834. else tr = {y: 'm', m: 'd', d: 'M', M: 'S', S: 4}[tr];
  43835. }
  43836. var dateStr = Lib.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat);
  43837. var headStr;
  43838. var splitIndex = dateStr.indexOf('\n');
  43839. if(splitIndex !== -1) {
  43840. headStr = dateStr.substr(splitIndex + 1);
  43841. dateStr = dateStr.substr(0, splitIndex);
  43842. }
  43843. if(extraPrecision) {
  43844. // if extraPrecision led to trailing zeros, strip them off
  43845. // actually, this can lead to removing even more zeros than
  43846. // in the original rounding, but that's fine because in these
  43847. // contexts uniformity is not so important (if there's even
  43848. // anything to be uniform with!)
  43849. // can we remove the whole time part?
  43850. if(dateStr === '00:00:00' || dateStr === '00:00') {
  43851. dateStr = headStr;
  43852. headStr = '';
  43853. }
  43854. else if(dateStr.length === 8) {
  43855. // strip off seconds if they're zero (zero fractional seconds
  43856. // are already omitted)
  43857. // but we never remove minutes and leave just hours
  43858. dateStr = dateStr.replace(/:00$/, '');
  43859. }
  43860. }
  43861. if(headStr) {
  43862. if(hover) {
  43863. // hover puts it all on one line, so headPart works best up front
  43864. // except for year headPart: turn this into "Jan 1, 2000" etc.
  43865. if(tr === 'd') dateStr += ', ' + headStr;
  43866. else dateStr = headStr + (dateStr ? ', ' + dateStr : '');
  43867. }
  43868. else if(!ax._inCalcTicks || (headStr !== ax._prevDateHead)) {
  43869. dateStr += '<br>' + headStr;
  43870. ax._prevDateHead = headStr;
  43871. }
  43872. }
  43873. out.text = dateStr;
  43874. }
  43875. function formatLog(ax, out, hover, extraPrecision, hideexp) {
  43876. var dtick = ax.dtick;
  43877. var x = out.x;
  43878. var tickformat = ax.tickformat;
  43879. var dtChar0 = typeof dtick === 'string' && dtick.charAt(0);
  43880. if(hideexp === 'never') {
  43881. // If this is a hover label, then we must *never* hide the exponent
  43882. // for the sake of display, which could give the wrong value by
  43883. // potentially many orders of magnitude. If hideexp was 'never', then
  43884. // it's now succeeded by preventing the other condition from automating
  43885. // this choice. Thus we can unset it so that the axis formatting takes
  43886. // precedence.
  43887. hideexp = '';
  43888. }
  43889. if(extraPrecision && (dtChar0 !== 'L')) {
  43890. dtick = 'L3';
  43891. dtChar0 = 'L';
  43892. }
  43893. if(tickformat || (dtChar0 === 'L')) {
  43894. out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision);
  43895. }
  43896. else if(isNumeric(dtick) || ((dtChar0 === 'D') && (Lib.mod(x + 0.01, 1) < 0.1))) {
  43897. var p = Math.round(x);
  43898. var absP = Math.abs(p);
  43899. var exponentFormat = ax.exponentformat;
  43900. if(exponentFormat === 'power' || (isSIFormat(exponentFormat) && beyondSI(p))) {
  43901. if(p === 0) out.text = 1;
  43902. else if(p === 1) out.text = '10';
  43903. else out.text = '10<sup>' + (p > 1 ? '' : MINUS_SIGN) + absP + '</sup>';
  43904. out.fontSize *= 1.25;
  43905. }
  43906. else if((exponentFormat === 'e' || exponentFormat === 'E') && absP > 2) {
  43907. out.text = '1' + exponentFormat + (p > 0 ? '+' : MINUS_SIGN) + absP;
  43908. }
  43909. else {
  43910. out.text = numFormat(Math.pow(10, x), ax, '', 'fakehover');
  43911. if(dtick === 'D1' && ax._id.charAt(0) === 'y') {
  43912. out.dy -= out.fontSize / 6;
  43913. }
  43914. }
  43915. }
  43916. else if(dtChar0 === 'D') {
  43917. out.text = String(Math.round(Math.pow(10, Lib.mod(x, 1))));
  43918. out.fontSize *= 0.75;
  43919. }
  43920. else throw 'unrecognized dtick ' + String(dtick);
  43921. // if 9's are printed on log scale, move the 10's away a bit
  43922. if(ax.dtick === 'D1') {
  43923. var firstChar = String(out.text).charAt(0);
  43924. if(firstChar === '0' || firstChar === '1') {
  43925. if(ax._id.charAt(0) === 'y') {
  43926. out.dx -= out.fontSize / 4;
  43927. }
  43928. else {
  43929. out.dy += out.fontSize / 2;
  43930. out.dx += (ax.range[1] > ax.range[0] ? 1 : -1) *
  43931. out.fontSize * (x < 0 ? 0.5 : 0.25);
  43932. }
  43933. }
  43934. }
  43935. }
  43936. function formatCategory(ax, out) {
  43937. var tt = ax._categories[Math.round(out.x)];
  43938. if(tt === undefined) tt = '';
  43939. out.text = String(tt);
  43940. }
  43941. function formatMultiCategory(ax, out, hover) {
  43942. var v = Math.round(out.x);
  43943. var cats = ax._categories[v] || [];
  43944. var tt = cats[1] === undefined ? '' : String(cats[1]);
  43945. var tt2 = cats[0] === undefined ? '' : String(cats[0]);
  43946. if(hover) {
  43947. // TODO is this what we want?
  43948. out.text = tt2 + ' - ' + tt;
  43949. } else {
  43950. // setup for secondary labels
  43951. out.text = tt;
  43952. out.text2 = tt2;
  43953. }
  43954. }
  43955. function formatLinear(ax, out, hover, extraPrecision, hideexp) {
  43956. if(hideexp === 'never') {
  43957. // If this is a hover label, then we must *never* hide the exponent
  43958. // for the sake of display, which could give the wrong value by
  43959. // potentially many orders of magnitude. If hideexp was 'never', then
  43960. // it's now succeeded by preventing the other condition from automating
  43961. // this choice. Thus we can unset it so that the axis formatting takes
  43962. // precedence.
  43963. hideexp = '';
  43964. } else if(ax.showexponent === 'all' && Math.abs(out.x / ax.dtick) < 1e-6) {
  43965. // don't add an exponent to zero if we're showing all exponents
  43966. // so the only reason you'd show an exponent on zero is if it's the
  43967. // ONLY tick to get an exponent (first or last)
  43968. hideexp = 'hide';
  43969. }
  43970. out.text = numFormat(out.x, ax, hideexp, extraPrecision);
  43971. }
  43972. function formatAngle(ax, out, hover, extraPrecision, hideexp) {
  43973. if(ax.thetaunit === 'radians' && !hover) {
  43974. var num = out.x / 180;
  43975. if(num === 0) {
  43976. out.text = '0';
  43977. } else {
  43978. var frac = num2frac(num);
  43979. if(frac[1] >= 100) {
  43980. out.text = numFormat(Lib.deg2rad(out.x), ax, hideexp, extraPrecision);
  43981. } else {
  43982. var isNeg = out.x < 0;
  43983. if(frac[1] === 1) {
  43984. if(frac[0] === 1) out.text = 'π';
  43985. else out.text = frac[0] + 'π';
  43986. } else {
  43987. out.text = [
  43988. '<sup>', frac[0], '</sup>',
  43989. '⁄',
  43990. '<sub>', frac[1], '</sub>',
  43991. 'π'
  43992. ].join('');
  43993. }
  43994. if(isNeg) out.text = MINUS_SIGN + out.text;
  43995. }
  43996. }
  43997. } else {
  43998. out.text = numFormat(out.x, ax, hideexp, extraPrecision);
  43999. }
  44000. }
  44001. // inspired by
  44002. // https://github.com/yisibl/num2fraction/blob/master/index.js
  44003. function num2frac(num) {
  44004. function almostEq(a, b) {
  44005. return Math.abs(a - b) <= 1e-6;
  44006. }
  44007. function findGCD(a, b) {
  44008. return almostEq(b, 0) ? a : findGCD(b, a % b);
  44009. }
  44010. function findPrecision(n) {
  44011. var e = 1;
  44012. while(!almostEq(Math.round(n * e) / e, n)) {
  44013. e *= 10;
  44014. }
  44015. return e;
  44016. }
  44017. var precision = findPrecision(num);
  44018. var number = num * precision;
  44019. var gcd = Math.abs(findGCD(number, precision));
  44020. return [
  44021. // numerator
  44022. Math.round(number / gcd),
  44023. // denominator
  44024. Math.round(precision / gcd)
  44025. ];
  44026. }
  44027. // format a number (tick value) according to the axis settings
  44028. // new, more reliable procedure than d3.round or similar:
  44029. // add half the rounding increment, then stringify and truncate
  44030. // also automatically switch to sci. notation
  44031. var SIPREFIXES = ['f', 'p', 'n', 'μ', 'm', '', 'k', 'M', 'G', 'T'];
  44032. function isSIFormat(exponentFormat) {
  44033. return exponentFormat === 'SI' || exponentFormat === 'B';
  44034. }
  44035. // are we beyond the range of common SI prefixes?
  44036. // 10^-16 -> 1x10^-16
  44037. // 10^-15 -> 1f
  44038. // ...
  44039. // 10^14 -> 100T
  44040. // 10^15 -> 1x10^15
  44041. // 10^16 -> 1x10^16
  44042. function beyondSI(exponent) {
  44043. return exponent > 14 || exponent < -15;
  44044. }
  44045. function numFormat(v, ax, fmtoverride, hover) {
  44046. var isNeg = v < 0;
  44047. // max number of digits past decimal point to show
  44048. var tickRound = ax._tickround;
  44049. var exponentFormat = fmtoverride || ax.exponentformat || 'B';
  44050. var exponent = ax._tickexponent;
  44051. var tickformat = axes.getTickFormat(ax);
  44052. var separatethousands = ax.separatethousands;
  44053. // special case for hover: set exponent just for this value, and
  44054. // add a couple more digits of precision over tick labels
  44055. if(hover) {
  44056. // make a dummy axis obj to get the auto rounding and exponent
  44057. var ah = {
  44058. exponentformat: exponentFormat,
  44059. dtick: ax.showexponent === 'none' ? ax.dtick :
  44060. (isNumeric(v) ? Math.abs(v) || 1 : 1),
  44061. // if not showing any exponents, don't change the exponent
  44062. // from what we calculate
  44063. range: ax.showexponent === 'none' ? ax.range.map(ax.r2d) : [0, v || 1]
  44064. };
  44065. autoTickRound(ah);
  44066. tickRound = (Number(ah._tickround) || 0) + 4;
  44067. exponent = ah._tickexponent;
  44068. if(ax.hoverformat) tickformat = ax.hoverformat;
  44069. }
  44070. if(tickformat) return ax._numFormat(tickformat)(v).replace(/-/g, MINUS_SIGN);
  44071. // 'epsilon' - rounding increment
  44072. var e = Math.pow(10, -tickRound) / 2;
  44073. // exponentFormat codes:
  44074. // 'e' (1.2e+6, default)
  44075. // 'E' (1.2E+6)
  44076. // 'SI' (1.2M)
  44077. // 'B' (same as SI except 10^9=B not G)
  44078. // 'none' (1200000)
  44079. // 'power' (1.2x10^6)
  44080. // 'hide' (1.2, use 3rd argument=='hide' to eg
  44081. // only show exponent on last tick)
  44082. if(exponentFormat === 'none') exponent = 0;
  44083. // take the sign out, put it back manually at the end
  44084. // - makes cases easier
  44085. v = Math.abs(v);
  44086. if(v < e) {
  44087. // 0 is just 0, but may get exponent if it's the last tick
  44088. v = '0';
  44089. isNeg = false;
  44090. }
  44091. else {
  44092. v += e;
  44093. // take out a common exponent, if any
  44094. if(exponent) {
  44095. v *= Math.pow(10, -exponent);
  44096. tickRound += exponent;
  44097. }
  44098. // round the mantissa
  44099. if(tickRound === 0) v = String(Math.floor(v));
  44100. else if(tickRound < 0) {
  44101. v = String(Math.round(v));
  44102. v = v.substr(0, v.length + tickRound);
  44103. for(var i = tickRound; i < 0; i++) v += '0';
  44104. }
  44105. else {
  44106. v = String(v);
  44107. var dp = v.indexOf('.') + 1;
  44108. if(dp) v = v.substr(0, dp + tickRound).replace(/\.?0+$/, '');
  44109. }
  44110. // insert appropriate decimal point and thousands separator
  44111. v = Lib.numSeparate(v, ax._separators, separatethousands);
  44112. }
  44113. // add exponent
  44114. if(exponent && exponentFormat !== 'hide') {
  44115. if(isSIFormat(exponentFormat) && beyondSI(exponent)) exponentFormat = 'power';
  44116. var signedExponent;
  44117. if(exponent < 0) signedExponent = MINUS_SIGN + -exponent;
  44118. else if(exponentFormat !== 'power') signedExponent = '+' + exponent;
  44119. else signedExponent = String(exponent);
  44120. if(exponentFormat === 'e' || exponentFormat === 'E') {
  44121. v += exponentFormat + signedExponent;
  44122. }
  44123. else if(exponentFormat === 'power') {
  44124. v += '×10<sup>' + signedExponent + '</sup>';
  44125. }
  44126. else if(exponentFormat === 'B' && exponent === 9) {
  44127. v += 'B';
  44128. }
  44129. else if(isSIFormat(exponentFormat)) {
  44130. v += SIPREFIXES[exponent / 3 + 5];
  44131. }
  44132. }
  44133. // put sign back in and return
  44134. // replace standard minus character (which is technically a hyphen)
  44135. // with a true minus sign
  44136. if(isNeg) return MINUS_SIGN + v;
  44137. return v;
  44138. }
  44139. axes.getTickFormat = function(ax) {
  44140. var i;
  44141. function convertToMs(dtick) {
  44142. return typeof dtick !== 'string' ? dtick : Number(dtick.replace('M', '')) * ONEAVGMONTH;
  44143. }
  44144. function compareLogTicks(left, right) {
  44145. var priority = ['L', 'D'];
  44146. if(typeof left === typeof right) {
  44147. if(typeof left === 'number') {
  44148. return left - right;
  44149. } else {
  44150. var leftPriority = priority.indexOf(left.charAt(0));
  44151. var rightPriority = priority.indexOf(right.charAt(0));
  44152. if(leftPriority === rightPriority) {
  44153. return Number(left.replace(/(L|D)/g, '')) - Number(right.replace(/(L|D)/g, ''));
  44154. } else {
  44155. return leftPriority - rightPriority;
  44156. }
  44157. }
  44158. } else {
  44159. return typeof left === 'number' ? 1 : -1;
  44160. }
  44161. }
  44162. function isProperStop(dtick, range, convert) {
  44163. var convertFn = convert || function(x) { return x;};
  44164. var leftDtick = range[0];
  44165. var rightDtick = range[1];
  44166. return ((!leftDtick && typeof leftDtick !== 'number') || convertFn(leftDtick) <= convertFn(dtick)) &&
  44167. ((!rightDtick && typeof rightDtick !== 'number') || convertFn(rightDtick) >= convertFn(dtick));
  44168. }
  44169. function isProperLogStop(dtick, range) {
  44170. var isLeftDtickNull = range[0] === null;
  44171. var isRightDtickNull = range[1] === null;
  44172. var isDtickInRangeLeft = compareLogTicks(dtick, range[0]) >= 0;
  44173. var isDtickInRangeRight = compareLogTicks(dtick, range[1]) <= 0;
  44174. return (isLeftDtickNull || isDtickInRangeLeft) && (isRightDtickNull || isDtickInRangeRight);
  44175. }
  44176. var tickstop, stopi;
  44177. if(ax.tickformatstops && ax.tickformatstops.length > 0) {
  44178. switch(ax.type) {
  44179. case 'date':
  44180. case 'linear': {
  44181. for(i = 0; i < ax.tickformatstops.length; i++) {
  44182. stopi = ax.tickformatstops[i];
  44183. if(stopi.enabled && isProperStop(ax.dtick, stopi.dtickrange, convertToMs)) {
  44184. tickstop = stopi;
  44185. break;
  44186. }
  44187. }
  44188. break;
  44189. }
  44190. case 'log': {
  44191. for(i = 0; i < ax.tickformatstops.length; i++) {
  44192. stopi = ax.tickformatstops[i];
  44193. if(stopi.enabled && isProperLogStop(ax.dtick, stopi.dtickrange)) {
  44194. tickstop = stopi;
  44195. break;
  44196. }
  44197. }
  44198. break;
  44199. }
  44200. default:
  44201. }
  44202. }
  44203. return tickstop ? tickstop.value : ax.tickformat;
  44204. };
  44205. // getSubplots - extract all subplot IDs we need
  44206. // as an array of items like 'xy', 'x2y', 'x2y2'...
  44207. // sorted by x (x,x2,x3...) then y
  44208. // optionally restrict to only subplots containing axis object ax
  44209. //
  44210. // NOTE: this is currently only used OUTSIDE plotly.js (toolpanel, webapp)
  44211. // ideally we get rid of it there (or just copy this there) and remove it here
  44212. axes.getSubplots = function(gd, ax) {
  44213. var subplotObj = gd._fullLayout._subplots;
  44214. var allSubplots = subplotObj.cartesian.concat(subplotObj.gl2d || []);
  44215. var out = ax ? axes.findSubplotsWithAxis(allSubplots, ax) : allSubplots;
  44216. out.sort(function(a, b) {
  44217. var aParts = a.substr(1).split('y');
  44218. var bParts = b.substr(1).split('y');
  44219. if(aParts[0] === bParts[0]) return +aParts[1] - +bParts[1];
  44220. return +aParts[0] - +bParts[0];
  44221. });
  44222. return out;
  44223. };
  44224. // find all subplots with axis 'ax'
  44225. // NOTE: this is only used in axes.getSubplots (only used outside plotly.js) and
  44226. // gl2d/convert (where it restricts axis subplots to only those with gl2d)
  44227. axes.findSubplotsWithAxis = function(subplots, ax) {
  44228. var axMatch = new RegExp(
  44229. (ax._id.charAt(0) === 'x') ? ('^' + ax._id + 'y') : (ax._id + '$')
  44230. );
  44231. var subplotsWithAx = [];
  44232. for(var i = 0; i < subplots.length; i++) {
  44233. var sp = subplots[i];
  44234. if(axMatch.test(sp)) subplotsWithAx.push(sp);
  44235. }
  44236. return subplotsWithAx;
  44237. };
  44238. // makeClipPaths: prepare clipPaths for all single axes and all possible xy pairings
  44239. axes.makeClipPaths = function(gd) {
  44240. var fullLayout = gd._fullLayout;
  44241. // for more info: https://github.com/plotly/plotly.js/issues/2595
  44242. if(fullLayout._hasOnlyLargeSploms) return;
  44243. var fullWidth = {_offset: 0, _length: fullLayout.width, _id: ''};
  44244. var fullHeight = {_offset: 0, _length: fullLayout.height, _id: ''};
  44245. var xaList = axes.list(gd, 'x', true);
  44246. var yaList = axes.list(gd, 'y', true);
  44247. var clipList = [];
  44248. var i, j;
  44249. for(i = 0; i < xaList.length; i++) {
  44250. clipList.push({x: xaList[i], y: fullHeight});
  44251. for(j = 0; j < yaList.length; j++) {
  44252. if(i === 0) clipList.push({x: fullWidth, y: yaList[j]});
  44253. clipList.push({x: xaList[i], y: yaList[j]});
  44254. }
  44255. }
  44256. // selectors don't work right with camelCase tags,
  44257. // have to use class instead
  44258. // https://groups.google.com/forum/#!topic/d3-js/6EpAzQ2gU9I
  44259. var axClips = fullLayout._clips.selectAll('.axesclip')
  44260. .data(clipList, function(d) { return d.x._id + d.y._id; });
  44261. axClips.enter().append('clipPath')
  44262. .classed('axesclip', true)
  44263. .attr('id', function(d) { return 'clip' + fullLayout._uid + d.x._id + d.y._id; })
  44264. .append('rect');
  44265. axClips.exit().remove();
  44266. axClips.each(function(d) {
  44267. d3.select(this).select('rect').attr({
  44268. x: d.x._offset || 0,
  44269. y: d.y._offset || 0,
  44270. width: d.x._length || 1,
  44271. height: d.y._length || 1
  44272. });
  44273. });
  44274. };
  44275. /**
  44276. * Main multi-axis drawing routine!
  44277. *
  44278. * @param {DOM element} gd : graph div
  44279. * @param {string or array of strings} arg : polymorphic argument
  44280. * @param {object} opts:
  44281. * - @param {boolean} skipTitle : optional flag to skip axis title draw/update
  44282. *
  44283. * Signature 1: Axes.draw(gd, 'redraw')
  44284. * use this to clear and redraw all axes on graph
  44285. *
  44286. * Signature 2: Axes.draw(gd, '')
  44287. * use this to draw all axes on graph w/o the selectAll().remove()
  44288. * of the 'redraw' signature
  44289. *
  44290. * Signature 3: Axes.draw(gd, [axId, axId2, ...])
  44291. * where the items are axis id string,
  44292. * use this to update multiple axes in one call
  44293. *
  44294. * N.B draw updates:
  44295. * - ax._r (stored range for use by zoom/pan)
  44296. * - ax._rl (stored linearized range for use by zoom/pan)
  44297. */
  44298. axes.draw = function(gd, arg, opts) {
  44299. var fullLayout = gd._fullLayout;
  44300. if(arg === 'redraw') {
  44301. fullLayout._paper.selectAll('g.subplot').each(function(d) {
  44302. var id = d[0];
  44303. var plotinfo = fullLayout._plots[id];
  44304. var xa = plotinfo.xaxis;
  44305. var ya = plotinfo.yaxis;
  44306. plotinfo.xaxislayer.selectAll('.' + xa._id + 'tick').remove();
  44307. plotinfo.yaxislayer.selectAll('.' + ya._id + 'tick').remove();
  44308. plotinfo.xaxislayer.selectAll('.' + xa._id + 'tick2').remove();
  44309. plotinfo.yaxislayer.selectAll('.' + ya._id + 'tick2').remove();
  44310. plotinfo.xaxislayer.selectAll('.' + xa._id + 'divider').remove();
  44311. plotinfo.yaxislayer.selectAll('.' + ya._id + 'divider').remove();
  44312. if(plotinfo.gridlayer) plotinfo.gridlayer.selectAll('path').remove();
  44313. if(plotinfo.zerolinelayer) plotinfo.zerolinelayer.selectAll('path').remove();
  44314. fullLayout._infolayer.select('.g-' + xa._id + 'title').remove();
  44315. fullLayout._infolayer.select('.g-' + ya._id + 'title').remove();
  44316. });
  44317. }
  44318. var axList = (!arg || arg === 'redraw') ? axes.listIds(gd) : arg;
  44319. return Lib.syncOrAsync(axList.map(function(axId) {
  44320. return function() {
  44321. if(!axId) return;
  44322. var ax = axes.getFromId(gd, axId);
  44323. var axDone = axes.drawOne(gd, ax, opts);
  44324. ax._r = ax.range.slice();
  44325. ax._rl = Lib.simpleMap(ax._r, ax.r2l);
  44326. return axDone;
  44327. };
  44328. }));
  44329. };
  44330. /**
  44331. * Draw one cartesian axis
  44332. *
  44333. * @param {DOM element} gd
  44334. * @param {object} ax (full) axis object
  44335. * @param {object} opts
  44336. * - @param {boolean} skipTitle (set to true to skip axis title draw call)
  44337. */
  44338. axes.drawOne = function(gd, ax, opts) {
  44339. opts = opts || {};
  44340. var i, sp, plotinfo;
  44341. ax.setScale();
  44342. var fullLayout = gd._fullLayout;
  44343. var axId = ax._id;
  44344. var axLetter = axId.charAt(0);
  44345. var counterLetter = axes.counterLetter(axId);
  44346. var mainSubplot = ax._mainSubplot;
  44347. var mainLinePosition = ax._mainLinePosition;
  44348. var mainMirrorPosition = ax._mainMirrorPosition;
  44349. var mainPlotinfo = fullLayout._plots[mainSubplot];
  44350. var mainAxLayer = mainPlotinfo[axLetter + 'axislayer'];
  44351. var subplotsWithAx = ax._subplotsWith;
  44352. var vals = ax._vals = axes.calcTicks(ax);
  44353. // Add a couple of axis properties that should cause us to recreate
  44354. // elements. Used in d3 data function.
  44355. var axInfo = [ax.mirror, mainLinePosition, mainMirrorPosition].join('_');
  44356. for(i = 0; i < vals.length; i++) {
  44357. vals[i].axInfo = axInfo;
  44358. }
  44359. if(!ax.visible) return;
  44360. // stash selections to avoid DOM queries e.g.
  44361. // - stash tickLabels selection, so that drawTitle can use it to scoot title
  44362. ax._selections = {};
  44363. // stash tick angle (including the computed 'auto' values) per tick-label class
  44364. ax._tickAngles = {};
  44365. var transFn = axes.makeTransFn(ax);
  44366. var tickVals;
  44367. // We remove zero lines, grid lines, and inside ticks if they're within 1px of the end
  44368. // The key case here is removing zero lines when the axis bound is zero
  44369. var valsClipped;
  44370. if(ax.tickson === 'boundaries') {
  44371. var boundaryVals = getBoundaryVals(ax, vals);
  44372. valsClipped = axes.clipEnds(ax, boundaryVals);
  44373. tickVals = ax.ticks === 'inside' ? valsClipped : boundaryVals;
  44374. } else {
  44375. valsClipped = axes.clipEnds(ax, vals);
  44376. tickVals = ax.ticks === 'inside' ? valsClipped : vals;
  44377. }
  44378. var gridVals = ax._gridVals = valsClipped;
  44379. var dividerVals = getDividerVals(ax, vals);
  44380. if(!fullLayout._hasOnlyLargeSploms) {
  44381. // keep track of which subplots (by main conteraxis) we've already
  44382. // drawn grids for, so we don't overdraw overlaying subplots
  44383. var finishedGrids = {};
  44384. for(i = 0; i < subplotsWithAx.length; i++) {
  44385. sp = subplotsWithAx[i];
  44386. plotinfo = fullLayout._plots[sp];
  44387. var counterAxis = plotinfo[counterLetter + 'axis'];
  44388. var mainCounterID = counterAxis._mainAxis._id;
  44389. if(finishedGrids[mainCounterID]) continue;
  44390. finishedGrids[mainCounterID] = 1;
  44391. var gridPath = axLetter === 'x' ?
  44392. 'M0,' + counterAxis._offset + 'v' + counterAxis._length :
  44393. 'M' + counterAxis._offset + ',0h' + counterAxis._length;
  44394. axes.drawGrid(gd, ax, {
  44395. vals: gridVals,
  44396. counterAxis: counterAxis,
  44397. layer: plotinfo.gridlayer.select('.' + axId),
  44398. path: gridPath,
  44399. transFn: transFn
  44400. });
  44401. axes.drawZeroLine(gd, ax, {
  44402. counterAxis: counterAxis,
  44403. layer: plotinfo.zerolinelayer,
  44404. path: gridPath,
  44405. transFn: transFn
  44406. });
  44407. }
  44408. }
  44409. var tickSigns = axes.getTickSigns(ax);
  44410. var tickSubplots = [];
  44411. if(ax.ticks) {
  44412. var mainTickPath = axes.makeTickPath(ax, mainLinePosition, tickSigns[2]);
  44413. var mirrorTickPath;
  44414. var fullTickPath;
  44415. if(ax._anchorAxis && ax.mirror && ax.mirror !== true) {
  44416. mirrorTickPath = axes.makeTickPath(ax, mainMirrorPosition, tickSigns[3]);
  44417. fullTickPath = mainTickPath + mirrorTickPath;
  44418. } else {
  44419. mirrorTickPath = '';
  44420. fullTickPath = mainTickPath;
  44421. }
  44422. var tickPath;
  44423. if(ax.showdividers && ax.ticks === 'outside' && ax.tickson === 'boundaries') {
  44424. var dividerLookup = {};
  44425. for(i = 0; i < dividerVals.length; i++) {
  44426. dividerLookup[dividerVals[i].x] = 1;
  44427. }
  44428. tickPath = function(d) {
  44429. return dividerLookup[d.x] ? mirrorTickPath : fullTickPath;
  44430. };
  44431. } else {
  44432. tickPath = fullTickPath;
  44433. }
  44434. axes.drawTicks(gd, ax, {
  44435. vals: tickVals,
  44436. layer: mainAxLayer,
  44437. path: tickPath,
  44438. transFn: transFn
  44439. });
  44440. tickSubplots = Object.keys(ax._linepositions || {});
  44441. }
  44442. for(i = 0; i < tickSubplots.length; i++) {
  44443. sp = tickSubplots[i];
  44444. plotinfo = fullLayout._plots[sp];
  44445. // [bottom or left, top or right], free and main are handled above
  44446. var linepositions = ax._linepositions[sp] || [];
  44447. var spTickPath = axes.makeTickPath(ax, linepositions[0], tickSigns[0]) +
  44448. axes.makeTickPath(ax, linepositions[1], tickSigns[1]);
  44449. axes.drawTicks(gd, ax, {
  44450. vals: tickVals,
  44451. layer: plotinfo[axLetter + 'axislayer'],
  44452. path: spTickPath,
  44453. transFn: transFn
  44454. });
  44455. }
  44456. var seq = [];
  44457. // tick labels - for now just the main labels.
  44458. // TODO: mirror labels, esp for subplots
  44459. seq.push(function() {
  44460. var labelFns = axes.makeLabelFns(ax, mainLinePosition);
  44461. return axes.drawLabels(gd, ax, {
  44462. vals: vals,
  44463. layer: mainAxLayer,
  44464. transFn: transFn,
  44465. labelXFn: labelFns.labelXFn,
  44466. labelYFn: labelFns.labelYFn,
  44467. labelAnchorFn: labelFns.labelAnchorFn,
  44468. });
  44469. });
  44470. if(ax.type === 'multicategory') {
  44471. var labelLength = 0;
  44472. var pad = {x: 2, y: 10}[axLetter];
  44473. var sgn = tickSigns[2] * (ax.ticks === 'inside' ? -1 : 1);
  44474. seq.push(function() {
  44475. labelLength += getLabelLevelSpan(ax, axId + 'tick') + pad;
  44476. labelLength += ax._tickAngles[axId + 'tick'] ? ax.tickfont.size * LINE_SPACING : 0;
  44477. var secondaryPosition = mainLinePosition + labelLength * sgn;
  44478. var secondaryLabelFns = axes.makeLabelFns(ax, secondaryPosition);
  44479. return axes.drawLabels(gd, ax, {
  44480. vals: getSecondaryLabelVals(ax, vals),
  44481. layer: mainAxLayer,
  44482. cls: axId + 'tick2',
  44483. repositionOnUpdate: true,
  44484. secondary: true,
  44485. transFn: transFn,
  44486. labelXFn: secondaryLabelFns.labelXFn,
  44487. labelYFn: secondaryLabelFns.labelYFn,
  44488. labelAnchorFn: secondaryLabelFns.labelAnchorFn,
  44489. });
  44490. });
  44491. seq.push(function() {
  44492. labelLength += getLabelLevelSpan(ax, axId + 'tick2');
  44493. ax._labelLength = labelLength;
  44494. return drawDividers(gd, ax, {
  44495. vals: dividerVals,
  44496. layer: mainAxLayer,
  44497. path: axes.makeTickPath(ax, mainLinePosition, sgn, labelLength),
  44498. transFn: transFn
  44499. });
  44500. });
  44501. }
  44502. function extendRange(range, newRange) {
  44503. range[0] = Math.min(range[0], newRange[0]);
  44504. range[1] = Math.max(range[1], newRange[1]);
  44505. }
  44506. function calcBoundingBox() {
  44507. if(ax.showticklabels) {
  44508. var gdBB = gd.getBoundingClientRect();
  44509. var bBox = mainAxLayer.node().getBoundingClientRect();
  44510. /*
  44511. * the way we're going to use this, the positioning that matters
  44512. * is relative to the origin of gd. This is important particularly
  44513. * if gd is scrollable, and may have been scrolled between the time
  44514. * we calculate this and the time we use it
  44515. */
  44516. ax._boundingBox = {
  44517. width: bBox.width,
  44518. height: bBox.height,
  44519. left: bBox.left - gdBB.left,
  44520. right: bBox.right - gdBB.left,
  44521. top: bBox.top - gdBB.top,
  44522. bottom: bBox.bottom - gdBB.top
  44523. };
  44524. } else {
  44525. var gs = fullLayout._size;
  44526. var pos;
  44527. // set dummy bbox for ticklabel-less axes
  44528. if(axLetter === 'x') {
  44529. pos = ax.anchor === 'free' ?
  44530. gs.t + gs.h * (1 - ax.position) :
  44531. gs.t + gs.h * (1 - ax._anchorAxis.domain[{bottom: 0, top: 1}[ax.side]]);
  44532. ax._boundingBox = {
  44533. top: pos,
  44534. bottom: pos,
  44535. left: ax._offset,
  44536. right: ax._offset + ax._length,
  44537. width: ax._length,
  44538. height: 0
  44539. };
  44540. } else {
  44541. pos = ax.anchor === 'free' ?
  44542. gs.l + gs.w * ax.position :
  44543. gs.l + gs.w * ax._anchorAxis.domain[{left: 0, right: 1}[ax.side]];
  44544. ax._boundingBox = {
  44545. left: pos,
  44546. right: pos,
  44547. bottom: ax._offset + ax._length,
  44548. top: ax._offset,
  44549. height: ax._length,
  44550. width: 0
  44551. };
  44552. }
  44553. }
  44554. /*
  44555. * for spikelines: what's the full domain of positions in the
  44556. * opposite direction that are associated with this axis?
  44557. * This means any axes that we make a subplot with, plus the
  44558. * position of the axis itself if it's free.
  44559. */
  44560. if(subplotsWithAx) {
  44561. var fullRange = ax._counterSpan = [Infinity, -Infinity];
  44562. for(var i = 0; i < subplotsWithAx.length; i++) {
  44563. var plotinfo = fullLayout._plots[subplotsWithAx[i]];
  44564. var counterAxis = plotinfo[(axLetter === 'x') ? 'yaxis' : 'xaxis'];
  44565. extendRange(fullRange, [
  44566. counterAxis._offset,
  44567. counterAxis._offset + counterAxis._length
  44568. ]);
  44569. }
  44570. if(ax.anchor === 'free') {
  44571. extendRange(fullRange, (axLetter === 'x') ?
  44572. [ax._boundingBox.bottom, ax._boundingBox.top] :
  44573. [ax._boundingBox.right, ax._boundingBox.left]);
  44574. }
  44575. }
  44576. }
  44577. var hasRangeSlider = Registry.getComponentMethod('rangeslider', 'isVisible')(ax);
  44578. function doAutoMargins() {
  44579. var s = ax.side.charAt(0);
  44580. var push;
  44581. var rangeSliderPush;
  44582. if(hasRangeSlider) {
  44583. rangeSliderPush = Registry.getComponentMethod('rangeslider', 'autoMarginOpts')(gd, ax);
  44584. }
  44585. Plots.autoMargin(gd, rangeSliderAutoMarginID(ax), rangeSliderPush);
  44586. if(ax.automargin && (!hasRangeSlider || s !== 'b')) {
  44587. push = {x: 0, y: 0, r: 0, l: 0, t: 0, b: 0};
  44588. var bbox = ax._boundingBox;
  44589. var counterAx = mainPlotinfo[counterLetter + 'axis'];
  44590. var anchorAxDomainIndex;
  44591. var offset;
  44592. switch(axLetter + s) {
  44593. case 'xb':
  44594. anchorAxDomainIndex = 0;
  44595. offset = bbox.top - counterAx._length - counterAx._offset;
  44596. push[s] = bbox.height;
  44597. break;
  44598. case 'xt':
  44599. anchorAxDomainIndex = 1;
  44600. offset = counterAx._offset - bbox.bottom;
  44601. push[s] = bbox.height;
  44602. break;
  44603. case 'yl':
  44604. anchorAxDomainIndex = 0;
  44605. offset = counterAx._offset - bbox.right;
  44606. push[s] = bbox.width;
  44607. break;
  44608. case 'yr':
  44609. anchorAxDomainIndex = 1;
  44610. offset = bbox.left - counterAx._length - counterAx._offset;
  44611. push[s] = bbox.width;
  44612. break;
  44613. }
  44614. push[counterLetter] = ax.anchor === 'free' ?
  44615. ax.position :
  44616. ax._anchorAxis.domain[anchorAxDomainIndex];
  44617. if(push[s] > 0) {
  44618. push[s] += offset;
  44619. }
  44620. if(ax.title.text !== fullLayout._dfltTitle[axLetter]) {
  44621. push[s] += ax.title.font.size;
  44622. }
  44623. }
  44624. Plots.autoMargin(gd, axAutoMarginID(ax), push);
  44625. }
  44626. seq.push(calcBoundingBox, doAutoMargins);
  44627. if(!opts.skipTitle &&
  44628. !(hasRangeSlider && ax._boundingBox && ax.side === 'bottom')
  44629. ) {
  44630. seq.push(function() { return drawTitle(gd, ax); });
  44631. }
  44632. return Lib.syncOrAsync(seq);
  44633. };
  44634. function getBoundaryVals(ax, vals) {
  44635. var out = [];
  44636. var i;
  44637. // boundaryVals are never used for labels;
  44638. // no need to worry about the other tickTextObj keys
  44639. var _push = function(d, bndIndex) {
  44640. var xb = d.xbnd[bndIndex];
  44641. if(xb !== null) {
  44642. out.push(Lib.extendFlat({}, d, {x: xb}));
  44643. }
  44644. };
  44645. if(vals.length) {
  44646. for(i = 0; i < vals.length; i++) {
  44647. _push(vals[i], 0);
  44648. }
  44649. _push(vals[i - 1], 1);
  44650. }
  44651. return out;
  44652. }
  44653. function getSecondaryLabelVals(ax, vals) {
  44654. var out = [];
  44655. var lookup = {};
  44656. for(var i = 0; i < vals.length; i++) {
  44657. var d = vals[i];
  44658. if(lookup[d.text2]) {
  44659. lookup[d.text2].push(d.x);
  44660. } else {
  44661. lookup[d.text2] = [d.x];
  44662. }
  44663. }
  44664. for(var k in lookup) {
  44665. out.push(tickTextObj(ax, Lib.interp(lookup[k], 0.5), k));
  44666. }
  44667. return out;
  44668. }
  44669. function getDividerVals(ax, vals) {
  44670. var out = [];
  44671. var i, current;
  44672. // never used for labels;
  44673. // no need to worry about the other tickTextObj keys
  44674. var _push = function(d, bndIndex) {
  44675. var xb = d.xbnd[bndIndex];
  44676. if(xb !== null) {
  44677. out.push(Lib.extendFlat({}, d, {x: xb}));
  44678. }
  44679. };
  44680. if(ax.showdividers && vals.length) {
  44681. for(i = 0; i < vals.length; i++) {
  44682. var d = vals[i];
  44683. if(d.text2 !== current) {
  44684. _push(d, 0);
  44685. }
  44686. current = d.text2;
  44687. }
  44688. _push(vals[i - 1], 1);
  44689. }
  44690. return out;
  44691. }
  44692. function getLabelLevelSpan(ax, cls) {
  44693. var axLetter = ax._id.charAt(0);
  44694. var angle = ax._tickAngles[cls] || 0;
  44695. var rad = Lib.deg2rad(angle);
  44696. var sinA = Math.sin(rad);
  44697. var cosA = Math.cos(rad);
  44698. var maxX = 0;
  44699. var maxY = 0;
  44700. // N.B. Drawing.bBox does not take into account rotate transforms
  44701. ax._selections[cls].each(function() {
  44702. var thisLabel = selectTickLabel(this);
  44703. var bb = Drawing.bBox(thisLabel.node());
  44704. var w = bb.width;
  44705. var h = bb.height;
  44706. maxX = Math.max(maxX, cosA * w, sinA * h);
  44707. maxY = Math.max(maxY, sinA * w, cosA * h);
  44708. });
  44709. return {x: maxY, y: maxX}[axLetter];
  44710. }
  44711. /**
  44712. * Which direction do the 'ax.side' values, and free ticks go?
  44713. *
  44714. * @param {object} ax (full) axis object
  44715. * - {string} _id (starting with 'x' or 'y')
  44716. * - {string} side
  44717. * - {string} ticks
  44718. * @return {array} all entries are either -1 or 1
  44719. * - [0]: sign for top/right ticks (i.e. negative SVG direction)
  44720. * - [1]: sign for bottom/left ticks (i.e. positive SVG direction)
  44721. * - [2]: sign for ticks corresponding to 'ax.side'
  44722. * - [3]: sign for ticks mirroring 'ax.side'
  44723. */
  44724. axes.getTickSigns = function(ax) {
  44725. var axLetter = ax._id.charAt(0);
  44726. var sideOpposite = {x: 'top', y: 'right'}[axLetter];
  44727. var main = ax.side === sideOpposite ? 1 : -1;
  44728. var out = [-1, 1, main, -main];
  44729. // then we flip if outside XOR y axis
  44730. if((ax.ticks !== 'inside') === (axLetter === 'x')) {
  44731. out = out.map(function(v) { return -v; });
  44732. }
  44733. return out;
  44734. };
  44735. /**
  44736. * Make axis translate transform function
  44737. *
  44738. * @param {object} ax (full) axis object
  44739. * - {string} _id
  44740. * - {number} _offset
  44741. * - {fn} l2p
  44742. * @return {fn} function of calcTicks items
  44743. */
  44744. axes.makeTransFn = function(ax) {
  44745. var axLetter = ax._id.charAt(0);
  44746. var offset = ax._offset;
  44747. return axLetter === 'x' ?
  44748. function(d) { return 'translate(' + (offset + ax.l2p(d.x)) + ',0)'; } :
  44749. function(d) { return 'translate(0,' + (offset + ax.l2p(d.x)) + ')'; };
  44750. };
  44751. /**
  44752. * Make axis tick path string
  44753. *
  44754. * @param {object} ax (full) axis object
  44755. * - {string} _id
  44756. * - {number} ticklen
  44757. * - {number} linewidth
  44758. * @param {number} shift along direction of ticklen
  44759. * @param {1 or -1} sng tick sign
  44760. * @param {number (optional)} len tick length
  44761. * @return {string}
  44762. */
  44763. axes.makeTickPath = function(ax, shift, sgn, len) {
  44764. len = len !== undefined ? len : ax.ticklen;
  44765. var axLetter = ax._id.charAt(0);
  44766. var pad = (ax.linewidth || 1) / 2;
  44767. return axLetter === 'x' ?
  44768. 'M0,' + (shift + pad * sgn) + 'v' + (len * sgn) :
  44769. 'M' + (shift + pad * sgn) + ',0h' + (len * sgn);
  44770. };
  44771. /**
  44772. * Make axis tick label x, y and anchor functions
  44773. *
  44774. * @param {object} ax (full) axis object
  44775. * - {string} _id
  44776. * - {string} ticks
  44777. * - {number} ticklen
  44778. * - {string} side
  44779. * - {number} linewidth
  44780. * - {number} tickfont.size
  44781. * - {boolean} showline
  44782. * @param {number} shift
  44783. * @param {number} angle [in degrees] ...
  44784. * @return {object}
  44785. * - {fn} labelXFn
  44786. * - {fn} labelYFn
  44787. * - {fn} labelAnchorFn
  44788. * - {number} labelStandoff
  44789. * - {number} labelShift
  44790. */
  44791. axes.makeLabelFns = function(ax, shift, angle) {
  44792. var axLetter = ax._id.charAt(0);
  44793. var pad = (ax.linewidth || 1) / 2;
  44794. var ticksOnOutsideLabels = ax.tickson !== 'boundaries' && ax.ticks === 'outside';
  44795. var labelStandoff = ticksOnOutsideLabels ? ax.ticklen : 0;
  44796. var labelShift = 0;
  44797. if(angle && ax.ticks === 'outside') {
  44798. var rad = Lib.deg2rad(angle);
  44799. labelStandoff = ax.ticklen * Math.cos(rad) + 1;
  44800. labelShift = ax.ticklen * Math.sin(rad);
  44801. }
  44802. if(ax.showticklabels && (ticksOnOutsideLabels || ax.showline)) {
  44803. labelStandoff += 0.2 * ax.tickfont.size;
  44804. }
  44805. // Used in polar angular label x/y functions
  44806. // TODO generalize makeLabelFns so that it just work for angular axes
  44807. var out = {
  44808. labelStandoff: labelStandoff,
  44809. labelShift: labelShift
  44810. };
  44811. var x0, y0, ff, flipIt;
  44812. if(axLetter === 'x') {
  44813. flipIt = ax.side === 'bottom' ? 1 : -1;
  44814. x0 = labelShift * flipIt;
  44815. y0 = shift + (labelStandoff + pad) * flipIt;
  44816. ff = ax.side === 'bottom' ? 1 : -0.2;
  44817. out.labelXFn = function(d) { return d.dx + x0; };
  44818. out.labelYFn = function(d) { return d.dy + y0 + d.fontSize * ff; };
  44819. out.labelAnchorFn = function(a) {
  44820. if(!isNumeric(a) || a === 0 || a === 180) {
  44821. return 'middle';
  44822. }
  44823. return (a * flipIt < 0) ? 'end' : 'start';
  44824. };
  44825. } else if(axLetter === 'y') {
  44826. flipIt = ax.side === 'right' ? 1 : -1;
  44827. x0 = labelStandoff + pad;
  44828. y0 = -labelShift * flipIt;
  44829. ff = Math.abs(ax.tickangle) === 90 ? 0.5 : 0;
  44830. out.labelXFn = function(d) { return d.dx + shift + (x0 + d.fontSize * ff) * flipIt; };
  44831. out.labelYFn = function(d) { return d.dy + y0 + d.fontSize * MID_SHIFT; };
  44832. out.labelAnchorFn = function(a) {
  44833. if(isNumeric(a) && Math.abs(a) === 90) {
  44834. return 'middle';
  44835. }
  44836. return ax.side === 'right' ? 'start' : 'end';
  44837. };
  44838. }
  44839. return out;
  44840. };
  44841. function tickDataFn(d) {
  44842. return [d.text, d.x, d.axInfo, d.font, d.fontSize, d.fontColor].join('_');
  44843. }
  44844. /**
  44845. * Draw axis ticks
  44846. *
  44847. * @param {DOM element} gd
  44848. * @param {object} ax (full) axis object
  44849. * - {string} _id
  44850. * - {string} ticks
  44851. * - {number} linewidth
  44852. * - {string} tickcolor
  44853. * @param {object} opts
  44854. * - {array of object} vals (calcTicks output-like)
  44855. * - {d3 selection} layer
  44856. * - {string or fn} path
  44857. * - {fn} transFn
  44858. * - {boolean} crisp (set to false to unset crisp-edge SVG rendering)
  44859. */
  44860. axes.drawTicks = function(gd, ax, opts) {
  44861. opts = opts || {};
  44862. var cls = ax._id + 'tick';
  44863. var ticks = opts.layer.selectAll('path.' + cls)
  44864. .data(ax.ticks ? opts.vals : [], tickDataFn);
  44865. ticks.exit().remove();
  44866. ticks.enter().append('path')
  44867. .classed(cls, 1)
  44868. .classed('ticks', 1)
  44869. .classed('crisp', opts.crisp !== false)
  44870. .call(Color.stroke, ax.tickcolor)
  44871. .style('stroke-width', Drawing.crispRound(gd, ax.tickwidth, 1) + 'px')
  44872. .attr('d', opts.path);
  44873. ticks.attr('transform', opts.transFn);
  44874. };
  44875. /**
  44876. * Draw axis grid
  44877. *
  44878. * @param {DOM element} gd
  44879. * @param {object} ax (full) axis object
  44880. * - {string} _id
  44881. * - {boolean} showgrid
  44882. * - {string} gridcolor
  44883. * - {string} gridwidth
  44884. * - {boolean} zeroline
  44885. * - {string} type
  44886. * - {string} dtick
  44887. * @param {object} opts
  44888. * - {array of object} vals (calcTicks output-like)
  44889. * - {d3 selection} layer
  44890. * - {object} counterAxis (full axis object corresponding to counter axis)
  44891. * optional - only required if this axis supports zero lines
  44892. * - {string or fn} path
  44893. * - {fn} transFn
  44894. * - {boolean} crisp (set to false to unset crisp-edge SVG rendering)
  44895. */
  44896. axes.drawGrid = function(gd, ax, opts) {
  44897. opts = opts || {};
  44898. var cls = ax._id + 'grid';
  44899. var vals = opts.vals;
  44900. var counterAx = opts.counterAxis;
  44901. if(ax.showgrid === false) {
  44902. vals = [];
  44903. }
  44904. else if(counterAx && axes.shouldShowZeroLine(gd, ax, counterAx)) {
  44905. var isArrayMode = ax.tickmode === 'array';
  44906. for(var i = 0; i < vals.length; i++) {
  44907. var xi = vals[i].x;
  44908. if(isArrayMode ? !xi : (Math.abs(xi) < ax.dtick / 100)) {
  44909. vals = vals.slice(0, i).concat(vals.slice(i + 1));
  44910. // In array mode you can in principle have multiple
  44911. // ticks at 0, so test them all. Otherwise once we found
  44912. // one we can stop.
  44913. if(isArrayMode) i--;
  44914. else break;
  44915. }
  44916. }
  44917. }
  44918. var grid = opts.layer.selectAll('path.' + cls)
  44919. .data(vals, tickDataFn);
  44920. grid.exit().remove();
  44921. grid.enter().append('path')
  44922. .classed(cls, 1)
  44923. .classed('crisp', opts.crisp !== false);
  44924. ax._gw = Drawing.crispRound(gd, ax.gridwidth, 1);
  44925. grid.attr('transform', opts.transFn)
  44926. .attr('d', opts.path)
  44927. .call(Color.stroke, ax.gridcolor || '#ddd')
  44928. .style('stroke-width', ax._gw + 'px');
  44929. if(typeof opts.path === 'function') grid.attr('d', opts.path);
  44930. };
  44931. /**
  44932. * Draw axis zero-line
  44933. *
  44934. * @param {DOM element} gd
  44935. * @param {object} ax (full) axis object
  44936. * - {string} _id
  44937. * - {boolean} zeroline
  44938. * - {number} zerolinewidth
  44939. * - {string} zerolinecolor
  44940. * - {number (optional)} _gridWidthCrispRound
  44941. * @param {object} opts
  44942. * - {d3 selection} layer
  44943. * - {object} counterAxis (full axis object corresponding to counter axis)
  44944. * - {string or fn} path
  44945. * - {fn} transFn
  44946. * - {boolean} crisp (set to false to unset crisp-edge SVG rendering)
  44947. */
  44948. axes.drawZeroLine = function(gd, ax, opts) {
  44949. opts = opts || opts;
  44950. var cls = ax._id + 'zl';
  44951. var show = axes.shouldShowZeroLine(gd, ax, opts.counterAxis);
  44952. var zl = opts.layer.selectAll('path.' + cls)
  44953. .data(show ? [{x: 0, id: ax._id}] : []);
  44954. zl.exit().remove();
  44955. zl.enter().append('path')
  44956. .classed(cls, 1)
  44957. .classed('zl', 1)
  44958. .classed('crisp', opts.crisp !== false)
  44959. .each(function() {
  44960. // use the fact that only one element can enter to trigger a sort.
  44961. // If several zerolines enter at the same time we will sort once per,
  44962. // but generally this should be a minimal overhead.
  44963. opts.layer.selectAll('path').sort(function(da, db) {
  44964. return axisIds.idSort(da.id, db.id);
  44965. });
  44966. });
  44967. zl.attr('transform', opts.transFn)
  44968. .attr('d', opts.path)
  44969. .call(Color.stroke, ax.zerolinecolor || Color.defaultLine)
  44970. .style('stroke-width', Drawing.crispRound(gd, ax.zerolinewidth, ax._gw || 1) + 'px');
  44971. };
  44972. /**
  44973. * Draw axis tick labels
  44974. *
  44975. * @param {DOM element} gd
  44976. * @param {object} ax (full) axis object
  44977. * - {string} _id
  44978. * - {boolean} showticklabels
  44979. * - {number} tickangle
  44980. * - {object (optional)} _selections
  44981. * - {object} (optional)} _tickAngles
  44982. * @param {object} opts
  44983. * - {array of object} vals (calcTicks output-like)
  44984. * - {d3 selection} layer
  44985. * - {string (optional)} cls (node className)
  44986. * - {boolean} repositionOnUpdate (set to true to reposition update selection)
  44987. * - {boolean} secondary
  44988. * - {fn} transFn
  44989. * - {fn} labelXFn
  44990. * - {fn} labelYFn
  44991. * - {fn} labelAnchorFn
  44992. */
  44993. axes.drawLabels = function(gd, ax, opts) {
  44994. opts = opts || {};
  44995. var axId = ax._id;
  44996. var axLetter = axId.charAt(0);
  44997. var cls = opts.cls || axId + 'tick';
  44998. var vals = opts.vals;
  44999. var labelXFn = opts.labelXFn;
  45000. var labelYFn = opts.labelYFn;
  45001. var labelAnchorFn = opts.labelAnchorFn;
  45002. var tickAngle = opts.secondary ? 0 : ax.tickangle;
  45003. var lastAngle = (ax._tickAngles || {})[cls];
  45004. var tickLabels = opts.layer.selectAll('g.' + cls)
  45005. .data(ax.showticklabels ? vals : [], tickDataFn);
  45006. var labelsReady = [];
  45007. tickLabels.enter().append('g')
  45008. .classed(cls, 1)
  45009. .append('text')
  45010. // only so tex has predictable alignment that we can
  45011. // alter later
  45012. .attr('text-anchor', 'middle')
  45013. .each(function(d) {
  45014. var thisLabel = d3.select(this);
  45015. var newPromise = gd._promises.length;
  45016. thisLabel
  45017. .call(svgTextUtils.positionText, labelXFn(d), labelYFn(d))
  45018. .call(Drawing.font, d.font, d.fontSize, d.fontColor)
  45019. .text(d.text)
  45020. .call(svgTextUtils.convertToTspans, gd);
  45021. if(gd._promises[newPromise]) {
  45022. // if we have an async label, we'll deal with that
  45023. // all here so take it out of gd._promises and
  45024. // instead position the label and promise this in
  45025. // labelsReady
  45026. labelsReady.push(gd._promises.pop().then(function() {
  45027. positionLabels(thisLabel, tickAngle);
  45028. }));
  45029. } else {
  45030. // sync label: just position it now.
  45031. positionLabels(thisLabel, tickAngle);
  45032. }
  45033. });
  45034. tickLabels.exit().remove();
  45035. if(opts.repositionOnUpdate) {
  45036. tickLabels.each(function(d) {
  45037. d3.select(this).select('text')
  45038. .call(svgTextUtils.positionText, labelXFn(d), labelYFn(d));
  45039. });
  45040. }
  45041. // How much to shift a multi-line label to center it vertically.
  45042. function getAnchorHeight(lineCount, lineHeight, angle) {
  45043. var h = (lineCount - 1) * lineHeight;
  45044. if(axLetter === 'x') {
  45045. if(angle < -60 || 60 < angle) {
  45046. return -0.5 * h;
  45047. } else if(ax.side === 'top') {
  45048. return -h;
  45049. }
  45050. } else {
  45051. angle *= ax.side === 'left' ? 1 : -1;
  45052. if(angle < -30) {
  45053. return -h;
  45054. } else if(angle < 30) {
  45055. return -0.5 * h;
  45056. }
  45057. }
  45058. return 0;
  45059. }
  45060. function positionLabels(s, angle) {
  45061. s.each(function(d) {
  45062. var thisLabel = d3.select(this);
  45063. var mathjaxGroup = thisLabel.select('.text-math-group');
  45064. var anchor = labelAnchorFn(angle, d);
  45065. var transform = opts.transFn.call(thisLabel.node(), d) +
  45066. ((isNumeric(angle) && +angle !== 0) ?
  45067. (' rotate(' + angle + ',' + labelXFn(d) + ',' +
  45068. (labelYFn(d) - d.fontSize / 2) + ')') :
  45069. '');
  45070. var anchorHeight = getAnchorHeight(
  45071. svgTextUtils.lineCount(thisLabel),
  45072. LINE_SPACING * d.fontSize,
  45073. isNumeric(angle) ? +angle : 0
  45074. );
  45075. if(anchorHeight) {
  45076. transform += ' translate(0, ' + anchorHeight + ')';
  45077. }
  45078. if(mathjaxGroup.empty()) {
  45079. thisLabel.select('text').attr({
  45080. transform: transform,
  45081. 'text-anchor': anchor
  45082. });
  45083. } else {
  45084. var mjWidth = Drawing.bBox(mathjaxGroup.node()).width;
  45085. var mjShift = mjWidth * {end: -0.5, start: 0.5}[anchor];
  45086. mathjaxGroup.attr('transform', transform + (mjShift ? 'translate(' + mjShift + ',0)' : ''));
  45087. }
  45088. });
  45089. }
  45090. // make sure all labels are correctly positioned at their base angle
  45091. // the positionLabels call above is only for newly drawn labels.
  45092. // do this without waiting, using the last calculated angle to
  45093. // minimize flicker, then do it again when we know all labels are
  45094. // there, putting back the prescribed angle to check for overlaps.
  45095. positionLabels(tickLabels, lastAngle || tickAngle);
  45096. function allLabelsReady() {
  45097. return labelsReady.length && Promise.all(labelsReady);
  45098. }
  45099. function fixLabelOverlaps() {
  45100. positionLabels(tickLabels, tickAngle);
  45101. var autoangle = null;
  45102. // check for auto-angling if x labels overlap
  45103. // don't auto-angle at all for log axes with
  45104. // base and digit format
  45105. if(vals.length && axLetter === 'x' && !isNumeric(tickAngle) &&
  45106. (ax.type !== 'log' || String(ax.dtick).charAt(0) !== 'D')
  45107. ) {
  45108. autoangle = 0;
  45109. var maxFontSize = 0;
  45110. var lbbArray = [];
  45111. var i;
  45112. tickLabels.each(function(d) {
  45113. maxFontSize = Math.max(maxFontSize, d.fontSize);
  45114. var x = ax.l2p(d.x);
  45115. var thisLabel = selectTickLabel(this);
  45116. var bb = Drawing.bBox(thisLabel.node());
  45117. lbbArray.push({
  45118. // ignore about y, just deal with x overlaps
  45119. top: 0,
  45120. bottom: 10,
  45121. height: 10,
  45122. left: x - bb.width / 2,
  45123. // impose a 2px gap
  45124. right: x + bb.width / 2 + 2,
  45125. width: bb.width + 2
  45126. });
  45127. });
  45128. if((ax.tickson === 'boundaries' || ax.showdividers) && !opts.secondary) {
  45129. var gap = 2;
  45130. if(ax.ticks) gap += ax.tickwidth / 2;
  45131. // TODO should secondary labels also fall into this fix-overlap regime?
  45132. for(i = 0; i < lbbArray.length; i++) {
  45133. var xbnd = vals[i].xbnd;
  45134. var lbb = lbbArray[i];
  45135. if(
  45136. (xbnd[0] !== null && (lbb.left - ax.l2p(xbnd[0])) < gap) ||
  45137. (xbnd[1] !== null && (ax.l2p(xbnd[1]) - lbb.right) < gap)
  45138. ) {
  45139. autoangle = 90;
  45140. break;
  45141. }
  45142. }
  45143. } else {
  45144. var vLen = vals.length;
  45145. var tickSpacing = Math.abs((vals[vLen - 1].x - vals[0].x) * ax._m) / (vLen - 1);
  45146. var rotate90 = (tickSpacing < maxFontSize * 2.5) || ax.type === 'multicategory';
  45147. // any overlap at all - set 30 degrees or 90 degrees
  45148. for(i = 0; i < lbbArray.length - 1; i++) {
  45149. if(Lib.bBoxIntersect(lbbArray[i], lbbArray[i + 1])) {
  45150. autoangle = rotate90 ? 90 : 30;
  45151. break;
  45152. }
  45153. }
  45154. }
  45155. if(autoangle) {
  45156. positionLabels(tickLabels, autoangle);
  45157. }
  45158. }
  45159. if(ax._tickAngles) {
  45160. ax._tickAngles[cls] = autoangle === null ?
  45161. (isNumeric(tickAngle) ? tickAngle : 0) :
  45162. autoangle;
  45163. }
  45164. }
  45165. if(ax._selections) {
  45166. ax._selections[cls] = tickLabels;
  45167. }
  45168. var done = Lib.syncOrAsync([allLabelsReady, fixLabelOverlaps]);
  45169. if(done && done.then) gd._promises.push(done);
  45170. return done;
  45171. };
  45172. /**
  45173. * Draw axis dividers
  45174. *
  45175. * @param {DOM element} gd
  45176. * @param {object} ax (full) axis object
  45177. * - {string} _id
  45178. * - {string} showdividers
  45179. * - {number} dividerwidth
  45180. * - {string} dividercolor
  45181. * @param {object} opts
  45182. * - {array of object} vals (calcTicks output-like)
  45183. * - {d3 selection} layer
  45184. * - {fn} path
  45185. * - {fn} transFn
  45186. */
  45187. function drawDividers(gd, ax, opts) {
  45188. var cls = ax._id + 'divider';
  45189. var vals = opts.vals;
  45190. var dividers = opts.layer.selectAll('path.' + cls)
  45191. .data(vals, tickDataFn);
  45192. dividers.exit().remove();
  45193. dividers.enter().insert('path', ':first-child')
  45194. .classed(cls, 1)
  45195. .classed('crisp', 1)
  45196. .call(Color.stroke, ax.dividercolor)
  45197. .style('stroke-width', Drawing.crispRound(gd, ax.dividerwidth, 1) + 'px');
  45198. dividers
  45199. .attr('transform', opts.transFn)
  45200. .attr('d', opts.path);
  45201. }
  45202. function drawTitle(gd, ax) {
  45203. var fullLayout = gd._fullLayout;
  45204. var axId = ax._id;
  45205. var axLetter = axId.charAt(0);
  45206. var gs = fullLayout._size;
  45207. var fontSize = ax.title.font.size;
  45208. var titleStandoff;
  45209. if(ax.type === 'multicategory') {
  45210. titleStandoff = ax._labelLength;
  45211. } else {
  45212. var offsetBase = 1.5;
  45213. titleStandoff = 10 + fontSize * offsetBase + (ax.linewidth ? ax.linewidth - 1 : 0);
  45214. }
  45215. var transform, counterAxis, x, y;
  45216. if(axLetter === 'x') {
  45217. counterAxis = (ax.anchor === 'free') ?
  45218. {_offset: gs.t + (1 - (ax.position || 0)) * gs.h, _length: 0} :
  45219. axisIds.getFromId(gd, ax.anchor);
  45220. x = ax._offset + ax._length / 2;
  45221. if(ax.side === 'top') {
  45222. y = -titleStandoff - fontSize * (ax.showticklabels ? 1 : 0);
  45223. } else {
  45224. y = counterAxis._length + titleStandoff +
  45225. fontSize * (ax.showticklabels ? 1.5 : 0.5);
  45226. }
  45227. y += counterAxis._offset;
  45228. } else {
  45229. counterAxis = (ax.anchor === 'free') ?
  45230. {_offset: gs.l + (ax.position || 0) * gs.w, _length: 0} :
  45231. axisIds.getFromId(gd, ax.anchor);
  45232. y = ax._offset + ax._length / 2;
  45233. if(ax.side === 'right') {
  45234. x = counterAxis._length + titleStandoff +
  45235. fontSize * (ax.showticklabels ? 1 : 0.5);
  45236. } else {
  45237. x = -titleStandoff - fontSize * (ax.showticklabels ? 0.5 : 0);
  45238. }
  45239. x += counterAxis._offset;
  45240. transform = {rotate: '-90', offset: 0};
  45241. }
  45242. var avoid;
  45243. if(ax.type !== 'multicategory') {
  45244. var tickLabels = ax._selections[ax._id + 'tick'];
  45245. avoid = {
  45246. selection: tickLabels,
  45247. side: ax.side
  45248. };
  45249. if(tickLabels && tickLabels.node() && tickLabels.node().parentNode) {
  45250. var translation = Drawing.getTranslate(tickLabels.node().parentNode);
  45251. avoid.offsetLeft = translation.x;
  45252. avoid.offsetTop = translation.y;
  45253. }
  45254. }
  45255. return Titles.draw(gd, axId + 'title', {
  45256. propContainer: ax,
  45257. propName: ax._name + '.title.text',
  45258. placeholder: fullLayout._dfltTitle[axLetter],
  45259. avoid: avoid,
  45260. transform: transform,
  45261. attributes: {x: x, y: y, 'text-anchor': 'middle'}
  45262. });
  45263. }
  45264. axes.shouldShowZeroLine = function(gd, ax, counterAxis) {
  45265. var rng = Lib.simpleMap(ax.range, ax.r2l);
  45266. return (
  45267. (rng[0] * rng[1] <= 0) &&
  45268. ax.zeroline &&
  45269. (ax.type === 'linear' || ax.type === '-') &&
  45270. ax._gridVals.length &&
  45271. (
  45272. clipEnds(ax, 0) ||
  45273. !anyCounterAxLineAtZero(gd, ax, counterAxis, rng) ||
  45274. hasBarsOrFill(gd, ax)
  45275. )
  45276. );
  45277. };
  45278. axes.clipEnds = function(ax, vals) {
  45279. return vals.filter(function(d) { return clipEnds(ax, d.x); });
  45280. };
  45281. function clipEnds(ax, l) {
  45282. var p = ax.l2p(l);
  45283. return (p > 1 && p < ax._length - 1);
  45284. }
  45285. function anyCounterAxLineAtZero(gd, ax, counterAxis, rng) {
  45286. var mainCounterAxis = counterAxis._mainAxis;
  45287. if(!mainCounterAxis) return;
  45288. var fullLayout = gd._fullLayout;
  45289. var axLetter = ax._id.charAt(0);
  45290. var counterLetter = axes.counterLetter(ax._id);
  45291. var zeroPosition = ax._offset + (
  45292. ((Math.abs(rng[0]) < Math.abs(rng[1])) === (axLetter === 'x')) ?
  45293. 0 : ax._length
  45294. );
  45295. function lineNearZero(ax2) {
  45296. if(!ax2.showline || !ax2.linewidth) return false;
  45297. var tolerance = Math.max((ax2.linewidth + ax.zerolinewidth) / 2, 1);
  45298. function closeEnough(pos2) {
  45299. return typeof pos2 === 'number' && Math.abs(pos2 - zeroPosition) < tolerance;
  45300. }
  45301. if(closeEnough(ax2._mainLinePosition) || closeEnough(ax2._mainMirrorPosition)) {
  45302. return true;
  45303. }
  45304. var linePositions = ax2._linepositions || {};
  45305. for(var k in linePositions) {
  45306. if(closeEnough(linePositions[k][0]) || closeEnough(linePositions[k][1])) {
  45307. return true;
  45308. }
  45309. }
  45310. }
  45311. var plotinfo = fullLayout._plots[counterAxis._mainSubplot];
  45312. if(!(plotinfo.mainplotinfo || plotinfo).overlays.length) {
  45313. return lineNearZero(counterAxis, zeroPosition);
  45314. }
  45315. var counterLetterAxes = axes.list(gd, counterLetter);
  45316. for(var i = 0; i < counterLetterAxes.length; i++) {
  45317. var counterAxis2 = counterLetterAxes[i];
  45318. if(
  45319. counterAxis2._mainAxis === mainCounterAxis &&
  45320. lineNearZero(counterAxis2, zeroPosition)
  45321. ) {
  45322. return true;
  45323. }
  45324. }
  45325. }
  45326. function hasBarsOrFill(gd, ax) {
  45327. var fullData = gd._fullData;
  45328. var subplot = ax._mainSubplot;
  45329. var axLetter = ax._id.charAt(0);
  45330. for(var i = 0; i < fullData.length; i++) {
  45331. var trace = fullData[i];
  45332. if(trace.visible === true &&
  45333. (trace.xaxis + trace.yaxis) === subplot &&
  45334. (
  45335. Registry.traceIs(trace, 'bar') && trace.orientation === {x: 'h', y: 'v'}[axLetter] ||
  45336. trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter
  45337. )
  45338. ) {
  45339. return true;
  45340. }
  45341. }
  45342. return false;
  45343. }
  45344. function selectTickLabel(gTick) {
  45345. var s = d3.select(gTick);
  45346. var mj = s.select('.text-math-group');
  45347. return mj.empty() ? s.select('text') : mj;
  45348. }
  45349. /**
  45350. * Find all margin pushers for 2D axes and reserve them for later use
  45351. * Both label and rangeslider automargin calculations happen later so
  45352. * we need to explicitly allow their ids in order to not delete them.
  45353. *
  45354. * TODO: can we pull the actual automargin calls forward to avoid this hack?
  45355. * We're probably also doing multiple redraws in this case, would be faster
  45356. * if we can just do the whole calculation ahead of time and draw once.
  45357. */
  45358. axes.allowAutoMargin = function(gd) {
  45359. var axList = axes.list(gd, '', true);
  45360. for(var i = 0; i < axList.length; i++) {
  45361. var ax = axList[i];
  45362. if(ax.automargin) {
  45363. Plots.allowAutoMargin(gd, axAutoMarginID(ax));
  45364. }
  45365. if(Registry.getComponentMethod('rangeslider', 'isVisible')(ax)) {
  45366. Plots.allowAutoMargin(gd, rangeSliderAutoMarginID(ax));
  45367. }
  45368. }
  45369. };
  45370. function axAutoMarginID(ax) { return ax._id + '.automargin'; }
  45371. function rangeSliderAutoMarginID(ax) { return ax._id + '.rangeslider'; }
  45372. // swap all the presentation attributes of the axes showing these traces
  45373. axes.swap = function(gd, traces) {
  45374. var axGroups = makeAxisGroups(gd, traces);
  45375. for(var i = 0; i < axGroups.length; i++) {
  45376. swapAxisGroup(gd, axGroups[i].x, axGroups[i].y);
  45377. }
  45378. };
  45379. function makeAxisGroups(gd, traces) {
  45380. var groups = [];
  45381. var i, j;
  45382. for(i = 0; i < traces.length; i++) {
  45383. var groupsi = [];
  45384. var xi = gd._fullData[traces[i]].xaxis;
  45385. var yi = gd._fullData[traces[i]].yaxis;
  45386. if(!xi || !yi) continue; // not a 2D cartesian trace?
  45387. for(j = 0; j < groups.length; j++) {
  45388. if(groups[j].x.indexOf(xi) !== -1 || groups[j].y.indexOf(yi) !== -1) {
  45389. groupsi.push(j);
  45390. }
  45391. }
  45392. if(!groupsi.length) {
  45393. groups.push({x: [xi], y: [yi]});
  45394. continue;
  45395. }
  45396. var group0 = groups[groupsi[0]];
  45397. var groupj;
  45398. if(groupsi.length > 1) {
  45399. for(j = 1; j < groupsi.length; j++) {
  45400. groupj = groups[groupsi[j]];
  45401. mergeAxisGroups(group0.x, groupj.x);
  45402. mergeAxisGroups(group0.y, groupj.y);
  45403. }
  45404. }
  45405. mergeAxisGroups(group0.x, [xi]);
  45406. mergeAxisGroups(group0.y, [yi]);
  45407. }
  45408. return groups;
  45409. }
  45410. function mergeAxisGroups(intoSet, fromSet) {
  45411. for(var i = 0; i < fromSet.length; i++) {
  45412. if(intoSet.indexOf(fromSet[i]) === -1) intoSet.push(fromSet[i]);
  45413. }
  45414. }
  45415. function swapAxisGroup(gd, xIds, yIds) {
  45416. var xFullAxes = [];
  45417. var yFullAxes = [];
  45418. var layout = gd.layout;
  45419. var i, j;
  45420. for(i = 0; i < xIds.length; i++) xFullAxes.push(axes.getFromId(gd, xIds[i]));
  45421. for(i = 0; i < yIds.length; i++) yFullAxes.push(axes.getFromId(gd, yIds[i]));
  45422. var allAxKeys = Object.keys(axAttrs);
  45423. var noSwapAttrs = [
  45424. 'anchor', 'domain', 'overlaying', 'position', 'side', 'tickangle', 'editType'
  45425. ];
  45426. var numericTypes = ['linear', 'log'];
  45427. for(i = 0; i < allAxKeys.length; i++) {
  45428. var keyi = allAxKeys[i];
  45429. var xVal = xFullAxes[0][keyi];
  45430. var yVal = yFullAxes[0][keyi];
  45431. var allEqual = true;
  45432. var coerceLinearX = false;
  45433. var coerceLinearY = false;
  45434. if(keyi.charAt(0) === '_' || typeof xVal === 'function' ||
  45435. noSwapAttrs.indexOf(keyi) !== -1) {
  45436. continue;
  45437. }
  45438. for(j = 1; j < xFullAxes.length && allEqual; j++) {
  45439. var xVali = xFullAxes[j][keyi];
  45440. if(keyi === 'type' && numericTypes.indexOf(xVal) !== -1 &&
  45441. numericTypes.indexOf(xVali) !== -1 && xVal !== xVali) {
  45442. // type is special - if we find a mixture of linear and log,
  45443. // coerce them all to linear on flipping
  45444. coerceLinearX = true;
  45445. }
  45446. else if(xVali !== xVal) allEqual = false;
  45447. }
  45448. for(j = 1; j < yFullAxes.length && allEqual; j++) {
  45449. var yVali = yFullAxes[j][keyi];
  45450. if(keyi === 'type' && numericTypes.indexOf(yVal) !== -1 &&
  45451. numericTypes.indexOf(yVali) !== -1 && yVal !== yVali) {
  45452. // type is special - if we find a mixture of linear and log,
  45453. // coerce them all to linear on flipping
  45454. coerceLinearY = true;
  45455. }
  45456. else if(yFullAxes[j][keyi] !== yVal) allEqual = false;
  45457. }
  45458. if(allEqual) {
  45459. if(coerceLinearX) layout[xFullAxes[0]._name].type = 'linear';
  45460. if(coerceLinearY) layout[yFullAxes[0]._name].type = 'linear';
  45461. swapAxisAttrs(layout, keyi, xFullAxes, yFullAxes, gd._fullLayout._dfltTitle);
  45462. }
  45463. }
  45464. // now swap x&y for any annotations anchored to these x & y
  45465. for(i = 0; i < gd._fullLayout.annotations.length; i++) {
  45466. var ann = gd._fullLayout.annotations[i];
  45467. if(xIds.indexOf(ann.xref) !== -1 &&
  45468. yIds.indexOf(ann.yref) !== -1) {
  45469. Lib.swapAttrs(layout.annotations[i], ['?']);
  45470. }
  45471. }
  45472. }
  45473. function swapAxisAttrs(layout, key, xFullAxes, yFullAxes, dfltTitle) {
  45474. // in case the value is the default for either axis,
  45475. // look at the first axis in each list and see if
  45476. // this key's value is undefined
  45477. var np = Lib.nestedProperty;
  45478. var xVal = np(layout[xFullAxes[0]._name], key).get();
  45479. var yVal = np(layout[yFullAxes[0]._name], key).get();
  45480. var i;
  45481. if(key === 'title') {
  45482. // special handling of placeholder titles
  45483. if(xVal && xVal.text === dfltTitle.x) {
  45484. xVal.text = dfltTitle.y;
  45485. }
  45486. if(yVal && yVal.text === dfltTitle.y) {
  45487. yVal.text = dfltTitle.x;
  45488. }
  45489. }
  45490. for(i = 0; i < xFullAxes.length; i++) {
  45491. np(layout, xFullAxes[i]._name + '.' + key).set(yVal);
  45492. }
  45493. for(i = 0; i < yFullAxes.length; i++) {
  45494. np(layout, yFullAxes[i]._name + '.' + key).set(xVal);
  45495. }
  45496. }
  45497. function isAngular(ax) {
  45498. return ax._id === 'angularaxis';
  45499. }
  45500. },{"../../components/color":51,"../../components/drawing":72,"../../components/titles":139,"../../constants/alignment":146,"../../constants/numerical":149,"../../lib":168,"../../lib/svg_text_utils":189,"../../plots/plots":245,"../../registry":257,"./autorange":211,"./axis_autotype":213,"./axis_ids":215,"./clean_ticks":217,"./layout_attributes":225,"./set_convert":231,"d3":16,"fast-isnumeric":18}],213:[function(_dereq_,module,exports){
  45501. /**
  45502. * Copyright 2012-2019, Plotly, Inc.
  45503. * All rights reserved.
  45504. *
  45505. * This source code is licensed under the MIT license found in the
  45506. * LICENSE file in the root directory of this source tree.
  45507. */
  45508. 'use strict';
  45509. var isNumeric = _dereq_('fast-isnumeric');
  45510. var Lib = _dereq_('../../lib');
  45511. var BADNUM = _dereq_('../../constants/numerical').BADNUM;
  45512. module.exports = function autoType(array, calendar, opts) {
  45513. opts = opts || {};
  45514. if(!opts.noMultiCategory && multiCategory(array)) return 'multicategory';
  45515. if(moreDates(array, calendar)) return 'date';
  45516. if(category(array)) return 'category';
  45517. if(linearOK(array)) return 'linear';
  45518. else return '-';
  45519. };
  45520. // is there at least one number in array? If not, we should leave
  45521. // ax.type empty so it can be autoset later
  45522. function linearOK(array) {
  45523. if(!array) return false;
  45524. for(var i = 0; i < array.length; i++) {
  45525. if(isNumeric(array[i])) return true;
  45526. }
  45527. return false;
  45528. }
  45529. // does the array a have mostly dates rather than numbers?
  45530. // note: some values can be neither (such as blanks, text)
  45531. // 2- or 4-digit integers can be both, so require twice as many
  45532. // dates as non-dates, to exclude cases with mostly 2 & 4 digit
  45533. // numbers and a few dates
  45534. // as with categories, consider DISTINCT values only.
  45535. function moreDates(a, calendar) {
  45536. // test at most 1000 points, evenly spaced
  45537. var inc = Math.max(1, (a.length - 1) / 1000);
  45538. var dcnt = 0;
  45539. var ncnt = 0;
  45540. var seen = {};
  45541. for(var i = 0; i < a.length; i += inc) {
  45542. var ai = a[Math.round(i)];
  45543. var stri = String(ai);
  45544. if(seen[stri]) continue;
  45545. seen[stri] = 1;
  45546. if(Lib.isDateTime(ai, calendar)) dcnt += 1;
  45547. if(isNumeric(ai)) ncnt += 1;
  45548. }
  45549. return (dcnt > ncnt * 2);
  45550. }
  45551. // are the (x,y)-values in gd.data mostly text?
  45552. // require twice as many DISTINCT categories as distinct numbers
  45553. function category(a) {
  45554. // test at most 1000 points
  45555. var inc = Math.max(1, (a.length - 1) / 1000);
  45556. var curvenums = 0;
  45557. var curvecats = 0;
  45558. var seen = {};
  45559. for(var i = 0; i < a.length; i += inc) {
  45560. var ai = a[Math.round(i)];
  45561. var stri = String(ai);
  45562. if(seen[stri]) continue;
  45563. seen[stri] = 1;
  45564. if(typeof ai === 'boolean') curvecats++;
  45565. else if(Lib.cleanNumber(ai) !== BADNUM) curvenums++;
  45566. else if(typeof ai === 'string') curvecats++;
  45567. }
  45568. return curvecats > curvenums * 2;
  45569. }
  45570. // very-loose requirements for multicategory,
  45571. // trace modules that should never auto-type to multicategory
  45572. // should be declared with 'noMultiCategory'
  45573. function multiCategory(a) {
  45574. return Lib.isArrayOrTypedArray(a[0]) && Lib.isArrayOrTypedArray(a[1]);
  45575. }
  45576. },{"../../constants/numerical":149,"../../lib":168,"fast-isnumeric":18}],214:[function(_dereq_,module,exports){
  45577. /**
  45578. * Copyright 2012-2019, Plotly, Inc.
  45579. * All rights reserved.
  45580. *
  45581. * This source code is licensed under the MIT license found in the
  45582. * LICENSE file in the root directory of this source tree.
  45583. */
  45584. 'use strict';
  45585. var Registry = _dereq_('../../registry');
  45586. var Lib = _dereq_('../../lib');
  45587. var layoutAttributes = _dereq_('./layout_attributes');
  45588. var handleTickValueDefaults = _dereq_('./tick_value_defaults');
  45589. var handleTickMarkDefaults = _dereq_('./tick_mark_defaults');
  45590. var handleTickLabelDefaults = _dereq_('./tick_label_defaults');
  45591. var handleCategoryOrderDefaults = _dereq_('./category_order_defaults');
  45592. var handleLineGridDefaults = _dereq_('./line_grid_defaults');
  45593. var setConvert = _dereq_('./set_convert');
  45594. /**
  45595. * options: object containing:
  45596. *
  45597. * letter: 'x' or 'y'
  45598. * title: name of the axis (ie 'Colorbar') to go in default title
  45599. * font: the default font to inherit
  45600. * outerTicks: boolean, should ticks default to outside?
  45601. * showGrid: boolean, should gridlines be shown by default?
  45602. * noHover: boolean, this axis doesn't support hover effects?
  45603. * noTickson: boolean, this axis doesn't support 'tickson'
  45604. * data: the plot data, used to manage categories
  45605. * bgColor: the plot background color, to calculate default gridline colors
  45606. */
  45607. module.exports = function handleAxisDefaults(containerIn, containerOut, coerce, options, layoutOut) {
  45608. var letter = options.letter;
  45609. var font = options.font || {};
  45610. var splomStash = options.splomStash || {};
  45611. var visible = coerce('visible', !options.cheateronly);
  45612. var axType = containerOut.type;
  45613. if(axType === 'date') {
  45614. var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleDefaults');
  45615. handleCalendarDefaults(containerIn, containerOut, 'calendar', options.calendar);
  45616. }
  45617. setConvert(containerOut, layoutOut);
  45618. var autoRange = coerce('autorange', !containerOut.isValidRange(containerIn.range));
  45619. if(autoRange && (axType === 'linear' || axType === '-')) coerce('rangemode');
  45620. coerce('range');
  45621. containerOut.cleanRange();
  45622. handleCategoryOrderDefaults(containerIn, containerOut, coerce, options);
  45623. if(axType !== 'category' && !options.noHover) coerce('hoverformat');
  45624. if(!visible) return containerOut;
  45625. var dfltColor = coerce('color');
  45626. // if axis.color was provided, use it for fonts too; otherwise,
  45627. // inherit from global font color in case that was provided.
  45628. // Compare to dflt rather than to containerIn, so we can provide color via
  45629. // template too.
  45630. var dfltFontColor = (dfltColor !== layoutAttributes.color.dflt) ? dfltColor : font.color;
  45631. // try to get default title from splom trace, fallback to graph-wide value
  45632. var dfltTitle = splomStash.label || layoutOut._dfltTitle[letter];
  45633. coerce('title.text', dfltTitle);
  45634. Lib.coerceFont(coerce, 'title.font', {
  45635. family: font.family,
  45636. size: Math.round(font.size * 1.2),
  45637. color: dfltFontColor
  45638. });
  45639. handleTickValueDefaults(containerIn, containerOut, coerce, axType);
  45640. handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options);
  45641. handleTickMarkDefaults(containerIn, containerOut, coerce, options);
  45642. handleLineGridDefaults(containerIn, containerOut, coerce, {
  45643. dfltColor: dfltColor,
  45644. bgColor: options.bgColor,
  45645. showGrid: options.showGrid,
  45646. attributes: layoutAttributes
  45647. });
  45648. if(containerOut.showline || containerOut.ticks) coerce('mirror');
  45649. if(options.automargin) coerce('automargin');
  45650. var isMultiCategory = containerOut.type === 'multicategory';
  45651. if(!options.noTickson &&
  45652. (containerOut.type === 'category' || isMultiCategory) &&
  45653. (containerOut.ticks || containerOut.showgrid)
  45654. ) {
  45655. var ticksonDflt;
  45656. if(isMultiCategory) ticksonDflt = 'boundaries';
  45657. coerce('tickson', ticksonDflt);
  45658. }
  45659. if(isMultiCategory) {
  45660. var showDividers = coerce('showdividers');
  45661. if(showDividers) {
  45662. coerce('dividercolor');
  45663. coerce('dividerwidth');
  45664. }
  45665. }
  45666. return containerOut;
  45667. };
  45668. },{"../../lib":168,"../../registry":257,"./category_order_defaults":216,"./layout_attributes":225,"./line_grid_defaults":227,"./set_convert":231,"./tick_label_defaults":232,"./tick_mark_defaults":233,"./tick_value_defaults":234}],215:[function(_dereq_,module,exports){
  45669. /**
  45670. * Copyright 2012-2019, Plotly, Inc.
  45671. * All rights reserved.
  45672. *
  45673. * This source code is licensed under the MIT license found in the
  45674. * LICENSE file in the root directory of this source tree.
  45675. */
  45676. 'use strict';
  45677. var Registry = _dereq_('../../registry');
  45678. var constants = _dereq_('./constants');
  45679. // convert between axis names (xaxis, xaxis2, etc, elements of gd.layout)
  45680. // and axis id's (x, x2, etc). Would probably have ditched 'xaxis'
  45681. // completely in favor of just 'x' if it weren't ingrained in the API etc.
  45682. exports.id2name = function id2name(id) {
  45683. if(typeof id !== 'string' || !id.match(constants.AX_ID_PATTERN)) return;
  45684. var axNum = id.substr(1);
  45685. if(axNum === '1') axNum = '';
  45686. return id.charAt(0) + 'axis' + axNum;
  45687. };
  45688. exports.name2id = function name2id(name) {
  45689. if(!name.match(constants.AX_NAME_PATTERN)) return;
  45690. var axNum = name.substr(5);
  45691. if(axNum === '1') axNum = '';
  45692. return name.charAt(0) + axNum;
  45693. };
  45694. exports.cleanId = function cleanId(id, axLetter) {
  45695. if(!id.match(constants.AX_ID_PATTERN)) return;
  45696. if(axLetter && id.charAt(0) !== axLetter) return;
  45697. var axNum = id.substr(1).replace(/^0+/, '');
  45698. if(axNum === '1') axNum = '';
  45699. return id.charAt(0) + axNum;
  45700. };
  45701. // get all axis objects, as restricted in listNames
  45702. exports.list = function(gd, axLetter, only2d) {
  45703. var fullLayout = gd._fullLayout;
  45704. if(!fullLayout) return [];
  45705. var idList = exports.listIds(gd, axLetter);
  45706. var out = new Array(idList.length);
  45707. var i;
  45708. for(i = 0; i < idList.length; i++) {
  45709. var idi = idList[i];
  45710. out[i] = fullLayout[idi.charAt(0) + 'axis' + idi.substr(1)];
  45711. }
  45712. if(!only2d) {
  45713. var sceneIds3D = fullLayout._subplots.gl3d || [];
  45714. for(i = 0; i < sceneIds3D.length; i++) {
  45715. var scene = fullLayout[sceneIds3D[i]];
  45716. if(axLetter) out.push(scene[axLetter + 'axis']);
  45717. else out.push(scene.xaxis, scene.yaxis, scene.zaxis);
  45718. }
  45719. }
  45720. return out;
  45721. };
  45722. // get all axis ids, optionally restricted by letter
  45723. // this only makes sense for 2d axes
  45724. exports.listIds = function(gd, axLetter) {
  45725. var fullLayout = gd._fullLayout;
  45726. if(!fullLayout) return [];
  45727. var subplotLists = fullLayout._subplots;
  45728. if(axLetter) return subplotLists[axLetter + 'axis'];
  45729. return subplotLists.xaxis.concat(subplotLists.yaxis);
  45730. };
  45731. // get an axis object from its id 'x','x2' etc
  45732. // optionally, id can be a subplot (ie 'x2y3') and type gets x or y from it
  45733. exports.getFromId = function(gd, id, type) {
  45734. var fullLayout = gd._fullLayout;
  45735. if(type === 'x') id = id.replace(/y[0-9]*/, '');
  45736. else if(type === 'y') id = id.replace(/x[0-9]*/, '');
  45737. return fullLayout[exports.id2name(id)];
  45738. };
  45739. // get an axis object of specified type from the containing trace
  45740. exports.getFromTrace = function(gd, fullTrace, type) {
  45741. var fullLayout = gd._fullLayout;
  45742. var ax = null;
  45743. if(Registry.traceIs(fullTrace, 'gl3d')) {
  45744. var scene = fullTrace.scene;
  45745. if(scene.substr(0, 5) === 'scene') {
  45746. ax = fullLayout[scene][type + 'axis'];
  45747. }
  45748. }
  45749. else {
  45750. ax = exports.getFromId(gd, fullTrace[type + 'axis'] || type);
  45751. }
  45752. return ax;
  45753. };
  45754. // sort x, x2, x10, y, y2, y10...
  45755. exports.idSort = function(id1, id2) {
  45756. var letter1 = id1.charAt(0);
  45757. var letter2 = id2.charAt(0);
  45758. if(letter1 !== letter2) return letter1 > letter2 ? 1 : -1;
  45759. return +(id1.substr(1) || 1) - +(id2.substr(1) || 1);
  45760. };
  45761. },{"../../registry":257,"./constants":218}],216:[function(_dereq_,module,exports){
  45762. /**
  45763. * Copyright 2012-2019, Plotly, Inc.
  45764. * All rights reserved.
  45765. *
  45766. * This source code is licensed under the MIT license found in the
  45767. * LICENSE file in the root directory of this source tree.
  45768. */
  45769. 'use strict';
  45770. function findCategories(ax, opts) {
  45771. var dataAttr = opts.dataAttr || ax._id.charAt(0);
  45772. var lookup = {};
  45773. var axData;
  45774. var i, j;
  45775. if(opts.axData) {
  45776. // non-x/y case
  45777. axData = opts.axData;
  45778. } else {
  45779. // x/y case
  45780. axData = [];
  45781. for(i = 0; i < opts.data.length; i++) {
  45782. var trace = opts.data[i];
  45783. if(trace[dataAttr + 'axis'] === ax._id) {
  45784. axData.push(trace);
  45785. }
  45786. }
  45787. }
  45788. for(i = 0; i < axData.length; i++) {
  45789. var vals = axData[i][dataAttr];
  45790. for(j = 0; j < vals.length; j++) {
  45791. var v = vals[j];
  45792. if(v !== null && v !== undefined) {
  45793. lookup[v] = 1;
  45794. }
  45795. }
  45796. }
  45797. return Object.keys(lookup);
  45798. }
  45799. /**
  45800. * Fills in category* default and initial categories.
  45801. *
  45802. * @param {object} containerIn : input axis object
  45803. * @param {object} containerOut : full axis object
  45804. * @param {function} coerce : Lib.coerce fn wrapper
  45805. * @param {object} opts :
  45806. * - data {array} : (full) data trace
  45807. * OR
  45808. * - axData {array} : (full) data associated with axis being coerced here
  45809. * - dataAttr {string} : attribute name corresponding to coordinate array
  45810. */
  45811. module.exports = function handleCategoryOrderDefaults(containerIn, containerOut, coerce, opts) {
  45812. if(containerOut.type !== 'category') return;
  45813. var arrayIn = containerIn.categoryarray;
  45814. var isValidArray = (Array.isArray(arrayIn) && arrayIn.length > 0);
  45815. // override default 'categoryorder' value when non-empty array is supplied
  45816. var orderDefault;
  45817. if(isValidArray) orderDefault = 'array';
  45818. var order = coerce('categoryorder', orderDefault);
  45819. var array;
  45820. // coerce 'categoryarray' only in array order case
  45821. if(order === 'array') {
  45822. array = coerce('categoryarray');
  45823. }
  45824. // cannot set 'categoryorder' to 'array' with an invalid 'categoryarray'
  45825. if(!isValidArray && order === 'array') {
  45826. order = containerOut.categoryorder = 'trace';
  45827. }
  45828. // set up things for makeCalcdata
  45829. if(order === 'trace') {
  45830. containerOut._initialCategories = [];
  45831. } else if(order === 'array') {
  45832. containerOut._initialCategories = array.slice();
  45833. } else {
  45834. array = findCategories(containerOut, opts).sort();
  45835. if(order === 'category ascending') {
  45836. containerOut._initialCategories = array;
  45837. } else if(order === 'category descending') {
  45838. containerOut._initialCategories = array.reverse();
  45839. }
  45840. }
  45841. };
  45842. },{}],217:[function(_dereq_,module,exports){
  45843. /**
  45844. * Copyright 2012-2019, Plotly, Inc.
  45845. * All rights reserved.
  45846. *
  45847. * This source code is licensed under the MIT license found in the
  45848. * LICENSE file in the root directory of this source tree.
  45849. */
  45850. 'use strict';
  45851. var isNumeric = _dereq_('fast-isnumeric');
  45852. var Lib = _dereq_('../../lib');
  45853. var ONEDAY = _dereq_('../../constants/numerical').ONEDAY;
  45854. /**
  45855. * Return a validated dtick value for this axis
  45856. *
  45857. * @param {any} dtick: the candidate dtick. valid values are numbers and strings,
  45858. * and further constrained depending on the axis type.
  45859. * @param {string} axType: the axis type
  45860. */
  45861. exports.dtick = function(dtick, axType) {
  45862. var isLog = axType === 'log';
  45863. var isDate = axType === 'date';
  45864. var isCat = axType === 'category';
  45865. var dtickDflt = isDate ? ONEDAY : 1;
  45866. if(!dtick) return dtickDflt;
  45867. if(isNumeric(dtick)) {
  45868. dtick = Number(dtick);
  45869. if(dtick <= 0) return dtickDflt;
  45870. if(isCat) {
  45871. // category dtick must be positive integers
  45872. return Math.max(1, Math.round(dtick));
  45873. }
  45874. if(isDate) {
  45875. // date dtick must be at least 0.1ms (our current precision)
  45876. return Math.max(0.1, dtick);
  45877. }
  45878. return dtick;
  45879. }
  45880. if(typeof dtick !== 'string' || !(isDate || isLog)) {
  45881. return dtickDflt;
  45882. }
  45883. var prefix = dtick.charAt(0);
  45884. var dtickNum = dtick.substr(1);
  45885. dtickNum = isNumeric(dtickNum) ? Number(dtickNum) : 0;
  45886. if((dtickNum <= 0) || !(
  45887. // "M<n>" gives ticks every (integer) n months
  45888. (isDate && prefix === 'M' && dtickNum === Math.round(dtickNum)) ||
  45889. // "L<f>" gives ticks linearly spaced in data (not in position) every (float) f
  45890. (isLog && prefix === 'L') ||
  45891. // "D1" gives powers of 10 with all small digits between, "D2" gives only 2 and 5
  45892. (isLog && prefix === 'D' && (dtickNum === 1 || dtickNum === 2))
  45893. )) {
  45894. return dtickDflt;
  45895. }
  45896. return dtick;
  45897. };
  45898. /**
  45899. * Return a validated tick0 for this axis
  45900. *
  45901. * @param {any} tick0: the candidate tick0. Valid values are numbers and strings,
  45902. * further constrained depending on the axis type
  45903. * @param {string} axType: the axis type
  45904. * @param {string} calendar: for date axes, the calendar to validate/convert with
  45905. * @param {any} dtick: an already valid dtick. Only used for D1 and D2 log dticks,
  45906. * which do not support tick0 at all.
  45907. */
  45908. exports.tick0 = function(tick0, axType, calendar, dtick) {
  45909. if(axType === 'date') {
  45910. return Lib.cleanDate(tick0, Lib.dateTick0(calendar));
  45911. }
  45912. if(dtick === 'D1' || dtick === 'D2') {
  45913. // D1 and D2 modes ignore tick0 entirely
  45914. return undefined;
  45915. }
  45916. // Aside from date axes, tick0 must be numeric
  45917. return isNumeric(tick0) ? Number(tick0) : 0;
  45918. };
  45919. },{"../../constants/numerical":149,"../../lib":168,"fast-isnumeric":18}],218:[function(_dereq_,module,exports){
  45920. /**
  45921. * Copyright 2012-2019, Plotly, Inc.
  45922. * All rights reserved.
  45923. *
  45924. * This source code is licensed under the MIT license found in the
  45925. * LICENSE file in the root directory of this source tree.
  45926. */
  45927. 'use strict';
  45928. var counterRegex = _dereq_('../../lib/regex').counter;
  45929. module.exports = {
  45930. idRegex: {
  45931. x: counterRegex('x'),
  45932. y: counterRegex('y')
  45933. },
  45934. attrRegex: counterRegex('[xy]axis'),
  45935. // axis match regular expression
  45936. xAxisMatch: counterRegex('xaxis'),
  45937. yAxisMatch: counterRegex('yaxis'),
  45938. // pattern matching axis ids and names
  45939. // note that this is more permissive than counterRegex, as
  45940. // id2name, name2id, and cleanId accept "x1" etc
  45941. AX_ID_PATTERN: /^[xyz][0-9]*$/,
  45942. AX_NAME_PATTERN: /^[xyz]axis[0-9]*$/,
  45943. // and for 2D subplots
  45944. SUBPLOT_PATTERN: /^x([0-9]*)y([0-9]*)$/,
  45945. // pixels to move mouse before you stop clamping to starting point
  45946. MINDRAG: 8,
  45947. // smallest dimension allowed for a select box
  45948. MINSELECT: 12,
  45949. // smallest dimension allowed for a zoombox
  45950. MINZOOM: 20,
  45951. // width of axis drag regions
  45952. DRAGGERSIZE: 20,
  45953. // max pixels off straight before a lasso select line counts as bent
  45954. BENDPX: 1.5,
  45955. // delay before a redraw (relayout) after smooth panning and zooming
  45956. REDRAWDELAY: 50,
  45957. // throttling limit (ms) for selectPoints calls
  45958. SELECTDELAY: 100,
  45959. // cache ID suffix for throttle
  45960. SELECTID: '-select',
  45961. // last resort axis ranges for x and y axes if we have no data
  45962. DFLTRANGEX: [-1, 6],
  45963. DFLTRANGEY: [-1, 4],
  45964. // Layers to keep trace types in the right order
  45965. // N.B. each 'unique' plot method must have its own layer
  45966. traceLayerClasses: [
  45967. 'heatmaplayer',
  45968. 'contourcarpetlayer', 'contourlayer',
  45969. 'barlayer',
  45970. 'carpetlayer',
  45971. 'violinlayer',
  45972. 'boxlayer',
  45973. 'ohlclayer',
  45974. 'scattercarpetlayer', 'scatterlayer'
  45975. ],
  45976. layerValue2layerClass: {
  45977. 'above traces': 'above',
  45978. 'below traces': 'below'
  45979. }
  45980. };
  45981. },{"../../lib/regex":183}],219:[function(_dereq_,module,exports){
  45982. /**
  45983. * Copyright 2012-2019, Plotly, Inc.
  45984. * All rights reserved.
  45985. *
  45986. * This source code is licensed under the MIT license found in the
  45987. * LICENSE file in the root directory of this source tree.
  45988. */
  45989. 'use strict';
  45990. var Lib = _dereq_('../../lib');
  45991. var id2name = _dereq_('./axis_ids').id2name;
  45992. module.exports = function handleConstraintDefaults(containerIn, containerOut, coerce, allAxisIds, layoutOut) {
  45993. var constraintGroups = layoutOut._axisConstraintGroups;
  45994. var thisID = containerOut._id;
  45995. var letter = thisID.charAt(0);
  45996. if(containerOut.fixedrange) return;
  45997. // coerce the constraint mechanics even if this axis has no scaleanchor
  45998. // because it may be the anchor of another axis.
  45999. coerce('constrain');
  46000. Lib.coerce(containerIn, containerOut, {
  46001. constraintoward: {
  46002. valType: 'enumerated',
  46003. values: letter === 'x' ? ['left', 'center', 'right'] : ['bottom', 'middle', 'top'],
  46004. dflt: letter === 'x' ? 'center' : 'middle'
  46005. }
  46006. }, 'constraintoward');
  46007. if(!containerIn.scaleanchor) return;
  46008. var constraintOpts = getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut);
  46009. var scaleanchor = Lib.coerce(containerIn, containerOut, {
  46010. scaleanchor: {
  46011. valType: 'enumerated',
  46012. values: constraintOpts.linkableAxes
  46013. }
  46014. }, 'scaleanchor');
  46015. if(scaleanchor) {
  46016. var scaleratio = coerce('scaleratio');
  46017. // TODO: I suppose I could do attribute.min: Number.MIN_VALUE to avoid zero,
  46018. // but that seems hacky. Better way to say "must be a positive number"?
  46019. // Of course if you use several super-tiny values you could eventually
  46020. // force a product of these to zero and all hell would break loose...
  46021. // Likewise with super-huge values.
  46022. if(!scaleratio) scaleratio = containerOut.scaleratio = 1;
  46023. updateConstraintGroups(constraintGroups, constraintOpts.thisGroup,
  46024. thisID, scaleanchor, scaleratio);
  46025. }
  46026. else if(allAxisIds.indexOf(containerIn.scaleanchor) !== -1) {
  46027. Lib.warn('ignored ' + containerOut._name + '.scaleanchor: "' +
  46028. containerIn.scaleanchor + '" to avoid either an infinite loop ' +
  46029. 'and possibly inconsistent scaleratios, or because the target' +
  46030. 'axis has fixed range.');
  46031. }
  46032. };
  46033. function getConstraintOpts(constraintGroups, thisID, allAxisIds, layoutOut) {
  46034. // If this axis is already part of a constraint group, we can't
  46035. // scaleanchor any other axis in that group, or we'd make a loop.
  46036. // Filter allAxisIds to enforce this, also matching axis types.
  46037. var thisType = layoutOut[id2name(thisID)].type;
  46038. var i, j, idj, axj;
  46039. var linkableAxes = [];
  46040. for(j = 0; j < allAxisIds.length; j++) {
  46041. idj = allAxisIds[j];
  46042. if(idj === thisID) continue;
  46043. axj = layoutOut[id2name(idj)];
  46044. if(axj.type === thisType && !axj.fixedrange) linkableAxes.push(idj);
  46045. }
  46046. for(i = 0; i < constraintGroups.length; i++) {
  46047. if(constraintGroups[i][thisID]) {
  46048. var thisGroup = constraintGroups[i];
  46049. var linkableAxesNoLoops = [];
  46050. for(j = 0; j < linkableAxes.length; j++) {
  46051. idj = linkableAxes[j];
  46052. if(!thisGroup[idj]) linkableAxesNoLoops.push(idj);
  46053. }
  46054. return {linkableAxes: linkableAxesNoLoops, thisGroup: thisGroup};
  46055. }
  46056. }
  46057. return {linkableAxes: linkableAxes, thisGroup: null};
  46058. }
  46059. /*
  46060. * Add this axis to the axis constraint groups, which is the collection
  46061. * of axes that are all constrained together on scale.
  46062. *
  46063. * constraintGroups: a list of objects. each object is
  46064. * {axis_id: scale_within_group}, where scale_within_group is
  46065. * only important relative to the rest of the group, and defines
  46066. * the relative scales between all axes in the group
  46067. *
  46068. * thisGroup: the group the current axis is already in
  46069. * thisID: the id if the current axis
  46070. * scaleanchor: the id of the axis to scale it with
  46071. * scaleratio: the ratio of this axis to the scaleanchor axis
  46072. */
  46073. function updateConstraintGroups(constraintGroups, thisGroup, thisID, scaleanchor, scaleratio) {
  46074. var i, j, groupi, keyj, thisGroupIndex;
  46075. if(thisGroup === null) {
  46076. thisGroup = {};
  46077. thisGroup[thisID] = 1;
  46078. thisGroupIndex = constraintGroups.length;
  46079. constraintGroups.push(thisGroup);
  46080. }
  46081. else {
  46082. thisGroupIndex = constraintGroups.indexOf(thisGroup);
  46083. }
  46084. var thisGroupKeys = Object.keys(thisGroup);
  46085. // we know that this axis isn't in any other groups, but we don't know
  46086. // about the scaleanchor axis. If it is, we need to merge the groups.
  46087. for(i = 0; i < constraintGroups.length; i++) {
  46088. groupi = constraintGroups[i];
  46089. if(i !== thisGroupIndex && groupi[scaleanchor]) {
  46090. var baseScale = groupi[scaleanchor];
  46091. for(j = 0; j < thisGroupKeys.length; j++) {
  46092. keyj = thisGroupKeys[j];
  46093. groupi[keyj] = baseScale * scaleratio * thisGroup[keyj];
  46094. }
  46095. constraintGroups.splice(thisGroupIndex, 1);
  46096. return;
  46097. }
  46098. }
  46099. // otherwise, we insert the new scaleanchor axis as the base scale (1)
  46100. // in its group, and scale the rest of the group to it
  46101. if(scaleratio !== 1) {
  46102. for(j = 0; j < thisGroupKeys.length; j++) {
  46103. thisGroup[thisGroupKeys[j]] *= scaleratio;
  46104. }
  46105. }
  46106. thisGroup[scaleanchor] = 1;
  46107. }
  46108. },{"../../lib":168,"./axis_ids":215}],220:[function(_dereq_,module,exports){
  46109. /**
  46110. * Copyright 2012-2019, Plotly, Inc.
  46111. * All rights reserved.
  46112. *
  46113. * This source code is licensed under the MIT license found in the
  46114. * LICENSE file in the root directory of this source tree.
  46115. */
  46116. 'use strict';
  46117. var id2name = _dereq_('./axis_ids').id2name;
  46118. var scaleZoom = _dereq_('./scale_zoom');
  46119. var makePadFn = _dereq_('./autorange').makePadFn;
  46120. var concatExtremes = _dereq_('./autorange').concatExtremes;
  46121. var ALMOST_EQUAL = _dereq_('../../constants/numerical').ALMOST_EQUAL;
  46122. var FROM_BL = _dereq_('../../constants/alignment').FROM_BL;
  46123. exports.enforce = function enforceAxisConstraints(gd) {
  46124. var fullLayout = gd._fullLayout;
  46125. var constraintGroups = fullLayout._axisConstraintGroups || [];
  46126. var i, j, axisID, ax, normScale, mode, factor;
  46127. for(i = 0; i < constraintGroups.length; i++) {
  46128. var group = constraintGroups[i];
  46129. var axisIDs = Object.keys(group);
  46130. var minScale = Infinity;
  46131. var maxScale = 0;
  46132. // mostly matchScale will be the same as minScale
  46133. // ie we expand axis ranges to encompass *everything*
  46134. // that's currently in any of their ranges, but during
  46135. // autorange of a subset of axes we will ignore other
  46136. // axes for this purpose.
  46137. var matchScale = Infinity;
  46138. var normScales = {};
  46139. var axes = {};
  46140. var hasAnyDomainConstraint = false;
  46141. // find the (normalized) scale of each axis in the group
  46142. for(j = 0; j < axisIDs.length; j++) {
  46143. axisID = axisIDs[j];
  46144. axes[axisID] = ax = fullLayout[id2name(axisID)];
  46145. if(ax._inputDomain) ax.domain = ax._inputDomain.slice();
  46146. else ax._inputDomain = ax.domain.slice();
  46147. if(!ax._inputRange) ax._inputRange = ax.range.slice();
  46148. // set axis scale here so we can use _m rather than
  46149. // having to calculate it from length and range
  46150. ax.setScale();
  46151. // abs: inverted scales still satisfy the constraint
  46152. normScales[axisID] = normScale = Math.abs(ax._m) / group[axisID];
  46153. minScale = Math.min(minScale, normScale);
  46154. if(ax.constrain === 'domain' || !ax._constraintShrinkable) {
  46155. matchScale = Math.min(matchScale, normScale);
  46156. }
  46157. // this has served its purpose, so remove it
  46158. delete ax._constraintShrinkable;
  46159. maxScale = Math.max(maxScale, normScale);
  46160. if(ax.constrain === 'domain') hasAnyDomainConstraint = true;
  46161. }
  46162. // Do we have a constraint mismatch? Give a small buffer for rounding errors
  46163. if(minScale > ALMOST_EQUAL * maxScale && !hasAnyDomainConstraint) continue;
  46164. // now increase any ranges we need to until all normalized scales are equal
  46165. for(j = 0; j < axisIDs.length; j++) {
  46166. axisID = axisIDs[j];
  46167. normScale = normScales[axisID];
  46168. ax = axes[axisID];
  46169. mode = ax.constrain;
  46170. // even if the scale didn't change, if we're shrinking domain
  46171. // we need to recalculate in case `constraintoward` changed
  46172. if(normScale !== matchScale || mode === 'domain') {
  46173. factor = normScale / matchScale;
  46174. if(mode === 'range') {
  46175. scaleZoom(ax, factor);
  46176. }
  46177. else {
  46178. // mode === 'domain'
  46179. var inputDomain = ax._inputDomain;
  46180. var domainShrunk = (ax.domain[1] - ax.domain[0]) /
  46181. (inputDomain[1] - inputDomain[0]);
  46182. var rangeShrunk = (ax.r2l(ax.range[1]) - ax.r2l(ax.range[0])) /
  46183. (ax.r2l(ax._inputRange[1]) - ax.r2l(ax._inputRange[0]));
  46184. factor /= domainShrunk;
  46185. if(factor * rangeShrunk < 1) {
  46186. // we've asked to magnify the axis more than we can just by
  46187. // enlarging the domain - so we need to constrict range
  46188. ax.domain = ax._input.domain = inputDomain.slice();
  46189. scaleZoom(ax, factor);
  46190. continue;
  46191. }
  46192. if(rangeShrunk < 1) {
  46193. // the range has previously been constricted by ^^, but we've
  46194. // switched to the domain-constricted regime, so reset range
  46195. ax.range = ax._input.range = ax._inputRange.slice();
  46196. factor *= rangeShrunk;
  46197. }
  46198. if(ax.autorange) {
  46199. /*
  46200. * range & factor may need to change because range was
  46201. * calculated for the larger scaling, so some pixel
  46202. * paddings may get cut off when we reduce the domain.
  46203. *
  46204. * This is easier than the regular autorange calculation
  46205. * because we already know the scaling `m`, but we still
  46206. * need to cut out impossible constraints (like
  46207. * annotations with super-long arrows). That's what
  46208. * outerMin/Max are for - if the expansion was going to
  46209. * go beyond the original domain, it must be impossible
  46210. */
  46211. var rl0 = ax.r2l(ax.range[0]);
  46212. var rl1 = ax.r2l(ax.range[1]);
  46213. var rangeCenter = (rl0 + rl1) / 2;
  46214. var rangeMin = rangeCenter;
  46215. var rangeMax = rangeCenter;
  46216. var halfRange = Math.abs(rl1 - rangeCenter);
  46217. // extra tiny bit for rounding errors, in case we actually
  46218. // *are* expanding to the full domain
  46219. var outerMin = rangeCenter - halfRange * factor * 1.0001;
  46220. var outerMax = rangeCenter + halfRange * factor * 1.0001;
  46221. var getPad = makePadFn(ax);
  46222. updateDomain(ax, factor);
  46223. var m = Math.abs(ax._m);
  46224. var extremes = concatExtremes(gd, ax);
  46225. var minArray = extremes.min;
  46226. var maxArray = extremes.max;
  46227. var newVal;
  46228. var k;
  46229. for(k = 0; k < minArray.length; k++) {
  46230. newVal = minArray[k].val - getPad(minArray[k]) / m;
  46231. if(newVal > outerMin && newVal < rangeMin) {
  46232. rangeMin = newVal;
  46233. }
  46234. }
  46235. for(k = 0; k < maxArray.length; k++) {
  46236. newVal = maxArray[k].val + getPad(maxArray[k]) / m;
  46237. if(newVal < outerMax && newVal > rangeMax) {
  46238. rangeMax = newVal;
  46239. }
  46240. }
  46241. var domainExpand = (rangeMax - rangeMin) / (2 * halfRange);
  46242. factor /= domainExpand;
  46243. rangeMin = ax.l2r(rangeMin);
  46244. rangeMax = ax.l2r(rangeMax);
  46245. ax.range = ax._input.range = (rl0 < rl1) ?
  46246. [rangeMin, rangeMax] : [rangeMax, rangeMin];
  46247. }
  46248. updateDomain(ax, factor);
  46249. }
  46250. }
  46251. }
  46252. }
  46253. };
  46254. // For use before autoranging, check if this axis was previously constrained
  46255. // by domain but no longer is
  46256. exports.clean = function cleanConstraints(gd, ax) {
  46257. if(ax._inputDomain) {
  46258. var isConstrained = false;
  46259. var axId = ax._id;
  46260. var constraintGroups = gd._fullLayout._axisConstraintGroups;
  46261. for(var j = 0; j < constraintGroups.length; j++) {
  46262. if(constraintGroups[j][axId]) {
  46263. isConstrained = true;
  46264. break;
  46265. }
  46266. }
  46267. if(!isConstrained || ax.constrain !== 'domain') {
  46268. ax._input.domain = ax.domain = ax._inputDomain;
  46269. delete ax._inputDomain;
  46270. }
  46271. }
  46272. };
  46273. function updateDomain(ax, factor) {
  46274. var inputDomain = ax._inputDomain;
  46275. var centerFraction = FROM_BL[ax.constraintoward];
  46276. var center = inputDomain[0] + (inputDomain[1] - inputDomain[0]) * centerFraction;
  46277. ax.domain = ax._input.domain = [
  46278. center + (inputDomain[0] - center) / factor,
  46279. center + (inputDomain[1] - center) / factor
  46280. ];
  46281. ax.setScale();
  46282. }
  46283. },{"../../constants/alignment":146,"../../constants/numerical":149,"./autorange":211,"./axis_ids":215,"./scale_zoom":229}],221:[function(_dereq_,module,exports){
  46284. /**
  46285. * Copyright 2012-2019, Plotly, Inc.
  46286. * All rights reserved.
  46287. *
  46288. * This source code is licensed under the MIT license found in the
  46289. * LICENSE file in the root directory of this source tree.
  46290. */
  46291. 'use strict';
  46292. var d3 = _dereq_('d3');
  46293. var tinycolor = _dereq_('tinycolor2');
  46294. var supportsPassive = _dereq_('has-passive-events');
  46295. var Registry = _dereq_('../../registry');
  46296. var Lib = _dereq_('../../lib');
  46297. var svgTextUtils = _dereq_('../../lib/svg_text_utils');
  46298. var Color = _dereq_('../../components/color');
  46299. var Drawing = _dereq_('../../components/drawing');
  46300. var Fx = _dereq_('../../components/fx');
  46301. var Axes = _dereq_('./axes');
  46302. var setCursor = _dereq_('../../lib/setcursor');
  46303. var dragElement = _dereq_('../../components/dragelement');
  46304. var FROM_TL = _dereq_('../../constants/alignment').FROM_TL;
  46305. var clearGlCanvases = _dereq_('../../lib/clear_gl_canvases');
  46306. var redrawReglTraces = _dereq_('../../plot_api/subroutines').redrawReglTraces;
  46307. var Plots = _dereq_('../plots');
  46308. var getFromId = _dereq_('./axis_ids').getFromId;
  46309. var prepSelect = _dereq_('./select').prepSelect;
  46310. var clearSelect = _dereq_('./select').clearSelect;
  46311. var selectOnClick = _dereq_('./select').selectOnClick;
  46312. var scaleZoom = _dereq_('./scale_zoom');
  46313. var constants = _dereq_('./constants');
  46314. var MINDRAG = constants.MINDRAG;
  46315. var MINZOOM = constants.MINZOOM;
  46316. // flag for showing "doubleclick to zoom out" only at the beginning
  46317. var SHOWZOOMOUTTIP = true;
  46318. // dragBox: create an element to drag one or more axis ends
  46319. // inputs:
  46320. // plotinfo - which subplot are we making dragboxes on?
  46321. // x,y,w,h - left, top, width, height of the box
  46322. // ns - how does this drag the vertical axis?
  46323. // 'n' - top only
  46324. // 's' - bottom only
  46325. // 'ns' - top and bottom together, difference unchanged
  46326. // ew - same for horizontal axis
  46327. function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) {
  46328. // mouseDown stores ms of first mousedown event in the last
  46329. // DBLCLICKDELAY ms on the drag bars
  46330. // numClicks stores how many mousedowns have been seen
  46331. // within DBLCLICKDELAY so we can check for click or doubleclick events
  46332. // dragged stores whether a drag has occurred, so we don't have to
  46333. // redraw unnecessarily, ie if no move bigger than MINDRAG or MINZOOM px
  46334. var zoomlayer = gd._fullLayout._zoomlayer;
  46335. var isMainDrag = (ns + ew === 'nsew');
  46336. var singleEnd = (ns + ew).length === 1;
  46337. // main subplot x and y (i.e. found in plotinfo - the main ones)
  46338. var xa0, ya0;
  46339. // {ax._id: ax} hash objects
  46340. var xaHash, yaHash;
  46341. // xaHash/yaHash values (arrays)
  46342. var xaxes, yaxes;
  46343. // main axis offsets
  46344. var xs, ys;
  46345. // main axis lengths
  46346. var pw, ph;
  46347. // contains keys 'xaHash', 'yaHash', 'xaxes', and 'yaxes'
  46348. // which are the x/y {ax._id: ax} hash objects and their values
  46349. // for linked axis relative to this subplot
  46350. var links;
  46351. // set to ew/ns val when active, set to '' when inactive
  46352. var xActive, yActive;
  46353. // are all axes in this subplot are fixed?
  46354. var allFixedRanges;
  46355. // is subplot constrained?
  46356. var isSubplotConstrained;
  46357. // do we need to edit x/y ranges?
  46358. var editX, editY;
  46359. // graph-wide optimization flags
  46360. var hasScatterGl, hasSplom, hasSVG;
  46361. // collected changes to be made to the plot by relayout at the end
  46362. var updates;
  46363. function recomputeAxisLists() {
  46364. xa0 = plotinfo.xaxis;
  46365. ya0 = plotinfo.yaxis;
  46366. pw = xa0._length;
  46367. ph = ya0._length;
  46368. xs = xa0._offset;
  46369. ys = ya0._offset;
  46370. xaHash = {};
  46371. xaHash[xa0._id] = xa0;
  46372. yaHash = {};
  46373. yaHash[ya0._id] = ya0;
  46374. // if we're dragging two axes at once, also drag overlays
  46375. if(ns && ew) {
  46376. var overlays = plotinfo.overlays;
  46377. for(var i = 0; i < overlays.length; i++) {
  46378. var xa = overlays[i].xaxis;
  46379. xaHash[xa._id] = xa;
  46380. var ya = overlays[i].yaxis;
  46381. yaHash[ya._id] = ya;
  46382. }
  46383. }
  46384. xaxes = hashValues(xaHash);
  46385. yaxes = hashValues(yaHash);
  46386. xActive = isDirectionActive(xaxes, ew);
  46387. yActive = isDirectionActive(yaxes, ns);
  46388. allFixedRanges = !yActive && !xActive;
  46389. links = calcLinks(gd, xaHash, yaHash);
  46390. isSubplotConstrained = links.isSubplotConstrained;
  46391. editX = ew || isSubplotConstrained;
  46392. editY = ns || isSubplotConstrained;
  46393. var fullLayout = gd._fullLayout;
  46394. hasScatterGl = fullLayout._has('scattergl');
  46395. hasSplom = fullLayout._has('splom');
  46396. hasSVG = fullLayout._has('svg');
  46397. }
  46398. recomputeAxisLists();
  46399. var cursor = getDragCursor(yActive + xActive, gd._fullLayout.dragmode, isMainDrag);
  46400. var dragger = makeRectDragger(plotinfo, ns + ew + 'drag', cursor, x, y, w, h);
  46401. // still need to make the element if the axes are disabled
  46402. // but nuke its events (except for maindrag which needs them for hover)
  46403. // and stop there
  46404. if(allFixedRanges && !isMainDrag) {
  46405. dragger.onmousedown = null;
  46406. dragger.style.pointerEvents = 'none';
  46407. return dragger;
  46408. }
  46409. var dragOptions = {
  46410. element: dragger,
  46411. gd: gd,
  46412. plotinfo: plotinfo
  46413. };
  46414. dragOptions.prepFn = function(e, startX, startY) {
  46415. var dragModePrev = dragOptions.dragmode;
  46416. var dragModeNow = gd._fullLayout.dragmode;
  46417. if(dragModeNow !== dragModePrev) {
  46418. dragOptions.dragmode = dragModeNow;
  46419. }
  46420. recomputeAxisLists();
  46421. if(!allFixedRanges) {
  46422. if(isMainDrag) {
  46423. // main dragger handles all drag modes, and changes
  46424. // to pan (or to zoom if it already is pan) on shift
  46425. if(e.shiftKey) {
  46426. if(dragModeNow === 'pan') dragModeNow = 'zoom';
  46427. else if(!isSelectOrLasso(dragModeNow)) dragModeNow = 'pan';
  46428. }
  46429. else if(e.ctrlKey) {
  46430. dragModeNow = 'pan';
  46431. }
  46432. }
  46433. // all other draggers just pan
  46434. else dragModeNow = 'pan';
  46435. }
  46436. if(dragModeNow === 'lasso') dragOptions.minDrag = 1;
  46437. else dragOptions.minDrag = undefined;
  46438. if(isSelectOrLasso(dragModeNow)) {
  46439. dragOptions.xaxes = xaxes;
  46440. dragOptions.yaxes = yaxes;
  46441. // this attaches moveFn, clickFn, doneFn on dragOptions
  46442. prepSelect(e, startX, startY, dragOptions, dragModeNow);
  46443. } else {
  46444. dragOptions.clickFn = clickFn;
  46445. if(isSelectOrLasso(dragModePrev)) {
  46446. // TODO Fix potential bug
  46447. // Note: clearing / resetting selection state only happens, when user
  46448. // triggers at least one interaction in pan/zoom mode. Otherwise, the
  46449. // select/lasso outlines are deleted (in plots.js.cleanPlot) but the selection
  46450. // cache isn't cleared. So when the user switches back to select/lasso and
  46451. // 'adds to a selection' with Shift, the "old", seemingly removed outlines
  46452. // are redrawn again because the selection cache still holds their coordinates.
  46453. // However, this isn't easily solved, since plots.js would need
  46454. // to have a reference to the dragOptions object (which holds the
  46455. // selection cache).
  46456. clearAndResetSelect();
  46457. }
  46458. if(!allFixedRanges) {
  46459. if(dragModeNow === 'zoom') {
  46460. dragOptions.moveFn = zoomMove;
  46461. dragOptions.doneFn = zoomDone;
  46462. // zoomMove takes care of the threshold, but we need to
  46463. // minimize this so that constrained zoom boxes will flip
  46464. // orientation at the right place
  46465. dragOptions.minDrag = 1;
  46466. zoomPrep(e, startX, startY);
  46467. } else if(dragModeNow === 'pan') {
  46468. dragOptions.moveFn = plotDrag;
  46469. dragOptions.doneFn = dragTail;
  46470. }
  46471. }
  46472. }
  46473. };
  46474. function clearAndResetSelect() {
  46475. // clear selection polygon cache (if any)
  46476. dragOptions.plotinfo.selection = false;
  46477. // clear selection outlines
  46478. clearSelect(zoomlayer);
  46479. }
  46480. function clickFn(numClicks, evt) {
  46481. var clickmode = gd._fullLayout.clickmode;
  46482. removeZoombox(gd);
  46483. if(numClicks === 2 && !singleEnd) doubleClick();
  46484. if(isMainDrag) {
  46485. if(clickmode.indexOf('select') > -1) {
  46486. selectOnClick(evt, gd, xaxes, yaxes, plotinfo.id, dragOptions);
  46487. }
  46488. if(clickmode.indexOf('event') > -1) {
  46489. Fx.click(gd, evt, plotinfo.id);
  46490. }
  46491. }
  46492. else if(numClicks === 1 && singleEnd) {
  46493. var ax = ns ? ya0 : xa0;
  46494. var end = (ns === 's' || ew === 'w') ? 0 : 1;
  46495. var attrStr = ax._name + '.range[' + end + ']';
  46496. var initialText = getEndText(ax, end);
  46497. var hAlign = 'left';
  46498. var vAlign = 'middle';
  46499. if(ax.fixedrange) return;
  46500. if(ns) {
  46501. vAlign = (ns === 'n') ? 'top' : 'bottom';
  46502. if(ax.side === 'right') hAlign = 'right';
  46503. }
  46504. else if(ew === 'e') hAlign = 'right';
  46505. if(gd._context.showAxisRangeEntryBoxes) {
  46506. d3.select(dragger)
  46507. .call(svgTextUtils.makeEditable, {
  46508. gd: gd,
  46509. immediate: true,
  46510. background: gd._fullLayout.paper_bgcolor,
  46511. text: String(initialText),
  46512. fill: ax.tickfont ? ax.tickfont.color : '#444',
  46513. horizontalAlign: hAlign,
  46514. verticalAlign: vAlign
  46515. })
  46516. .on('edit', function(text) {
  46517. var v = ax.d2r(text);
  46518. if(v !== undefined) {
  46519. Registry.call('_guiRelayout', gd, attrStr, v);
  46520. }
  46521. });
  46522. }
  46523. }
  46524. }
  46525. dragElement.init(dragOptions);
  46526. var x0,
  46527. y0,
  46528. box,
  46529. lum,
  46530. path0,
  46531. dimmed,
  46532. zoomMode,
  46533. zb,
  46534. corners;
  46535. // zoom takes over minDrag, so it also has to take over gd._dragged
  46536. var zoomDragged;
  46537. function zoomPrep(e, startX, startY) {
  46538. var dragBBox = dragger.getBoundingClientRect();
  46539. x0 = startX - dragBBox.left;
  46540. y0 = startY - dragBBox.top;
  46541. box = {l: x0, r: x0, w: 0, t: y0, b: y0, h: 0};
  46542. lum = gd._hmpixcount ?
  46543. (gd._hmlumcount / gd._hmpixcount) :
  46544. tinycolor(gd._fullLayout.plot_bgcolor).getLuminance();
  46545. path0 = 'M0,0H' + pw + 'V' + ph + 'H0V0';
  46546. dimmed = false;
  46547. zoomMode = 'xy';
  46548. zoomDragged = false;
  46549. zb = makeZoombox(zoomlayer, lum, xs, ys, path0);
  46550. corners = makeCorners(zoomlayer, xs, ys);
  46551. }
  46552. function zoomMove(dx0, dy0) {
  46553. if(gd._transitioningWithDuration) {
  46554. return false;
  46555. }
  46556. var x1 = Math.max(0, Math.min(pw, dx0 + x0));
  46557. var y1 = Math.max(0, Math.min(ph, dy0 + y0));
  46558. var dx = Math.abs(x1 - x0);
  46559. var dy = Math.abs(y1 - y0);
  46560. box.l = Math.min(x0, x1);
  46561. box.r = Math.max(x0, x1);
  46562. box.t = Math.min(y0, y1);
  46563. box.b = Math.max(y0, y1);
  46564. function noZoom() {
  46565. zoomMode = '';
  46566. box.r = box.l;
  46567. box.t = box.b;
  46568. corners.attr('d', 'M0,0Z');
  46569. }
  46570. if(isSubplotConstrained) {
  46571. if(dx > MINZOOM || dy > MINZOOM) {
  46572. zoomMode = 'xy';
  46573. if(dx / pw > dy / ph) {
  46574. dy = dx * ph / pw;
  46575. if(y0 > y1) box.t = y0 - dy;
  46576. else box.b = y0 + dy;
  46577. }
  46578. else {
  46579. dx = dy * pw / ph;
  46580. if(x0 > x1) box.l = x0 - dx;
  46581. else box.r = x0 + dx;
  46582. }
  46583. corners.attr('d', xyCorners(box));
  46584. }
  46585. else {
  46586. noZoom();
  46587. }
  46588. }
  46589. // look for small drags in one direction or the other,
  46590. // and only drag the other axis
  46591. else if(!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) {
  46592. if(dx < MINDRAG || !xActive) {
  46593. noZoom();
  46594. } else {
  46595. box.t = 0;
  46596. box.b = ph;
  46597. zoomMode = 'x';
  46598. corners.attr('d', xCorners(box, y0));
  46599. }
  46600. }
  46601. else if(!xActive || dx < Math.min(dy * 0.6, MINZOOM)) {
  46602. box.l = 0;
  46603. box.r = pw;
  46604. zoomMode = 'y';
  46605. corners.attr('d', yCorners(box, x0));
  46606. }
  46607. else {
  46608. zoomMode = 'xy';
  46609. corners.attr('d', xyCorners(box));
  46610. }
  46611. box.w = box.r - box.l;
  46612. box.h = box.b - box.t;
  46613. if(zoomMode) zoomDragged = true;
  46614. gd._dragged = zoomDragged;
  46615. updateZoombox(zb, corners, box, path0, dimmed, lum);
  46616. dimmed = true;
  46617. }
  46618. function zoomDone() {
  46619. updates = {};
  46620. // more strict than dragged, which allows you to come back to where you started
  46621. // and still count as dragged
  46622. if(Math.min(box.h, box.w) < MINDRAG * 2) {
  46623. return removeZoombox(gd);
  46624. }
  46625. // TODO: edit linked axes in zoomAxRanges and in dragTail
  46626. if(zoomMode === 'xy' || zoomMode === 'x') {
  46627. zoomAxRanges(xaxes, box.l / pw, box.r / pw, updates, links.xaxes);
  46628. }
  46629. if(zoomMode === 'xy' || zoomMode === 'y') {
  46630. zoomAxRanges(yaxes, (ph - box.b) / ph, (ph - box.t) / ph, updates, links.yaxes);
  46631. }
  46632. removeZoombox(gd);
  46633. dragTail();
  46634. showDoubleClickNotifier(gd);
  46635. }
  46636. // scroll zoom, on all draggers except corners
  46637. var scrollViewBox = [0, 0, pw, ph];
  46638. // wait a little after scrolling before redrawing
  46639. var redrawTimer = null;
  46640. var REDRAWDELAY = constants.REDRAWDELAY;
  46641. var mainplot = plotinfo.mainplot ? gd._fullLayout._plots[plotinfo.mainplot] : plotinfo;
  46642. function zoomWheel(e) {
  46643. // deactivate mousewheel scrolling on embedded graphs
  46644. // devs can override this with layout._enablescrollzoom,
  46645. // but _ ensures this setting won't leave their page
  46646. if(!gd._context._scrollZoom.cartesian && !gd._fullLayout._enablescrollzoom) {
  46647. return;
  46648. }
  46649. clearAndResetSelect();
  46650. // If a transition is in progress, then disable any behavior:
  46651. if(gd._transitioningWithDuration) {
  46652. e.preventDefault();
  46653. e.stopPropagation();
  46654. return;
  46655. }
  46656. recomputeAxisLists();
  46657. clearTimeout(redrawTimer);
  46658. var wheelDelta = -e.deltaY;
  46659. if(!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10;
  46660. if(!isFinite(wheelDelta)) {
  46661. Lib.log('Did not find wheel motion attributes: ', e);
  46662. return;
  46663. }
  46664. var zoom = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200);
  46665. var gbb = mainplot.draglayer.select('.nsewdrag').node().getBoundingClientRect();
  46666. var xfrac = (e.clientX - gbb.left) / gbb.width;
  46667. var yfrac = (gbb.bottom - e.clientY) / gbb.height;
  46668. var i;
  46669. function zoomWheelOneAxis(ax, centerFraction, zoom) {
  46670. if(ax.fixedrange) return;
  46671. var axRange = Lib.simpleMap(ax.range, ax.r2l);
  46672. var v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction;
  46673. function doZoom(v) { return ax.l2r(v0 + (v - v0) * zoom); }
  46674. ax.range = axRange.map(doZoom);
  46675. }
  46676. if(editX) {
  46677. // if we're only zooming this axis because of constraints,
  46678. // zoom it about the center
  46679. if(!ew) xfrac = 0.5;
  46680. for(i = 0; i < xaxes.length; i++) {
  46681. zoomWheelOneAxis(xaxes[i], xfrac, zoom);
  46682. }
  46683. scrollViewBox[2] *= zoom;
  46684. scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom - 1);
  46685. }
  46686. if(editY) {
  46687. if(!ns) yfrac = 0.5;
  46688. for(i = 0; i < yaxes.length; i++) {
  46689. zoomWheelOneAxis(yaxes[i], yfrac, zoom);
  46690. }
  46691. scrollViewBox[3] *= zoom;
  46692. scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom - 1);
  46693. }
  46694. // viewbox redraw at first
  46695. updateSubplots(scrollViewBox);
  46696. ticksAndAnnotations();
  46697. // then replot after a delay to make sure
  46698. // no more scrolling is coming
  46699. redrawTimer = setTimeout(function() {
  46700. scrollViewBox = [0, 0, pw, ph];
  46701. dragTail();
  46702. }, REDRAWDELAY);
  46703. e.preventDefault();
  46704. return;
  46705. }
  46706. // everything but the corners gets wheel zoom
  46707. if(ns.length * ew.length !== 1) {
  46708. attachWheelEventHandler(dragger, zoomWheel);
  46709. }
  46710. // plotDrag: move the plot in response to a drag
  46711. function plotDrag(dx, dy) {
  46712. // If a transition is in progress, then disable any behavior:
  46713. if(gd._transitioningWithDuration) {
  46714. return;
  46715. }
  46716. // prevent axis drawing from monkeying with margins until we're done
  46717. gd._fullLayout._replotting = true;
  46718. if(xActive === 'ew' || yActive === 'ns') {
  46719. if(xActive) dragAxList(xaxes, dx);
  46720. if(yActive) dragAxList(yaxes, dy);
  46721. updateSubplots([xActive ? -dx : 0, yActive ? -dy : 0, pw, ph]);
  46722. ticksAndAnnotations();
  46723. return;
  46724. }
  46725. // dz: set a new value for one end (0 or 1) of an axis array axArray,
  46726. // and return a pixel shift for that end for the viewbox
  46727. // based on pixel drag distance d
  46728. // TODO: this makes (generally non-fatal) errors when you get
  46729. // near floating point limits
  46730. function dz(axArray, end, d) {
  46731. var otherEnd = 1 - end;
  46732. var movedAx;
  46733. var newLinearizedEnd;
  46734. for(var i = 0; i < axArray.length; i++) {
  46735. var axi = axArray[i];
  46736. if(axi.fixedrange) continue;
  46737. movedAx = axi;
  46738. newLinearizedEnd = axi._rl[otherEnd] +
  46739. (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length);
  46740. var newEnd = axi.l2r(newLinearizedEnd);
  46741. // if l2r comes back false or undefined, it means we've dragged off
  46742. // the end of valid ranges - so stop.
  46743. if(newEnd !== false && newEnd !== undefined) axi.range[end] = newEnd;
  46744. }
  46745. return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) /
  46746. (movedAx._rl[end] - movedAx._rl[otherEnd]);
  46747. }
  46748. if(isSubplotConstrained && xActive && yActive) {
  46749. // dragging a corner of a constrained subplot:
  46750. // respect the fixed corner, but harmonize dx and dy
  46751. var dxySign = ((xActive === 'w') === (yActive === 'n')) ? 1 : -1;
  46752. var dxyFraction = (dx / pw + dxySign * dy / ph) / 2;
  46753. dx = dxyFraction * pw;
  46754. dy = dxySign * dxyFraction * ph;
  46755. }
  46756. if(xActive === 'w') dx = dz(xaxes, 0, dx);
  46757. else if(xActive === 'e') dx = dz(xaxes, 1, -dx);
  46758. else if(!xActive) dx = 0;
  46759. if(yActive === 'n') dy = dz(yaxes, 1, dy);
  46760. else if(yActive === 's') dy = dz(yaxes, 0, -dy);
  46761. else if(!yActive) dy = 0;
  46762. var x0 = (xActive === 'w') ? dx : 0;
  46763. var y0 = (yActive === 'n') ? dy : 0;
  46764. if(isSubplotConstrained) {
  46765. var i;
  46766. if(!xActive && yActive.length === 1) {
  46767. // dragging one end of the y axis of a constrained subplot
  46768. // scale the other axis the same about its middle
  46769. for(i = 0; i < xaxes.length; i++) {
  46770. xaxes[i].range = xaxes[i]._r.slice();
  46771. scaleZoom(xaxes[i], 1 - dy / ph);
  46772. }
  46773. dx = dy * pw / ph;
  46774. x0 = dx / 2;
  46775. }
  46776. if(!yActive && xActive.length === 1) {
  46777. for(i = 0; i < yaxes.length; i++) {
  46778. yaxes[i].range = yaxes[i]._r.slice();
  46779. scaleZoom(yaxes[i], 1 - dx / pw);
  46780. }
  46781. dy = dx * ph / pw;
  46782. y0 = dy / 2;
  46783. }
  46784. }
  46785. updateSubplots([x0, y0, pw - dx, ph - dy]);
  46786. ticksAndAnnotations();
  46787. }
  46788. // Draw ticks and annotations (and other components) when ranges change.
  46789. // Also records the ranges that have changed for use by update at the end.
  46790. function ticksAndAnnotations() {
  46791. var activeAxIds = [];
  46792. var i;
  46793. function pushActiveAxIds(axList) {
  46794. for(i = 0; i < axList.length; i++) {
  46795. if(!axList[i].fixedrange) activeAxIds.push(axList[i]._id);
  46796. }
  46797. }
  46798. if(editX) {
  46799. pushActiveAxIds(xaxes);
  46800. pushActiveAxIds(links.xaxes);
  46801. }
  46802. if(editY) {
  46803. pushActiveAxIds(yaxes);
  46804. pushActiveAxIds(links.yaxes);
  46805. }
  46806. updates = {};
  46807. for(i = 0; i < activeAxIds.length; i++) {
  46808. var axId = activeAxIds[i];
  46809. var ax = getFromId(gd, axId);
  46810. Axes.drawOne(gd, ax, {skipTitle: true});
  46811. updates[ax._name + '.range[0]'] = ax.range[0];
  46812. updates[ax._name + '.range[1]'] = ax.range[1];
  46813. }
  46814. Axes.redrawComponents(gd, activeAxIds);
  46815. }
  46816. function doubleClick() {
  46817. if(gd._transitioningWithDuration) return;
  46818. var doubleClickConfig = gd._context.doubleClick;
  46819. var axList = (xActive ? xaxes : []).concat(yActive ? yaxes : []);
  46820. var attrs = {};
  46821. var ax, i, rangeInitial;
  46822. // For reset+autosize mode:
  46823. // If *any* of the main axes is not at its initial range
  46824. // (or autoranged, if we have no initial range, to match the logic in
  46825. // doubleClickConfig === 'reset' below), we reset.
  46826. // If they are *all* at their initial ranges, then we autosize.
  46827. if(doubleClickConfig === 'reset+autosize') {
  46828. doubleClickConfig = 'autosize';
  46829. for(i = 0; i < axList.length; i++) {
  46830. ax = axList[i];
  46831. if((ax._rangeInitial && (
  46832. ax.range[0] !== ax._rangeInitial[0] ||
  46833. ax.range[1] !== ax._rangeInitial[1]
  46834. )) ||
  46835. (!ax._rangeInitial && !ax.autorange)
  46836. ) {
  46837. doubleClickConfig = 'reset';
  46838. break;
  46839. }
  46840. }
  46841. }
  46842. if(doubleClickConfig === 'autosize') {
  46843. // don't set the linked axes here, so relayout marks them as shrinkable
  46844. // and we autosize just to the requested axis/axes
  46845. for(i = 0; i < axList.length; i++) {
  46846. ax = axList[i];
  46847. if(!ax.fixedrange) attrs[ax._name + '.autorange'] = true;
  46848. }
  46849. }
  46850. else if(doubleClickConfig === 'reset') {
  46851. // when we're resetting, reset all linked axes too, so we get back
  46852. // to the fully-auto-with-constraints situation
  46853. if(xActive || isSubplotConstrained) axList = axList.concat(links.xaxes);
  46854. if(yActive && !isSubplotConstrained) axList = axList.concat(links.yaxes);
  46855. if(isSubplotConstrained) {
  46856. if(!xActive) axList = axList.concat(xaxes);
  46857. else if(!yActive) axList = axList.concat(yaxes);
  46858. }
  46859. for(i = 0; i < axList.length; i++) {
  46860. ax = axList[i];
  46861. if(!ax.fixedrange) {
  46862. if(!ax._rangeInitial) {
  46863. attrs[ax._name + '.autorange'] = true;
  46864. } else {
  46865. rangeInitial = ax._rangeInitial;
  46866. attrs[ax._name + '.range[0]'] = rangeInitial[0];
  46867. attrs[ax._name + '.range[1]'] = rangeInitial[1];
  46868. }
  46869. }
  46870. }
  46871. }
  46872. gd.emit('plotly_doubleclick', null);
  46873. Registry.call('_guiRelayout', gd, attrs);
  46874. }
  46875. // dragTail - finish a drag event with a redraw
  46876. function dragTail() {
  46877. // put the subplot viewboxes back to default (Because we're going to)
  46878. // be repositioning the data in the relayout. But DON'T call
  46879. // ticksAndAnnotations again - it's unnecessary and would overwrite `updates`
  46880. updateSubplots([0, 0, pw, ph]);
  46881. // since we may have been redrawing some things during the drag, we may have
  46882. // accumulated MathJax promises - wait for them before we relayout.
  46883. Lib.syncOrAsync([
  46884. Plots.previousPromises,
  46885. function() {
  46886. gd._fullLayout._replotting = false;
  46887. Registry.call('_guiRelayout', gd, updates);
  46888. }
  46889. ], gd);
  46890. }
  46891. // x/y scaleFactor stash,
  46892. // minimizes number of per-point DOM updates in updateSubplots below
  46893. var xScaleFactorOld, yScaleFactorOld;
  46894. // updateSubplots - find all plot viewboxes that should be
  46895. // affected by this drag, and update them. look for all plots
  46896. // sharing an affected axis (including the one being dragged),
  46897. // includes also scattergl and splom logic.
  46898. function updateSubplots(viewBox) {
  46899. var fullLayout = gd._fullLayout;
  46900. var plotinfos = fullLayout._plots;
  46901. var subplots = fullLayout._subplots.cartesian;
  46902. var i, sp, xa, ya;
  46903. if(hasSplom) {
  46904. Registry.subplotsRegistry.splom.drag(gd);
  46905. }
  46906. if(hasScatterGl) {
  46907. for(i = 0; i < subplots.length; i++) {
  46908. sp = plotinfos[subplots[i]];
  46909. xa = sp.xaxis;
  46910. ya = sp.yaxis;
  46911. if(sp._scene) {
  46912. var xrng = Lib.simpleMap(xa.range, xa.r2l);
  46913. var yrng = Lib.simpleMap(ya.range, ya.r2l);
  46914. sp._scene.update({range: [xrng[0], yrng[0], xrng[1], yrng[1]]});
  46915. }
  46916. }
  46917. }
  46918. if(hasSplom || hasScatterGl) {
  46919. clearGlCanvases(gd);
  46920. redrawReglTraces(gd);
  46921. }
  46922. if(hasSVG) {
  46923. var xScaleFactor = viewBox[2] / xa0._length;
  46924. var yScaleFactor = viewBox[3] / ya0._length;
  46925. for(i = 0; i < subplots.length; i++) {
  46926. sp = plotinfos[subplots[i]];
  46927. xa = sp.xaxis;
  46928. ya = sp.yaxis;
  46929. var editX2 = editX && !xa.fixedrange && xaHash[xa._id];
  46930. var editY2 = editY && !ya.fixedrange && yaHash[ya._id];
  46931. var xScaleFactor2, yScaleFactor2;
  46932. var clipDx, clipDy;
  46933. if(editX2) {
  46934. xScaleFactor2 = xScaleFactor;
  46935. clipDx = ew ? viewBox[0] : getShift(xa, xScaleFactor2);
  46936. } else {
  46937. xScaleFactor2 = getLinkedScaleFactor(xa, xScaleFactor, yScaleFactor);
  46938. clipDx = scaleAndGetShift(xa, xScaleFactor2);
  46939. }
  46940. if(editY2) {
  46941. yScaleFactor2 = yScaleFactor;
  46942. clipDy = ns ? viewBox[1] : getShift(ya, yScaleFactor2);
  46943. } else {
  46944. yScaleFactor2 = getLinkedScaleFactor(ya, xScaleFactor, yScaleFactor);
  46945. clipDy = scaleAndGetShift(ya, yScaleFactor2);
  46946. }
  46947. // don't scale at all if neither axis is scalable here
  46948. if(!xScaleFactor2 && !yScaleFactor2) {
  46949. continue;
  46950. }
  46951. // but if only one is, reset the other axis scaling
  46952. if(!xScaleFactor2) xScaleFactor2 = 1;
  46953. if(!yScaleFactor2) yScaleFactor2 = 1;
  46954. var plotDx = xa._offset - clipDx / xScaleFactor2;
  46955. var plotDy = ya._offset - clipDy / yScaleFactor2;
  46956. // TODO could be more efficient here:
  46957. // setTranslate and setScale do a lot of extra work
  46958. // when working independently, should perhaps combine
  46959. // them into a single routine.
  46960. sp.clipRect
  46961. .call(Drawing.setTranslate, clipDx, clipDy)
  46962. .call(Drawing.setScale, xScaleFactor2, yScaleFactor2);
  46963. sp.plot
  46964. .call(Drawing.setTranslate, plotDx, plotDy)
  46965. .call(Drawing.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2);
  46966. // apply an inverse scale to individual points to counteract
  46967. // the scale of the trace group.
  46968. // apply only when scale changes, as adjusting the scale of
  46969. // all the points can be expansive.
  46970. if(xScaleFactor2 !== xScaleFactorOld || yScaleFactor2 !== yScaleFactorOld) {
  46971. Drawing.setPointGroupScale(sp.zoomScalePts, xScaleFactor2, yScaleFactor2);
  46972. Drawing.setTextPointsScale(sp.zoomScaleTxt, xScaleFactor2, yScaleFactor2);
  46973. }
  46974. Drawing.hideOutsideRangePoints(sp.clipOnAxisFalseTraces, sp);
  46975. // update x/y scaleFactor stash
  46976. xScaleFactorOld = xScaleFactor2;
  46977. yScaleFactorOld = yScaleFactor2;
  46978. }
  46979. }
  46980. }
  46981. // Find the appropriate scaling for this axis, if it's linked to the
  46982. // dragged axes by constraints. 0 is special, it means this axis shouldn't
  46983. // ever be scaled (will be converted to 1 if the other axis is scaled)
  46984. function getLinkedScaleFactor(ax, xScaleFactor, yScaleFactor) {
  46985. if(ax.fixedrange) return 0;
  46986. if(editX && links.xaHash[ax._id]) {
  46987. return xScaleFactor;
  46988. }
  46989. if(editY && (isSubplotConstrained ? links.xaHash : links.yaHash)[ax._id]) {
  46990. return yScaleFactor;
  46991. }
  46992. return 0;
  46993. }
  46994. function scaleAndGetShift(ax, scaleFactor) {
  46995. if(scaleFactor) {
  46996. ax.range = ax._r.slice();
  46997. scaleZoom(ax, scaleFactor);
  46998. return getShift(ax, scaleFactor);
  46999. }
  47000. return 0;
  47001. }
  47002. function getShift(ax, scaleFactor) {
  47003. return ax._length * (1 - scaleFactor) * FROM_TL[ax.constraintoward || 'middle'];
  47004. }
  47005. return dragger;
  47006. }
  47007. function makeDragger(plotinfo, nodeName, dragClass, cursor) {
  47008. var dragger3 = Lib.ensureSingle(plotinfo.draglayer, nodeName, dragClass, function(s) {
  47009. s.classed('drag', true)
  47010. .style({fill: 'transparent', 'stroke-width': 0})
  47011. .attr('data-subplot', plotinfo.id);
  47012. });
  47013. dragger3.call(setCursor, cursor);
  47014. return dragger3.node();
  47015. }
  47016. function makeRectDragger(plotinfo, dragClass, cursor, x, y, w, h) {
  47017. var dragger = makeDragger(plotinfo, 'rect', dragClass, cursor);
  47018. d3.select(dragger).call(Drawing.setRect, x, y, w, h);
  47019. return dragger;
  47020. }
  47021. function isDirectionActive(axList, activeVal) {
  47022. for(var i = 0; i < axList.length; i++) {
  47023. if(!axList[i].fixedrange) return activeVal;
  47024. }
  47025. return '';
  47026. }
  47027. function getEndText(ax, end) {
  47028. var initialVal = ax.range[end];
  47029. var diff = Math.abs(initialVal - ax.range[1 - end]);
  47030. var dig;
  47031. // TODO: this should basically be ax.r2d but we're doing extra
  47032. // rounding here... can we clean up at all?
  47033. if(ax.type === 'date') {
  47034. return initialVal;
  47035. }
  47036. else if(ax.type === 'log') {
  47037. dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3;
  47038. return d3.format('.' + dig + 'g')(Math.pow(10, initialVal));
  47039. }
  47040. else { // linear numeric (or category... but just show numbers here)
  47041. dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) -
  47042. Math.floor(Math.log(diff) / Math.LN10) + 4;
  47043. return d3.format('.' + String(dig) + 'g')(initialVal);
  47044. }
  47045. }
  47046. function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) {
  47047. var i,
  47048. axi,
  47049. axRangeLinear0,
  47050. axRangeLinearSpan;
  47051. for(i = 0; i < axList.length; i++) {
  47052. axi = axList[i];
  47053. if(axi.fixedrange) continue;
  47054. axRangeLinear0 = axi._rl[0];
  47055. axRangeLinearSpan = axi._rl[1] - axRangeLinear0;
  47056. axi.range = [
  47057. axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction),
  47058. axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction)
  47059. ];
  47060. updates[axi._name + '.range[0]'] = axi.range[0];
  47061. updates[axi._name + '.range[1]'] = axi.range[1];
  47062. }
  47063. // zoom linked axes about their centers
  47064. if(linkedAxes && linkedAxes.length) {
  47065. var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2;
  47066. zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates);
  47067. }
  47068. }
  47069. function dragAxList(axList, pix) {
  47070. for(var i = 0; i < axList.length; i++) {
  47071. var axi = axList[i];
  47072. if(!axi.fixedrange) {
  47073. axi.range = [
  47074. axi.l2r(axi._rl[0] - pix / axi._m),
  47075. axi.l2r(axi._rl[1] - pix / axi._m)
  47076. ];
  47077. }
  47078. }
  47079. }
  47080. // common transform for dragging one end of an axis
  47081. // d>0 is compressing scale (cursor is over the plot,
  47082. // the axis end should move with the cursor)
  47083. // d<0 is expanding (cursor is off the plot, axis end moves
  47084. // nonlinearly so you can expand far)
  47085. function dZoom(d) {
  47086. return 1 - ((d >= 0) ? Math.min(d, 0.9) :
  47087. 1 / (1 / Math.max(d, -0.3) + 3.222));
  47088. }
  47089. function getDragCursor(nsew, dragmode, isMainDrag) {
  47090. if(!nsew) return 'pointer';
  47091. if(nsew === 'nsew') {
  47092. // in this case here, clear cursor and
  47093. // use the cursor style set on <g .draglayer>
  47094. if(isMainDrag) return '';
  47095. if(dragmode === 'pan') return 'move';
  47096. return 'crosshair';
  47097. }
  47098. return nsew.toLowerCase() + '-resize';
  47099. }
  47100. function makeZoombox(zoomlayer, lum, xs, ys, path0) {
  47101. return zoomlayer.append('path')
  47102. .attr('class', 'zoombox')
  47103. .style({
  47104. 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)',
  47105. 'stroke-width': 0
  47106. })
  47107. .attr('transform', 'translate(' + xs + ', ' + ys + ')')
  47108. .attr('d', path0 + 'Z');
  47109. }
  47110. function makeCorners(zoomlayer, xs, ys) {
  47111. return zoomlayer.append('path')
  47112. .attr('class', 'zoombox-corners')
  47113. .style({
  47114. fill: Color.background,
  47115. stroke: Color.defaultLine,
  47116. 'stroke-width': 1,
  47117. opacity: 0
  47118. })
  47119. .attr('transform', 'translate(' + xs + ', ' + ys + ')')
  47120. .attr('d', 'M0,0Z');
  47121. }
  47122. function updateZoombox(zb, corners, box, path0, dimmed, lum) {
  47123. zb.attr('d',
  47124. path0 + 'M' + (box.l) + ',' + (box.t) + 'v' + (box.h) +
  47125. 'h' + (box.w) + 'v-' + (box.h) + 'h-' + (box.w) + 'Z');
  47126. transitionZoombox(zb, corners, dimmed, lum);
  47127. }
  47128. function transitionZoombox(zb, corners, dimmed, lum) {
  47129. if(!dimmed) {
  47130. zb.transition()
  47131. .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' :
  47132. 'rgba(255,255,255,0.3)')
  47133. .duration(200);
  47134. corners.transition()
  47135. .style('opacity', 1)
  47136. .duration(200);
  47137. }
  47138. }
  47139. function removeZoombox(gd) {
  47140. d3.select(gd)
  47141. .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners')
  47142. .remove();
  47143. }
  47144. function showDoubleClickNotifier(gd) {
  47145. if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) {
  47146. Lib.notifier(Lib._(gd, 'Double-click to zoom back out'), 'long');
  47147. SHOWZOOMOUTTIP = false;
  47148. }
  47149. }
  47150. function isSelectOrLasso(dragmode) {
  47151. return dragmode === 'lasso' || dragmode === 'select';
  47152. }
  47153. function xCorners(box, y0) {
  47154. return 'M' +
  47155. (box.l - 0.5) + ',' + (y0 - MINZOOM - 0.5) +
  47156. 'h-3v' + (2 * MINZOOM + 1) + 'h3ZM' +
  47157. (box.r + 0.5) + ',' + (y0 - MINZOOM - 0.5) +
  47158. 'h3v' + (2 * MINZOOM + 1) + 'h-3Z';
  47159. }
  47160. function yCorners(box, x0) {
  47161. return 'M' +
  47162. (x0 - MINZOOM - 0.5) + ',' + (box.t - 0.5) +
  47163. 'v-3h' + (2 * MINZOOM + 1) + 'v3ZM' +
  47164. (x0 - MINZOOM - 0.5) + ',' + (box.b + 0.5) +
  47165. 'v3h' + (2 * MINZOOM + 1) + 'v-3Z';
  47166. }
  47167. function xyCorners(box) {
  47168. var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2);
  47169. return 'M' +
  47170. (box.l - 3.5) + ',' + (box.t - 0.5 + clen) + 'h3v' + (-clen) +
  47171. 'h' + clen + 'v-3h-' + (clen + 3) + 'ZM' +
  47172. (box.r + 3.5) + ',' + (box.t - 0.5 + clen) + 'h-3v' + (-clen) +
  47173. 'h' + (-clen) + 'v-3h' + (clen + 3) + 'ZM' +
  47174. (box.r + 3.5) + ',' + (box.b + 0.5 - clen) + 'h-3v' + clen +
  47175. 'h' + (-clen) + 'v3h' + (clen + 3) + 'ZM' +
  47176. (box.l - 3.5) + ',' + (box.b + 0.5 - clen) + 'h3v' + clen +
  47177. 'h' + clen + 'v3h-' + (clen + 3) + 'Z';
  47178. }
  47179. function calcLinks(gd, xaHash, yaHash) {
  47180. var constraintGroups = gd._fullLayout._axisConstraintGroups;
  47181. var isSubplotConstrained = false;
  47182. var xLinks = {};
  47183. var yLinks = {};
  47184. var xID, yID, xLinkID, yLinkID;
  47185. for(var i = 0; i < constraintGroups.length; i++) {
  47186. var group = constraintGroups[i];
  47187. // check if any of the x axes we're dragging is in this constraint group
  47188. for(xID in xaHash) {
  47189. if(group[xID]) {
  47190. // put the rest of these axes into xLinks, if we're not already
  47191. // dragging them, so we know to scale these axes automatically too
  47192. // to match the changes in the dragged x axes
  47193. for(xLinkID in group) {
  47194. if(!(xLinkID.charAt(0) === 'x' ? xaHash : yaHash)[xLinkID]) {
  47195. xLinks[xLinkID] = 1;
  47196. }
  47197. }
  47198. // check if the x and y axes of THIS drag are linked
  47199. for(yID in yaHash) {
  47200. if(group[yID]) isSubplotConstrained = true;
  47201. }
  47202. }
  47203. }
  47204. // now check if any of the y axes we're dragging is in this constraint group
  47205. // only look for outside links, as we've already checked for links within the dragger
  47206. for(yID in yaHash) {
  47207. if(group[yID]) {
  47208. for(yLinkID in group) {
  47209. if(!(yLinkID.charAt(0) === 'x' ? xaHash : yaHash)[yLinkID]) {
  47210. yLinks[yLinkID] = 1;
  47211. }
  47212. }
  47213. }
  47214. }
  47215. }
  47216. if(isSubplotConstrained) {
  47217. // merge xLinks and yLinks if the subplot is constrained,
  47218. // since we'll always apply both anyway and the two will contain
  47219. // duplicates
  47220. Lib.extendFlat(xLinks, yLinks);
  47221. yLinks = {};
  47222. }
  47223. var xaHashLinked = {};
  47224. var xaxesLinked = [];
  47225. for(xLinkID in xLinks) {
  47226. var xa = getFromId(gd, xLinkID);
  47227. xaxesLinked.push(xa);
  47228. xaHashLinked[xa._id] = xa;
  47229. }
  47230. var yaHashLinked = {};
  47231. var yaxesLinked = [];
  47232. for(yLinkID in yLinks) {
  47233. var ya = getFromId(gd, yLinkID);
  47234. yaxesLinked.push(ya);
  47235. yaHashLinked[ya._id] = ya;
  47236. }
  47237. return {
  47238. xaHash: xaHashLinked,
  47239. yaHash: yaHashLinked,
  47240. xaxes: xaxesLinked,
  47241. yaxes: yaxesLinked,
  47242. isSubplotConstrained: isSubplotConstrained
  47243. };
  47244. }
  47245. // still seems to be some confusion about onwheel vs onmousewheel...
  47246. function attachWheelEventHandler(element, handler) {
  47247. if(!supportsPassive) {
  47248. if(element.onwheel !== undefined) element.onwheel = handler;
  47249. else if(element.onmousewheel !== undefined) element.onmousewheel = handler;
  47250. }
  47251. else {
  47252. var wheelEventName = element.onwheel !== undefined ? 'wheel' : 'mousewheel';
  47253. if(element._onwheel) {
  47254. element.removeEventListener(wheelEventName, element._onwheel);
  47255. }
  47256. element._onwheel = handler;
  47257. element.addEventListener(wheelEventName, handler, {passive: false});
  47258. }
  47259. }
  47260. function hashValues(hash) {
  47261. var out = [];
  47262. for(var k in hash) out.push(hash[k]);
  47263. return out;
  47264. }
  47265. module.exports = {
  47266. makeDragBox: makeDragBox,
  47267. makeDragger: makeDragger,
  47268. makeRectDragger: makeRectDragger,
  47269. makeZoombox: makeZoombox,
  47270. makeCorners: makeCorners,
  47271. updateZoombox: updateZoombox,
  47272. xyCorners: xyCorners,
  47273. transitionZoombox: transitionZoombox,
  47274. removeZoombox: removeZoombox,
  47275. showDoubleClickNotifier: showDoubleClickNotifier,
  47276. attachWheelEventHandler: attachWheelEventHandler
  47277. };
  47278. },{"../../components/color":51,"../../components/dragelement":69,"../../components/drawing":72,"../../components/fx":90,"../../constants/alignment":146,"../../lib":168,"../../lib/clear_gl_canvases":157,"../../lib/setcursor":187,"../../lib/svg_text_utils":189,"../../plot_api/subroutines":203,"../../registry":257,"../plots":245,"./axes":212,"./axis_ids":215,"./constants":218,"./scale_zoom":229,"./select":230,"d3":16,"has-passive-events":21,"tinycolor2":34}],222:[function(_dereq_,module,exports){
  47279. /**
  47280. * Copyright 2012-2019, Plotly, Inc.
  47281. * All rights reserved.
  47282. *
  47283. * This source code is licensed under the MIT license found in the
  47284. * LICENSE file in the root directory of this source tree.
  47285. */
  47286. 'use strict';
  47287. var d3 = _dereq_('d3');
  47288. var Fx = _dereq_('../../components/fx');
  47289. var dragElement = _dereq_('../../components/dragelement');
  47290. var setCursor = _dereq_('../../lib/setcursor');
  47291. var makeDragBox = _dereq_('./dragbox').makeDragBox;
  47292. var DRAGGERSIZE = _dereq_('./constants').DRAGGERSIZE;
  47293. exports.initInteractions = function initInteractions(gd) {
  47294. var fullLayout = gd._fullLayout;
  47295. if(gd._context.staticPlot) {
  47296. // this sweeps up more than just cartesian drag elements...
  47297. d3.select(gd).selectAll('.drag').remove();
  47298. return;
  47299. }
  47300. if(!fullLayout._has('cartesian') && !fullLayout._has('splom')) return;
  47301. var subplots = Object.keys(fullLayout._plots || {}).sort(function(a, b) {
  47302. // sort overlays last, then by x axis number, then y axis number
  47303. if((fullLayout._plots[a].mainplot && true) ===
  47304. (fullLayout._plots[b].mainplot && true)) {
  47305. var aParts = a.split('y');
  47306. var bParts = b.split('y');
  47307. return (aParts[0] === bParts[0]) ?
  47308. (Number(aParts[1] || 1) - Number(bParts[1] || 1)) :
  47309. (Number(aParts[0] || 1) - Number(bParts[0] || 1));
  47310. }
  47311. return fullLayout._plots[a].mainplot ? 1 : -1;
  47312. });
  47313. subplots.forEach(function(subplot) {
  47314. var plotinfo = fullLayout._plots[subplot];
  47315. var xa = plotinfo.xaxis;
  47316. var ya = plotinfo.yaxis;
  47317. // main and corner draggers need not be repeated for
  47318. // overlaid subplots - these draggers drag them all
  47319. if(!plotinfo.mainplot) {
  47320. // main dragger goes over the grids and data, so we use its
  47321. // mousemove events for all data hover effects
  47322. var maindrag = makeDragBox(gd, plotinfo, xa._offset, ya._offset,
  47323. xa._length, ya._length, 'ns', 'ew');
  47324. maindrag.onmousemove = function(evt) {
  47325. // This is on `gd._fullLayout`, *not* fullLayout because the reference
  47326. // changes by the time this is called again.
  47327. gd._fullLayout._rehover = function() {
  47328. if(gd._fullLayout._hoversubplot === subplot) {
  47329. Fx.hover(gd, evt, subplot);
  47330. }
  47331. };
  47332. Fx.hover(gd, evt, subplot);
  47333. // Note that we have *not* used the cached fullLayout variable here
  47334. // since that may be outdated when this is called as a callback later on
  47335. gd._fullLayout._lasthover = maindrag;
  47336. gd._fullLayout._hoversubplot = subplot;
  47337. };
  47338. /*
  47339. * IMPORTANT:
  47340. * We must check for the presence of the drag cover here.
  47341. * If we don't, a 'mouseout' event is triggered on the
  47342. * maindrag before each 'click' event, which has the effect
  47343. * of clearing the hoverdata; thus, cancelling the click event.
  47344. */
  47345. maindrag.onmouseout = function(evt) {
  47346. if(gd._dragging) return;
  47347. // When the mouse leaves this maindrag, unset the hovered subplot.
  47348. // This may cause problems if it leaves the subplot directly *onto*
  47349. // another subplot, but that's a tiny corner case at the moment.
  47350. gd._fullLayout._hoversubplot = null;
  47351. dragElement.unhover(gd, evt);
  47352. };
  47353. // corner draggers
  47354. if(gd._context.showAxisDragHandles) {
  47355. makeDragBox(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset - DRAGGERSIZE,
  47356. DRAGGERSIZE, DRAGGERSIZE, 'n', 'w');
  47357. makeDragBox(gd, plotinfo, xa._offset + xa._length, ya._offset - DRAGGERSIZE,
  47358. DRAGGERSIZE, DRAGGERSIZE, 'n', 'e');
  47359. makeDragBox(gd, plotinfo, xa._offset - DRAGGERSIZE, ya._offset + ya._length,
  47360. DRAGGERSIZE, DRAGGERSIZE, 's', 'w');
  47361. makeDragBox(gd, plotinfo, xa._offset + xa._length, ya._offset + ya._length,
  47362. DRAGGERSIZE, DRAGGERSIZE, 's', 'e');
  47363. }
  47364. }
  47365. if(gd._context.showAxisDragHandles) {
  47366. // x axis draggers - if you have overlaid plots,
  47367. // these drag each axis separately
  47368. if(subplot === xa._mainSubplot) {
  47369. // the y position of the main x axis line
  47370. var y0 = xa._mainLinePosition;
  47371. if(xa.side === 'top') y0 -= DRAGGERSIZE;
  47372. makeDragBox(gd, plotinfo, xa._offset + xa._length * 0.1, y0,
  47373. xa._length * 0.8, DRAGGERSIZE, '', 'ew');
  47374. makeDragBox(gd, plotinfo, xa._offset, y0,
  47375. xa._length * 0.1, DRAGGERSIZE, '', 'w');
  47376. makeDragBox(gd, plotinfo, xa._offset + xa._length * 0.9, y0,
  47377. xa._length * 0.1, DRAGGERSIZE, '', 'e');
  47378. }
  47379. // y axis draggers
  47380. if(subplot === ya._mainSubplot) {
  47381. // the x position of the main y axis line
  47382. var x0 = ya._mainLinePosition;
  47383. if(ya.side !== 'right') x0 -= DRAGGERSIZE;
  47384. makeDragBox(gd, plotinfo, x0, ya._offset + ya._length * 0.1,
  47385. DRAGGERSIZE, ya._length * 0.8, 'ns', '');
  47386. makeDragBox(gd, plotinfo, x0, ya._offset + ya._length * 0.9,
  47387. DRAGGERSIZE, ya._length * 0.1, 's', '');
  47388. makeDragBox(gd, plotinfo, x0, ya._offset,
  47389. DRAGGERSIZE, ya._length * 0.1, 'n', '');
  47390. }
  47391. }
  47392. });
  47393. // In case you mousemove over some hovertext, send it to Fx.hover too
  47394. // we do this so that we can put the hover text in front of everything,
  47395. // but still be able to interact with everything as if it isn't there
  47396. var hoverLayer = fullLayout._hoverlayer.node();
  47397. hoverLayer.onmousemove = function(evt) {
  47398. evt.target = gd._fullLayout._lasthover;
  47399. Fx.hover(gd, evt, fullLayout._hoversubplot);
  47400. };
  47401. hoverLayer.onclick = function(evt) {
  47402. evt.target = gd._fullLayout._lasthover;
  47403. Fx.click(gd, evt);
  47404. };
  47405. // also delegate mousedowns... TODO: does this actually work?
  47406. hoverLayer.onmousedown = function(evt) {
  47407. gd._fullLayout._lasthover.onmousedown(evt);
  47408. };
  47409. exports.updateFx(gd);
  47410. };
  47411. // Minimal set of update needed on 'modebar' edits.
  47412. // We only need to update the <g .draglayer> cursor style.
  47413. //
  47414. // Note that changing the axis configuration and/or the fixedrange attribute
  47415. // should trigger a full initInteractions.
  47416. exports.updateFx = function(gd) {
  47417. var fullLayout = gd._fullLayout;
  47418. var cursor = fullLayout.dragmode === 'pan' ? 'move' : 'crosshair';
  47419. setCursor(fullLayout._draggers, cursor);
  47420. };
  47421. },{"../../components/dragelement":69,"../../components/fx":90,"../../lib/setcursor":187,"./constants":218,"./dragbox":221,"d3":16}],223:[function(_dereq_,module,exports){
  47422. /**
  47423. * Copyright 2012-2019, Plotly, Inc.
  47424. * All rights reserved.
  47425. *
  47426. * This source code is licensed under the MIT license found in the
  47427. * LICENSE file in the root directory of this source tree.
  47428. */
  47429. 'use strict';
  47430. var Registry = _dereq_('../../registry');
  47431. var Lib = _dereq_('../../lib');
  47432. /**
  47433. * Factory function for checking component arrays for subplot references.
  47434. *
  47435. * @param {string} containerArrayName: the top-level array in gd.layout to check
  47436. * If an item in this container is found that references a cartesian x and/or y axis,
  47437. * ensure cartesian is marked as a base plot module and record the axes (and subplot
  47438. * if both refs are axes) in gd._fullLayout
  47439. *
  47440. * @return {function}: with args layoutIn (gd.layout) and layoutOut (gd._fullLayout)
  47441. * as expected of a component includeBasePlot method
  47442. */
  47443. module.exports = function makeIncludeComponents(containerArrayName) {
  47444. return function includeComponents(layoutIn, layoutOut) {
  47445. var array = layoutIn[containerArrayName];
  47446. if(!Array.isArray(array)) return;
  47447. var Cartesian = Registry.subplotsRegistry.cartesian;
  47448. var idRegex = Cartesian.idRegex;
  47449. var subplots = layoutOut._subplots;
  47450. var xaList = subplots.xaxis;
  47451. var yaList = subplots.yaxis;
  47452. var cartesianList = subplots.cartesian;
  47453. var hasCartesianOrGL2D = layoutOut._has('cartesian') || layoutOut._has('gl2d');
  47454. for(var i = 0; i < array.length; i++) {
  47455. var itemi = array[i];
  47456. if(!Lib.isPlainObject(itemi)) continue;
  47457. var xref = itemi.xref;
  47458. var yref = itemi.yref;
  47459. var hasXref = idRegex.x.test(xref);
  47460. var hasYref = idRegex.y.test(yref);
  47461. if(hasXref || hasYref) {
  47462. if(!hasCartesianOrGL2D) Lib.pushUnique(layoutOut._basePlotModules, Cartesian);
  47463. var newAxis = false;
  47464. if(hasXref && xaList.indexOf(xref) === -1) {
  47465. xaList.push(xref);
  47466. newAxis = true;
  47467. }
  47468. if(hasYref && yaList.indexOf(yref) === -1) {
  47469. yaList.push(yref);
  47470. newAxis = true;
  47471. }
  47472. /*
  47473. * Notice the logic here: only add a subplot for a component if
  47474. * it's referencing both x and y axes AND it's creating a new axis
  47475. * so for example if your plot already has xy and x2y2, an annotation
  47476. * on x2y or xy2 will not create a new subplot.
  47477. */
  47478. if(newAxis && hasXref && hasYref) {
  47479. cartesianList.push(xref + yref);
  47480. }
  47481. }
  47482. }
  47483. };
  47484. };
  47485. },{"../../lib":168,"../../registry":257}],224:[function(_dereq_,module,exports){
  47486. /**
  47487. * Copyright 2012-2019, Plotly, Inc.
  47488. * All rights reserved.
  47489. *
  47490. * This source code is licensed under the MIT license found in the
  47491. * LICENSE file in the root directory of this source tree.
  47492. */
  47493. 'use strict';
  47494. var d3 = _dereq_('d3');
  47495. var Registry = _dereq_('../../registry');
  47496. var Lib = _dereq_('../../lib');
  47497. var Plots = _dereq_('../plots');
  47498. var Drawing = _dereq_('../../components/drawing');
  47499. var getModuleCalcData = _dereq_('../get_data').getModuleCalcData;
  47500. var axisIds = _dereq_('./axis_ids');
  47501. var constants = _dereq_('./constants');
  47502. var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');
  47503. var ensureSingle = Lib.ensureSingle;
  47504. function ensureSingleAndAddDatum(parent, nodeType, className) {
  47505. return Lib.ensureSingle(parent, nodeType, className, function(s) {
  47506. s.datum(className);
  47507. });
  47508. }
  47509. exports.name = 'cartesian';
  47510. exports.attr = ['xaxis', 'yaxis'];
  47511. exports.idRoot = ['x', 'y'];
  47512. exports.idRegex = constants.idRegex;
  47513. exports.attrRegex = constants.attrRegex;
  47514. exports.attributes = _dereq_('./attributes');
  47515. exports.layoutAttributes = _dereq_('./layout_attributes');
  47516. exports.supplyLayoutDefaults = _dereq_('./layout_defaults');
  47517. exports.transitionAxes = _dereq_('./transition_axes');
  47518. exports.finalizeSubplots = function(layoutIn, layoutOut) {
  47519. var subplots = layoutOut._subplots;
  47520. var xList = subplots.xaxis;
  47521. var yList = subplots.yaxis;
  47522. var spSVG = subplots.cartesian;
  47523. var spAll = spSVG.concat(subplots.gl2d || []);
  47524. var allX = {};
  47525. var allY = {};
  47526. var i, xi, yi;
  47527. for(i = 0; i < spAll.length; i++) {
  47528. var parts = spAll[i].split('y');
  47529. allX[parts[0]] = 1;
  47530. allY['y' + parts[1]] = 1;
  47531. }
  47532. // check for x axes with no subplot, and make one from the anchor of that x axis
  47533. for(i = 0; i < xList.length; i++) {
  47534. xi = xList[i];
  47535. if(!allX[xi]) {
  47536. yi = (layoutIn[axisIds.id2name(xi)] || {}).anchor;
  47537. if(!constants.idRegex.y.test(yi)) yi = 'y';
  47538. spSVG.push(xi + yi);
  47539. spAll.push(xi + yi);
  47540. if(!allY[yi]) {
  47541. allY[yi] = 1;
  47542. Lib.pushUnique(yList, yi);
  47543. }
  47544. }
  47545. }
  47546. // same for y axes with no subplot
  47547. for(i = 0; i < yList.length; i++) {
  47548. yi = yList[i];
  47549. if(!allY[yi]) {
  47550. xi = (layoutIn[axisIds.id2name(yi)] || {}).anchor;
  47551. if(!constants.idRegex.x.test(xi)) xi = 'x';
  47552. spSVG.push(xi + yi);
  47553. spAll.push(xi + yi);
  47554. if(!allX[xi]) {
  47555. allX[xi] = 1;
  47556. Lib.pushUnique(xList, xi);
  47557. }
  47558. }
  47559. }
  47560. // finally, if we've gotten here we're supposed to show cartesian...
  47561. // so if there are NO subplots at all, make one from the first
  47562. // x & y axes in the input layout
  47563. if(!spAll.length) {
  47564. xi = '';
  47565. yi = '';
  47566. for(var ki in layoutIn) {
  47567. if(constants.attrRegex.test(ki)) {
  47568. var axLetter = ki.charAt(0);
  47569. if(axLetter === 'x') {
  47570. if(!xi || (+ki.substr(5) < +xi.substr(5))) {
  47571. xi = ki;
  47572. }
  47573. }
  47574. else if(!yi || (+ki.substr(5) < +yi.substr(5))) {
  47575. yi = ki;
  47576. }
  47577. }
  47578. }
  47579. xi = xi ? axisIds.name2id(xi) : 'x';
  47580. yi = yi ? axisIds.name2id(yi) : 'y';
  47581. xList.push(xi);
  47582. yList.push(yi);
  47583. spSVG.push(xi + yi);
  47584. }
  47585. };
  47586. /**
  47587. * Cartesian.plot
  47588. *
  47589. * @param {DOM div | object} gd
  47590. * @param {array | null} (optional) traces
  47591. * array of traces indices to plot
  47592. * if undefined, plots all cartesian traces,
  47593. * if null, plots no traces
  47594. * @param {object} (optional) transitionOpts
  47595. * transition option object
  47596. * @param {function} (optional) makeOnCompleteCallback
  47597. * transition make callback function from Plots.transition
  47598. */
  47599. exports.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) {
  47600. var fullLayout = gd._fullLayout;
  47601. var subplots = fullLayout._subplots.cartesian;
  47602. var calcdata = gd.calcdata;
  47603. var i;
  47604. if(traces === null) {
  47605. // this means no updates required, must return here
  47606. // so that plotOne doesn't remove the trace layers
  47607. return;
  47608. } else if(!Array.isArray(traces)) {
  47609. // If traces is not provided, then it's a complete replot and missing
  47610. // traces are removed
  47611. traces = [];
  47612. for(i = 0; i < calcdata.length; i++) traces.push(i);
  47613. }
  47614. for(i = 0; i < subplots.length; i++) {
  47615. var subplot = subplots[i];
  47616. var subplotInfo = fullLayout._plots[subplot];
  47617. // Get all calcdata for this subplot:
  47618. var cdSubplot = [];
  47619. var pcd;
  47620. for(var j = 0; j < calcdata.length; j++) {
  47621. var cd = calcdata[j];
  47622. var trace = cd[0].trace;
  47623. // Skip trace if whitelist provided and it's not whitelisted:
  47624. // if (Array.isArray(traces) && traces.indexOf(i) === -1) continue;
  47625. if(trace.xaxis + trace.yaxis === subplot) {
  47626. // XXX: Should trace carpet dependencies. Only replot all carpet plots if the carpet
  47627. // axis has actually changed:
  47628. //
  47629. // If this trace is specifically requested, add it to the list:
  47630. if(traces.indexOf(trace.index) !== -1 || trace.carpet) {
  47631. // Okay, so example: traces 0, 1, and 2 have fill = tonext. You animate
  47632. // traces 0 and 2. Trace 1 also needs to be updated, otherwise its fill
  47633. // is outdated. So this retroactively adds the previous trace if the
  47634. // traces are interdependent.
  47635. if(
  47636. pcd &&
  47637. pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot &&
  47638. ['tonextx', 'tonexty', 'tonext'].indexOf(trace.fill) !== -1 &&
  47639. cdSubplot.indexOf(pcd) === -1
  47640. ) {
  47641. cdSubplot.push(pcd);
  47642. }
  47643. cdSubplot.push(cd);
  47644. }
  47645. // Track the previous trace on this subplot for the retroactive-add step
  47646. // above:
  47647. pcd = cd;
  47648. }
  47649. }
  47650. plotOne(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback);
  47651. }
  47652. };
  47653. function plotOne(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) {
  47654. var traceLayerClasses = constants.traceLayerClasses;
  47655. var fullLayout = gd._fullLayout;
  47656. var modules = fullLayout._modules;
  47657. var _module, cdModuleAndOthers, cdModule;
  47658. var layerData = [];
  47659. var zoomScaleQueryParts = [];
  47660. for(var i = 0; i < modules.length; i++) {
  47661. _module = modules[i];
  47662. var name = _module.name;
  47663. var categories = Registry.modules[name].categories;
  47664. if(categories.svg) {
  47665. var className = (_module.layerName || name + 'layer');
  47666. var plotMethod = _module.plot;
  47667. // plot all visible traces of this type on this subplot at once
  47668. cdModuleAndOthers = getModuleCalcData(cdSubplot, plotMethod);
  47669. cdModule = cdModuleAndOthers[0];
  47670. // don't need to search the found traces again - in fact we need to NOT
  47671. // so that if two modules share the same plotter we don't double-plot
  47672. cdSubplot = cdModuleAndOthers[1];
  47673. if(cdModule.length) {
  47674. layerData.push({
  47675. i: traceLayerClasses.indexOf(className),
  47676. className: className,
  47677. plotMethod: plotMethod,
  47678. cdModule: cdModule
  47679. });
  47680. }
  47681. if(categories.zoomScale) {
  47682. zoomScaleQueryParts.push('.' + className);
  47683. }
  47684. }
  47685. }
  47686. layerData.sort(function(a, b) { return a.i - b.i; });
  47687. var layers = plotinfo.plot.selectAll('g.mlayer')
  47688. .data(layerData, function(d) { return d.className; });
  47689. layers.enter().append('g')
  47690. .attr('class', function(d) { return d.className; })
  47691. .classed('mlayer', true);
  47692. layers.exit().remove();
  47693. layers.order();
  47694. layers.each(function(d) {
  47695. var sel = d3.select(this);
  47696. var className = d.className;
  47697. d.plotMethod(
  47698. gd, plotinfo, d.cdModule, sel,
  47699. transitionOpts, makeOnCompleteCallback
  47700. );
  47701. // layers that allow `cliponaxis: false`
  47702. if(className !== 'scatterlayer' && className !== 'barlayer') {
  47703. Drawing.setClipUrl(sel, plotinfo.layerClipId, gd);
  47704. }
  47705. });
  47706. // call Scattergl.plot separately
  47707. if(fullLayout._has('scattergl')) {
  47708. _module = Registry.getModule('scattergl');
  47709. cdModule = getModuleCalcData(cdSubplot, _module)[0];
  47710. _module.plot(gd, plotinfo, cdModule);
  47711. }
  47712. // stash "hot" selections for faster interaction on drag and scroll
  47713. if(!gd._context.staticPlot) {
  47714. if(plotinfo._hasClipOnAxisFalse) {
  47715. plotinfo.clipOnAxisFalseTraces = plotinfo.plot
  47716. .selectAll('.scatterlayer, .barlayer')
  47717. .selectAll('.trace');
  47718. }
  47719. if(zoomScaleQueryParts.length) {
  47720. var traces = plotinfo.plot
  47721. .selectAll(zoomScaleQueryParts.join(','))
  47722. .selectAll('.trace');
  47723. plotinfo.zoomScalePts = traces.selectAll('path.point');
  47724. plotinfo.zoomScaleTxt = traces.selectAll('.textpoint');
  47725. }
  47726. }
  47727. }
  47728. exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
  47729. var oldPlots = oldFullLayout._plots || {};
  47730. var newPlots = newFullLayout._plots || {};
  47731. var oldSubplotList = oldFullLayout._subplots || {};
  47732. var plotinfo;
  47733. var i, k;
  47734. // when going from a large splom graph to something else,
  47735. // we need to clear <g subplot> so that the new cartesian subplot
  47736. // can have the correct layer ordering
  47737. if(oldFullLayout._hasOnlyLargeSploms && !newFullLayout._hasOnlyLargeSploms) {
  47738. for(k in oldPlots) {
  47739. plotinfo = oldPlots[k];
  47740. if(plotinfo.plotgroup) plotinfo.plotgroup.remove();
  47741. }
  47742. }
  47743. var hadGl = (oldFullLayout._has && oldFullLayout._has('gl'));
  47744. var hasGl = (newFullLayout._has && newFullLayout._has('gl'));
  47745. if(hadGl && !hasGl) {
  47746. for(k in oldPlots) {
  47747. plotinfo = oldPlots[k];
  47748. if(plotinfo._scene) plotinfo._scene.destroy();
  47749. }
  47750. }
  47751. // delete any titles we don't need anymore
  47752. // check if axis list has changed, and if so clear old titles
  47753. if(oldSubplotList.xaxis && oldSubplotList.yaxis) {
  47754. var oldAxIDs = axisIds.listIds({_fullLayout: oldFullLayout});
  47755. for(i = 0; i < oldAxIDs.length; i++) {
  47756. var oldAxId = oldAxIDs[i];
  47757. if(!newFullLayout[axisIds.id2name(oldAxId)]) {
  47758. oldFullLayout._infolayer.selectAll('.g-' + oldAxId + 'title').remove();
  47759. }
  47760. }
  47761. }
  47762. // if we've gotten rid of all cartesian traces, remove all the subplot svg items
  47763. var hadCartesian = (oldFullLayout._has && oldFullLayout._has('cartesian'));
  47764. var hasCartesian = (newFullLayout._has && newFullLayout._has('cartesian'));
  47765. if(hadCartesian && !hasCartesian) {
  47766. purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll('.subplot'), oldFullLayout);
  47767. oldFullLayout._defs.selectAll('.axesclip').remove();
  47768. delete oldFullLayout._axisConstraintGroups;
  47769. }
  47770. // otherwise look for subplots we need to remove
  47771. else if(oldSubplotList.cartesian) {
  47772. for(i = 0; i < oldSubplotList.cartesian.length; i++) {
  47773. var oldSubplotId = oldSubplotList.cartesian[i];
  47774. if(!newPlots[oldSubplotId]) {
  47775. var selector = '.' + oldSubplotId + ',.' + oldSubplotId + '-x,.' + oldSubplotId + '-y';
  47776. oldFullLayout._cartesianlayer.selectAll(selector).remove();
  47777. removeSubplotExtras(oldSubplotId, oldFullLayout);
  47778. }
  47779. }
  47780. }
  47781. };
  47782. exports.drawFramework = function(gd) {
  47783. var fullLayout = gd._fullLayout;
  47784. var subplotData = makeSubplotData(gd);
  47785. var subplotLayers = fullLayout._cartesianlayer.selectAll('.subplot')
  47786. .data(subplotData, String);
  47787. subplotLayers.enter().append('g')
  47788. .attr('class', function(d) { return 'subplot ' + d[0]; });
  47789. subplotLayers.order();
  47790. subplotLayers.exit()
  47791. .call(purgeSubplotLayers, fullLayout);
  47792. subplotLayers.each(function(d) {
  47793. var id = d[0];
  47794. var plotinfo = fullLayout._plots[id];
  47795. plotinfo.plotgroup = d3.select(this);
  47796. makeSubplotLayer(gd, plotinfo);
  47797. // make separate drag layers for each subplot,
  47798. // but append them to paper rather than the plot groups,
  47799. // so they end up on top of the rest
  47800. plotinfo.draglayer = ensureSingle(fullLayout._draggers, 'g', id);
  47801. });
  47802. };
  47803. exports.rangePlot = function(gd, plotinfo, cdSubplot) {
  47804. makeSubplotLayer(gd, plotinfo);
  47805. plotOne(gd, plotinfo, cdSubplot);
  47806. Plots.style(gd);
  47807. };
  47808. function makeSubplotData(gd) {
  47809. var fullLayout = gd._fullLayout;
  47810. var ids = fullLayout._subplots.cartesian;
  47811. var len = ids.length;
  47812. var i, j, id, plotinfo, xa, ya;
  47813. // split 'regular' and 'overlaying' subplots
  47814. var regulars = [];
  47815. var overlays = [];
  47816. for(i = 0; i < len; i++) {
  47817. id = ids[i];
  47818. plotinfo = fullLayout._plots[id];
  47819. xa = plotinfo.xaxis;
  47820. ya = plotinfo.yaxis;
  47821. var xa2 = xa._mainAxis;
  47822. var ya2 = ya._mainAxis;
  47823. var mainplot = xa2._id + ya2._id;
  47824. var mainplotinfo = fullLayout._plots[mainplot];
  47825. plotinfo.overlays = [];
  47826. if(mainplot !== id && mainplotinfo) {
  47827. plotinfo.mainplot = mainplot;
  47828. plotinfo.mainplotinfo = mainplotinfo;
  47829. overlays.push(id);
  47830. } else {
  47831. plotinfo.mainplot = undefined;
  47832. plotinfo.mainPlotinfo = undefined;
  47833. regulars.push(id);
  47834. }
  47835. }
  47836. // fill in list of overlaying subplots in 'main plot'
  47837. for(i = 0; i < overlays.length; i++) {
  47838. id = overlays[i];
  47839. plotinfo = fullLayout._plots[id];
  47840. plotinfo.mainplotinfo.overlays.push(plotinfo);
  47841. }
  47842. // put 'regular' subplot data before 'overlaying'
  47843. var subplotIds = regulars.concat(overlays);
  47844. var subplotData = new Array(len);
  47845. for(i = 0; i < len; i++) {
  47846. id = subplotIds[i];
  47847. plotinfo = fullLayout._plots[id];
  47848. xa = plotinfo.xaxis;
  47849. ya = plotinfo.yaxis;
  47850. // use info about axis layer and overlaying pattern
  47851. // to clean what need to be cleaned up in exit selection
  47852. var d = [id, xa.layer, ya.layer, xa.overlaying || '', ya.overlaying || ''];
  47853. for(j = 0; j < plotinfo.overlays.length; j++) {
  47854. d.push(plotinfo.overlays[j].id);
  47855. }
  47856. subplotData[i] = d;
  47857. }
  47858. return subplotData;
  47859. }
  47860. function makeSubplotLayer(gd, plotinfo) {
  47861. var plotgroup = plotinfo.plotgroup;
  47862. var id = plotinfo.id;
  47863. var xLayer = constants.layerValue2layerClass[plotinfo.xaxis.layer];
  47864. var yLayer = constants.layerValue2layerClass[plotinfo.yaxis.layer];
  47865. var hasOnlyLargeSploms = gd._fullLayout._hasOnlyLargeSploms;
  47866. if(!plotinfo.mainplot) {
  47867. if(hasOnlyLargeSploms) {
  47868. // TODO could do even better
  47869. // - we don't need plot (but we would have to mock it in lsInner
  47870. // and other places
  47871. // - we don't (x|y)lines and (x|y)axislayer for most subplots
  47872. // usually just the bottom x and left y axes.
  47873. plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above');
  47874. plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above');
  47875. plotinfo.xaxislayer = ensureSingle(plotgroup, 'g', 'xaxislayer-above');
  47876. plotinfo.yaxislayer = ensureSingle(plotgroup, 'g', 'yaxislayer-above');
  47877. }
  47878. else {
  47879. var backLayer = ensureSingle(plotgroup, 'g', 'layer-subplot');
  47880. plotinfo.shapelayer = ensureSingle(backLayer, 'g', 'shapelayer');
  47881. plotinfo.imagelayer = ensureSingle(backLayer, 'g', 'imagelayer');
  47882. plotinfo.gridlayer = ensureSingle(plotgroup, 'g', 'gridlayer');
  47883. plotinfo.zerolinelayer = ensureSingle(plotgroup, 'g', 'zerolinelayer');
  47884. ensureSingle(plotgroup, 'path', 'xlines-below');
  47885. ensureSingle(plotgroup, 'path', 'ylines-below');
  47886. plotinfo.overlinesBelow = ensureSingle(plotgroup, 'g', 'overlines-below');
  47887. ensureSingle(plotgroup, 'g', 'xaxislayer-below');
  47888. ensureSingle(plotgroup, 'g', 'yaxislayer-below');
  47889. plotinfo.overaxesBelow = ensureSingle(plotgroup, 'g', 'overaxes-below');
  47890. plotinfo.plot = ensureSingle(plotgroup, 'g', 'plot');
  47891. plotinfo.overplot = ensureSingle(plotgroup, 'g', 'overplot');
  47892. plotinfo.xlines = ensureSingle(plotgroup, 'path', 'xlines-above');
  47893. plotinfo.ylines = ensureSingle(plotgroup, 'path', 'ylines-above');
  47894. plotinfo.overlinesAbove = ensureSingle(plotgroup, 'g', 'overlines-above');
  47895. ensureSingle(plotgroup, 'g', 'xaxislayer-above');
  47896. ensureSingle(plotgroup, 'g', 'yaxislayer-above');
  47897. plotinfo.overaxesAbove = ensureSingle(plotgroup, 'g', 'overaxes-above');
  47898. // set refs to correct layers as determined by 'axis.layer'
  47899. plotinfo.xlines = plotgroup.select('.xlines-' + xLayer);
  47900. plotinfo.ylines = plotgroup.select('.ylines-' + yLayer);
  47901. plotinfo.xaxislayer = plotgroup.select('.xaxislayer-' + xLayer);
  47902. plotinfo.yaxislayer = plotgroup.select('.yaxislayer-' + yLayer);
  47903. }
  47904. }
  47905. else {
  47906. var mainplotinfo = plotinfo.mainplotinfo;
  47907. var mainplotgroup = mainplotinfo.plotgroup;
  47908. var xId = id + '-x';
  47909. var yId = id + '-y';
  47910. // now make the components of overlaid subplots
  47911. // overlays don't have backgrounds, and append all
  47912. // their other components to the corresponding
  47913. // extra groups of their main plots.
  47914. plotinfo.gridlayer = mainplotinfo.gridlayer;
  47915. plotinfo.zerolinelayer = mainplotinfo.zerolinelayer;
  47916. ensureSingle(mainplotinfo.overlinesBelow, 'path', xId);
  47917. ensureSingle(mainplotinfo.overlinesBelow, 'path', yId);
  47918. ensureSingle(mainplotinfo.overaxesBelow, 'g', xId);
  47919. ensureSingle(mainplotinfo.overaxesBelow, 'g', yId);
  47920. plotinfo.plot = ensureSingle(mainplotinfo.overplot, 'g', id);
  47921. ensureSingle(mainplotinfo.overlinesAbove, 'path', xId);
  47922. ensureSingle(mainplotinfo.overlinesAbove, 'path', yId);
  47923. ensureSingle(mainplotinfo.overaxesAbove, 'g', xId);
  47924. ensureSingle(mainplotinfo.overaxesAbove, 'g', yId);
  47925. // set refs to correct layers as determined by 'abovetraces'
  47926. plotinfo.xlines = mainplotgroup.select('.overlines-' + xLayer).select('.' + xId);
  47927. plotinfo.ylines = mainplotgroup.select('.overlines-' + yLayer).select('.' + yId);
  47928. plotinfo.xaxislayer = mainplotgroup.select('.overaxes-' + xLayer).select('.' + xId);
  47929. plotinfo.yaxislayer = mainplotgroup.select('.overaxes-' + yLayer).select('.' + yId);
  47930. }
  47931. // common attributes for all subplots, overlays or not
  47932. if(!hasOnlyLargeSploms) {
  47933. ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.xaxis._id);
  47934. ensureSingleAndAddDatum(plotinfo.gridlayer, 'g', plotinfo.yaxis._id);
  47935. plotinfo.gridlayer.selectAll('g')
  47936. .map(function(d) { return d[0]; })
  47937. .sort(axisIds.idSort);
  47938. }
  47939. plotinfo.xlines
  47940. .style('fill', 'none')
  47941. .classed('crisp', true);
  47942. plotinfo.ylines
  47943. .style('fill', 'none')
  47944. .classed('crisp', true);
  47945. }
  47946. function purgeSubplotLayers(layers, fullLayout) {
  47947. if(!layers) return;
  47948. var overlayIdsToRemove = {};
  47949. layers.each(function(d) {
  47950. var id = d[0];
  47951. var plotgroup = d3.select(this);
  47952. plotgroup.remove();
  47953. removeSubplotExtras(id, fullLayout);
  47954. overlayIdsToRemove[id] = true;
  47955. // do not remove individual axis <clipPath>s here
  47956. // as other subplots may need them
  47957. });
  47958. // must remove overlaid subplot trace layers 'manually'
  47959. for(var k in fullLayout._plots) {
  47960. var subplotInfo = fullLayout._plots[k];
  47961. var overlays = subplotInfo.overlays || [];
  47962. for(var j = 0; j < overlays.length; j++) {
  47963. var overlayInfo = overlays[j];
  47964. if(overlayIdsToRemove[overlayInfo.id]) {
  47965. overlayInfo.plot.selectAll('.trace').remove();
  47966. }
  47967. }
  47968. }
  47969. }
  47970. function removeSubplotExtras(subplotId, fullLayout) {
  47971. fullLayout._draggers.selectAll('g.' + subplotId).remove();
  47972. fullLayout._defs.select('#clip' + fullLayout._uid + subplotId + 'plot').remove();
  47973. }
  47974. exports.toSVG = function(gd) {
  47975. var imageRoot = gd._fullLayout._glimages;
  47976. var root = d3.select(gd).selectAll('.svg-container');
  47977. var canvases = root.filter(function(d, i) {return i === root.size() - 1;})
  47978. .selectAll('.gl-canvas-context, .gl-canvas-focus');
  47979. function canvasToImage() {
  47980. var canvas = this;
  47981. var imageData = canvas.toDataURL('image/png');
  47982. var image = imageRoot.append('svg:image');
  47983. image.attr({
  47984. xmlns: xmlnsNamespaces.svg,
  47985. 'xlink:href': imageData,
  47986. preserveAspectRatio: 'none',
  47987. x: 0,
  47988. y: 0,
  47989. width: canvas.width,
  47990. height: canvas.height
  47991. });
  47992. }
  47993. canvases.each(canvasToImage);
  47994. };
  47995. exports.updateFx = _dereq_('./graph_interact').updateFx;
  47996. },{"../../components/drawing":72,"../../constants/xmlns_namespaces":150,"../../lib":168,"../../registry":257,"../get_data":241,"../plots":245,"./attributes":210,"./axis_ids":215,"./constants":218,"./graph_interact":222,"./layout_attributes":225,"./layout_defaults":226,"./transition_axes":235,"d3":16}],225:[function(_dereq_,module,exports){
  47997. /**
  47998. * Copyright 2012-2019, Plotly, Inc.
  47999. * All rights reserved.
  48000. *
  48001. * This source code is licensed under the MIT license found in the
  48002. * LICENSE file in the root directory of this source tree.
  48003. */
  48004. 'use strict';
  48005. var fontAttrs = _dereq_('../font_attributes');
  48006. var colorAttrs = _dereq_('../../components/color/attributes');
  48007. var dash = _dereq_('../../components/drawing/attributes').dash;
  48008. var extendFlat = _dereq_('../../lib/extend').extendFlat;
  48009. var templatedArray = _dereq_('../../plot_api/plot_template').templatedArray;
  48010. var constants = _dereq_('./constants');
  48011. module.exports = {
  48012. visible: {
  48013. valType: 'boolean',
  48014. editType: 'plot',
  48015. },
  48016. color: {
  48017. valType: 'color',
  48018. dflt: colorAttrs.defaultLine,
  48019. editType: 'ticks',
  48020. },
  48021. title: {
  48022. text: {
  48023. valType: 'string',
  48024. editType: 'ticks',
  48025. },
  48026. font: fontAttrs({
  48027. editType: 'ticks',
  48028. }),
  48029. editType: 'ticks'
  48030. },
  48031. type: {
  48032. valType: 'enumerated',
  48033. // '-' means we haven't yet run autotype or couldn't find any data
  48034. // it gets turned into linear in gd._fullLayout but not copied back
  48035. // to gd.data like the others are.
  48036. values: ['-', 'linear', 'log', 'date', 'category', 'multicategory'],
  48037. dflt: '-',
  48038. editType: 'calc',
  48039. // we forget when an axis has been autotyped, just writing the auto
  48040. // value back to the input - so it doesn't make sense to template this.
  48041. // Note: we do NOT prohibit this in `coerce`, so if someone enters a
  48042. // type in the template explicitly it will be honored as the default.
  48043. _noTemplating: true,
  48044. },
  48045. autorange: {
  48046. valType: 'enumerated',
  48047. values: [true, false, 'reversed'],
  48048. dflt: true,
  48049. editType: 'axrange',
  48050. impliedEdits: {'range[0]': undefined, 'range[1]': undefined},
  48051. },
  48052. rangemode: {
  48053. valType: 'enumerated',
  48054. values: ['normal', 'tozero', 'nonnegative'],
  48055. dflt: 'normal',
  48056. editType: 'plot',
  48057. },
  48058. range: {
  48059. valType: 'info_array',
  48060. items: [
  48061. {valType: 'any', editType: 'axrange', impliedEdits: {'^autorange': false}, anim: true},
  48062. {valType: 'any', editType: 'axrange', impliedEdits: {'^autorange': false}, anim: true}
  48063. ],
  48064. editType: 'axrange',
  48065. impliedEdits: {'autorange': false},
  48066. anim: true,
  48067. },
  48068. fixedrange: {
  48069. valType: 'boolean',
  48070. dflt: false,
  48071. editType: 'calc',
  48072. },
  48073. // scaleanchor: not used directly, just put here for reference
  48074. // values are any opposite-letter axis id
  48075. scaleanchor: {
  48076. valType: 'enumerated',
  48077. values: [
  48078. constants.idRegex.x.toString(),
  48079. constants.idRegex.y.toString()
  48080. ],
  48081. editType: 'plot',
  48082. },
  48083. scaleratio: {
  48084. valType: 'number',
  48085. min: 0,
  48086. dflt: 1,
  48087. editType: 'plot',
  48088. },
  48089. constrain: {
  48090. valType: 'enumerated',
  48091. values: ['range', 'domain'],
  48092. dflt: 'range',
  48093. editType: 'plot',
  48094. },
  48095. // constraintoward: not used directly, just put here for reference
  48096. constraintoward: {
  48097. valType: 'enumerated',
  48098. values: ['left', 'center', 'right', 'top', 'middle', 'bottom'],
  48099. editType: 'plot',
  48100. },
  48101. // ticks
  48102. tickmode: {
  48103. valType: 'enumerated',
  48104. values: ['auto', 'linear', 'array'],
  48105. editType: 'ticks',
  48106. impliedEdits: {tick0: undefined, dtick: undefined},
  48107. },
  48108. nticks: {
  48109. valType: 'integer',
  48110. min: 0,
  48111. dflt: 0,
  48112. editType: 'ticks',
  48113. },
  48114. tick0: {
  48115. valType: 'any',
  48116. editType: 'ticks',
  48117. impliedEdits: {tickmode: 'linear'},
  48118. },
  48119. dtick: {
  48120. valType: 'any',
  48121. editType: 'ticks',
  48122. impliedEdits: {tickmode: 'linear'},
  48123. },
  48124. tickvals: {
  48125. valType: 'data_array',
  48126. editType: 'ticks',
  48127. },
  48128. ticktext: {
  48129. valType: 'data_array',
  48130. editType: 'ticks',
  48131. },
  48132. ticks: {
  48133. valType: 'enumerated',
  48134. values: ['outside', 'inside', ''],
  48135. editType: 'ticks',
  48136. },
  48137. tickson: {
  48138. valType: 'enumerated',
  48139. values: ['labels', 'boundaries'],
  48140. dflt: 'labels',
  48141. editType: 'ticks',
  48142. },
  48143. mirror: {
  48144. valType: 'enumerated',
  48145. values: [true, 'ticks', false, 'all', 'allticks'],
  48146. dflt: false,
  48147. editType: 'ticks+layoutstyle',
  48148. },
  48149. ticklen: {
  48150. valType: 'number',
  48151. min: 0,
  48152. dflt: 5,
  48153. editType: 'ticks',
  48154. },
  48155. tickwidth: {
  48156. valType: 'number',
  48157. min: 0,
  48158. dflt: 1,
  48159. editType: 'ticks',
  48160. },
  48161. tickcolor: {
  48162. valType: 'color',
  48163. dflt: colorAttrs.defaultLine,
  48164. editType: 'ticks',
  48165. },
  48166. showticklabels: {
  48167. valType: 'boolean',
  48168. dflt: true,
  48169. editType: 'ticks',
  48170. },
  48171. automargin: {
  48172. valType: 'boolean',
  48173. dflt: false,
  48174. editType: 'ticks',
  48175. },
  48176. showspikes: {
  48177. valType: 'boolean',
  48178. dflt: false,
  48179. editType: 'modebar',
  48180. },
  48181. spikecolor: {
  48182. valType: 'color',
  48183. dflt: null,
  48184. editType: 'none',
  48185. },
  48186. spikethickness: {
  48187. valType: 'number',
  48188. dflt: 3,
  48189. editType: 'none',
  48190. },
  48191. spikedash: extendFlat({}, dash, {dflt: 'dash', editType: 'none'}),
  48192. spikemode: {
  48193. valType: 'flaglist',
  48194. flags: ['toaxis', 'across', 'marker'],
  48195. dflt: 'toaxis',
  48196. editType: 'none',
  48197. },
  48198. spikesnap: {
  48199. valType: 'enumerated',
  48200. values: ['data', 'cursor'],
  48201. dflt: 'data',
  48202. editType: 'none',
  48203. },
  48204. tickfont: fontAttrs({
  48205. editType: 'ticks',
  48206. }),
  48207. tickangle: {
  48208. valType: 'angle',
  48209. dflt: 'auto',
  48210. editType: 'ticks',
  48211. },
  48212. tickprefix: {
  48213. valType: 'string',
  48214. dflt: '',
  48215. editType: 'ticks',
  48216. },
  48217. showtickprefix: {
  48218. valType: 'enumerated',
  48219. values: ['all', 'first', 'last', 'none'],
  48220. dflt: 'all',
  48221. editType: 'ticks',
  48222. },
  48223. ticksuffix: {
  48224. valType: 'string',
  48225. dflt: '',
  48226. editType: 'ticks',
  48227. },
  48228. showticksuffix: {
  48229. valType: 'enumerated',
  48230. values: ['all', 'first', 'last', 'none'],
  48231. dflt: 'all',
  48232. editType: 'ticks',
  48233. },
  48234. showexponent: {
  48235. valType: 'enumerated',
  48236. values: ['all', 'first', 'last', 'none'],
  48237. dflt: 'all',
  48238. editType: 'ticks',
  48239. },
  48240. exponentformat: {
  48241. valType: 'enumerated',
  48242. values: ['none', 'e', 'E', 'power', 'SI', 'B'],
  48243. dflt: 'B',
  48244. editType: 'ticks',
  48245. },
  48246. separatethousands: {
  48247. valType: 'boolean',
  48248. dflt: false,
  48249. editType: 'ticks',
  48250. },
  48251. tickformat: {
  48252. valType: 'string',
  48253. dflt: '',
  48254. editType: 'ticks',
  48255. },
  48256. tickformatstops: templatedArray('tickformatstop', {
  48257. enabled: {
  48258. valType: 'boolean',
  48259. dflt: true,
  48260. editType: 'ticks',
  48261. },
  48262. dtickrange: {
  48263. valType: 'info_array',
  48264. items: [
  48265. {valType: 'any', editType: 'ticks'},
  48266. {valType: 'any', editType: 'ticks'}
  48267. ],
  48268. editType: 'ticks',
  48269. },
  48270. value: {
  48271. valType: 'string',
  48272. dflt: '',
  48273. editType: 'ticks',
  48274. },
  48275. editType: 'ticks'
  48276. }),
  48277. hoverformat: {
  48278. valType: 'string',
  48279. dflt: '',
  48280. editType: 'none',
  48281. },
  48282. // lines and grids
  48283. showline: {
  48284. valType: 'boolean',
  48285. dflt: false,
  48286. editType: 'ticks+layoutstyle',
  48287. },
  48288. linecolor: {
  48289. valType: 'color',
  48290. dflt: colorAttrs.defaultLine,
  48291. editType: 'layoutstyle',
  48292. },
  48293. linewidth: {
  48294. valType: 'number',
  48295. min: 0,
  48296. dflt: 1,
  48297. editType: 'ticks+layoutstyle',
  48298. },
  48299. showgrid: {
  48300. valType: 'boolean',
  48301. editType: 'ticks',
  48302. },
  48303. gridcolor: {
  48304. valType: 'color',
  48305. dflt: colorAttrs.lightLine,
  48306. editType: 'ticks',
  48307. },
  48308. gridwidth: {
  48309. valType: 'number',
  48310. min: 0,
  48311. dflt: 1,
  48312. editType: 'ticks',
  48313. },
  48314. zeroline: {
  48315. valType: 'boolean',
  48316. editType: 'ticks',
  48317. },
  48318. zerolinecolor: {
  48319. valType: 'color',
  48320. dflt: colorAttrs.defaultLine,
  48321. editType: 'ticks',
  48322. },
  48323. zerolinewidth: {
  48324. valType: 'number',
  48325. dflt: 1,
  48326. editType: 'ticks',
  48327. },
  48328. showdividers: {
  48329. valType: 'boolean',
  48330. dflt: true,
  48331. editType: 'ticks',
  48332. },
  48333. dividercolor: {
  48334. valType: 'color',
  48335. dflt: colorAttrs.defaultLine,
  48336. editType: 'ticks',
  48337. },
  48338. dividerwidth: {
  48339. valType: 'number',
  48340. dflt: 1,
  48341. editType: 'ticks',
  48342. },
  48343. // TODO dividerlen: that would override "to label base" length?
  48344. // positioning attributes
  48345. // anchor: not used directly, just put here for reference
  48346. // values are any opposite-letter axis id
  48347. anchor: {
  48348. valType: 'enumerated',
  48349. values: [
  48350. 'free',
  48351. constants.idRegex.x.toString(),
  48352. constants.idRegex.y.toString()
  48353. ],
  48354. editType: 'plot',
  48355. },
  48356. // side: not used directly, as values depend on direction
  48357. // values are top, bottom for x axes, and left, right for y
  48358. side: {
  48359. valType: 'enumerated',
  48360. values: ['top', 'bottom', 'left', 'right'],
  48361. editType: 'plot',
  48362. },
  48363. // overlaying: not used directly, just put here for reference
  48364. // values are false and any other same-letter axis id that's not
  48365. // itself overlaying anything
  48366. overlaying: {
  48367. valType: 'enumerated',
  48368. values: [
  48369. 'free',
  48370. constants.idRegex.x.toString(),
  48371. constants.idRegex.y.toString()
  48372. ],
  48373. editType: 'plot',
  48374. },
  48375. layer: {
  48376. valType: 'enumerated',
  48377. values: ['above traces', 'below traces'],
  48378. dflt: 'above traces',
  48379. editType: 'plot',
  48380. },
  48381. domain: {
  48382. valType: 'info_array',
  48383. items: [
  48384. {valType: 'number', min: 0, max: 1, editType: 'plot'},
  48385. {valType: 'number', min: 0, max: 1, editType: 'plot'}
  48386. ],
  48387. dflt: [0, 1],
  48388. editType: 'plot',
  48389. },
  48390. position: {
  48391. valType: 'number',
  48392. min: 0,
  48393. max: 1,
  48394. dflt: 0,
  48395. editType: 'plot',
  48396. },
  48397. categoryorder: {
  48398. valType: 'enumerated',
  48399. values: [
  48400. 'trace', 'category ascending', 'category descending', 'array'
  48401. /* , 'value ascending', 'value descending'*/ // value ascending / descending to be implemented later
  48402. ],
  48403. dflt: 'trace',
  48404. editType: 'calc',
  48405. },
  48406. categoryarray: {
  48407. valType: 'data_array',
  48408. editType: 'calc',
  48409. },
  48410. uirevision: {
  48411. valType: 'any',
  48412. editType: 'none',
  48413. },
  48414. editType: 'calc',
  48415. _deprecated: {
  48416. autotick: {
  48417. valType: 'boolean',
  48418. editType: 'ticks',
  48419. },
  48420. title: {
  48421. valType: 'string',
  48422. editType: 'ticks',
  48423. },
  48424. titlefont: fontAttrs({
  48425. editType: 'ticks',
  48426. })
  48427. }
  48428. };
  48429. },{"../../components/color/attributes":50,"../../components/drawing/attributes":71,"../../lib/extend":162,"../../plot_api/plot_template":202,"../font_attributes":239,"./constants":218}],226:[function(_dereq_,module,exports){
  48430. /**
  48431. * Copyright 2012-2019, Plotly, Inc.
  48432. * All rights reserved.
  48433. *
  48434. * This source code is licensed under the MIT license found in the
  48435. * LICENSE file in the root directory of this source tree.
  48436. */
  48437. 'use strict';
  48438. var Lib = _dereq_('../../lib');
  48439. var Color = _dereq_('../../components/color');
  48440. var Template = _dereq_('../../plot_api/plot_template');
  48441. var basePlotLayoutAttributes = _dereq_('../layout_attributes');
  48442. var layoutAttributes = _dereq_('./layout_attributes');
  48443. var handleTypeDefaults = _dereq_('./type_defaults');
  48444. var handleAxisDefaults = _dereq_('./axis_defaults');
  48445. var handleConstraintDefaults = _dereq_('./constraint_defaults');
  48446. var handlePositionDefaults = _dereq_('./position_defaults');
  48447. var axisIds = _dereq_('./axis_ids');
  48448. var id2name = axisIds.id2name;
  48449. var name2id = axisIds.name2id;
  48450. var Registry = _dereq_('../../registry');
  48451. var traceIs = Registry.traceIs;
  48452. var getComponentMethod = Registry.getComponentMethod;
  48453. function appendList(cont, k, item) {
  48454. if(Array.isArray(cont[k])) cont[k].push(item);
  48455. else cont[k] = [item];
  48456. }
  48457. module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
  48458. var ax2traces = {};
  48459. var xaCheater = {};
  48460. var xaNonCheater = {};
  48461. var outerTicks = {};
  48462. var noGrids = {};
  48463. var i, j;
  48464. // look for axes in the data
  48465. for(i = 0; i < fullData.length; i++) {
  48466. var trace = fullData[i];
  48467. if(!traceIs(trace, 'cartesian') && !traceIs(trace, 'gl2d')) continue;
  48468. var xaName;
  48469. if(trace.xaxis) {
  48470. xaName = id2name(trace.xaxis);
  48471. appendList(ax2traces, xaName, trace);
  48472. } else if(trace.xaxes) {
  48473. for(j = 0; j < trace.xaxes.length; j++) {
  48474. appendList(ax2traces, id2name(trace.xaxes[j]), trace);
  48475. }
  48476. }
  48477. var yaName;
  48478. if(trace.yaxis) {
  48479. yaName = id2name(trace.yaxis);
  48480. appendList(ax2traces, yaName, trace);
  48481. } else if(trace.yaxes) {
  48482. for(j = 0; j < trace.yaxes.length; j++) {
  48483. appendList(ax2traces, id2name(trace.yaxes[j]), trace);
  48484. }
  48485. }
  48486. // Two things trigger axis visibility:
  48487. // 1. is not carpet
  48488. // 2. carpet that's not cheater
  48489. if(!traceIs(trace, 'carpet') || (trace.type === 'carpet' && !trace._cheater)) {
  48490. if(xaName) xaNonCheater[xaName] = 1;
  48491. }
  48492. // The above check for definitely-not-cheater is not adequate. This
  48493. // second list tracks which axes *could* be a cheater so that the
  48494. // full condition triggering hiding is:
  48495. // *could* be a cheater and *is not definitely visible*
  48496. if(trace.type === 'carpet' && trace._cheater) {
  48497. if(xaName) xaCheater[xaName] = 1;
  48498. }
  48499. // check for default formatting tweaks
  48500. if(traceIs(trace, '2dMap')) {
  48501. outerTicks[xaName] = 1;
  48502. outerTicks[yaName] = 1;
  48503. }
  48504. if(traceIs(trace, 'oriented')) {
  48505. var positionAxis = trace.orientation === 'h' ? yaName : xaName;
  48506. noGrids[positionAxis] = 1;
  48507. }
  48508. }
  48509. var subplots = layoutOut._subplots;
  48510. var xIds = subplots.xaxis;
  48511. var yIds = subplots.yaxis;
  48512. var xNames = Lib.simpleMap(xIds, id2name);
  48513. var yNames = Lib.simpleMap(yIds, id2name);
  48514. var axNames = xNames.concat(yNames);
  48515. // plot_bgcolor only makes sense if there's a (2D) plot!
  48516. // TODO: bgcolor for each subplot, to inherit from the main one
  48517. var plotBgColor = Color.background;
  48518. if(xIds.length && yIds.length) {
  48519. plotBgColor = Lib.coerce(layoutIn, layoutOut, basePlotLayoutAttributes, 'plot_bgcolor');
  48520. }
  48521. var bgColor = Color.combine(plotBgColor, layoutOut.paper_bgcolor);
  48522. var axName, axLetter, axLayoutIn, axLayoutOut;
  48523. function coerce(attr, dflt) {
  48524. return Lib.coerce(axLayoutIn, axLayoutOut, layoutAttributes, attr, dflt);
  48525. }
  48526. function coerce2(attr, dflt) {
  48527. return Lib.coerce2(axLayoutIn, axLayoutOut, layoutAttributes, attr, dflt);
  48528. }
  48529. function getCounterAxes(axLetter) {
  48530. return (axLetter === 'x') ? yIds : xIds;
  48531. }
  48532. var counterAxes = {x: getCounterAxes('x'), y: getCounterAxes('y')};
  48533. function getOverlayableAxes(axLetter, axName) {
  48534. var list = (axLetter === 'x') ? xNames : yNames;
  48535. var out = [];
  48536. for(var j = 0; j < list.length; j++) {
  48537. var axName2 = list[j];
  48538. if(axName2 !== axName && !(layoutIn[axName2] || {}).overlaying) {
  48539. out.push(name2id(axName2));
  48540. }
  48541. }
  48542. return out;
  48543. }
  48544. // first pass creates the containers, determines types, and handles most of the settings
  48545. for(i = 0; i < axNames.length; i++) {
  48546. axName = axNames[i];
  48547. axLetter = axName.charAt(0);
  48548. if(!Lib.isPlainObject(layoutIn[axName])) {
  48549. layoutIn[axName] = {};
  48550. }
  48551. axLayoutIn = layoutIn[axName];
  48552. axLayoutOut = Template.newContainer(layoutOut, axName, axLetter + 'axis');
  48553. var traces = ax2traces[axName] || [];
  48554. axLayoutOut._traceIndices = traces.map(function(t) { return t._expandedIndex; });
  48555. axLayoutOut._annIndices = [];
  48556. axLayoutOut._shapeIndices = [];
  48557. axLayoutOut._imgIndices = [];
  48558. axLayoutOut._subplotsWith = [];
  48559. axLayoutOut._counterAxes = [];
  48560. // set up some private properties
  48561. axLayoutOut._name = axLayoutOut._attr = axName;
  48562. var id = axLayoutOut._id = name2id(axName);
  48563. var overlayableAxes = getOverlayableAxes(axLetter, axName);
  48564. var defaultOptions = {
  48565. letter: axLetter,
  48566. font: layoutOut.font,
  48567. outerTicks: outerTicks[axName],
  48568. showGrid: !noGrids[axName],
  48569. data: traces,
  48570. bgColor: bgColor,
  48571. calendar: layoutOut.calendar,
  48572. automargin: true,
  48573. cheateronly: axLetter === 'x' && xaCheater[axName] && !xaNonCheater[axName],
  48574. splomStash: ((layoutOut._splomAxes || {})[axLetter] || {})[id]
  48575. };
  48576. coerce('uirevision', layoutOut.uirevision);
  48577. handleTypeDefaults(axLayoutIn, axLayoutOut, coerce, defaultOptions);
  48578. handleAxisDefaults(axLayoutIn, axLayoutOut, coerce, defaultOptions, layoutOut);
  48579. var spikecolor = coerce2('spikecolor');
  48580. var spikethickness = coerce2('spikethickness');
  48581. var spikedash = coerce2('spikedash');
  48582. var spikemode = coerce2('spikemode');
  48583. var spikesnap = coerce2('spikesnap');
  48584. var showSpikes = coerce('showspikes', !!spikecolor || !!spikethickness || !!spikedash || !!spikemode || !!spikesnap);
  48585. if(!showSpikes) {
  48586. delete axLayoutOut.spikecolor;
  48587. delete axLayoutOut.spikethickness;
  48588. delete axLayoutOut.spikedash;
  48589. delete axLayoutOut.spikemode;
  48590. delete axLayoutOut.spikesnap;
  48591. }
  48592. var positioningOptions = {
  48593. letter: axLetter,
  48594. counterAxes: counterAxes[axLetter],
  48595. overlayableAxes: overlayableAxes,
  48596. grid: layoutOut.grid
  48597. };
  48598. handlePositionDefaults(axLayoutIn, axLayoutOut, coerce, positioningOptions);
  48599. axLayoutOut._input = axLayoutIn;
  48600. }
  48601. // quick second pass for range slider and selector defaults
  48602. var rangeSliderDefaults = getComponentMethod('rangeslider', 'handleDefaults');
  48603. var rangeSelectorDefaults = getComponentMethod('rangeselector', 'handleDefaults');
  48604. for(i = 0; i < xNames.length; i++) {
  48605. axName = xNames[i];
  48606. axLayoutIn = layoutIn[axName];
  48607. axLayoutOut = layoutOut[axName];
  48608. rangeSliderDefaults(layoutIn, layoutOut, axName);
  48609. if(axLayoutOut.type === 'date') {
  48610. rangeSelectorDefaults(
  48611. axLayoutIn,
  48612. axLayoutOut,
  48613. layoutOut,
  48614. yNames,
  48615. axLayoutOut.calendar
  48616. );
  48617. }
  48618. coerce('fixedrange');
  48619. }
  48620. for(i = 0; i < yNames.length; i++) {
  48621. axName = yNames[i];
  48622. axLayoutIn = layoutIn[axName];
  48623. axLayoutOut = layoutOut[axName];
  48624. var anchoredAxis = layoutOut[id2name(axLayoutOut.anchor)];
  48625. var fixedRangeDflt = getComponentMethod('rangeslider', 'isVisible')(anchoredAxis);
  48626. coerce('fixedrange', fixedRangeDflt);
  48627. }
  48628. // Finally, handle scale constraints. We need to do this after all axes have
  48629. // coerced both `type` (so we link only axes of the same type) and
  48630. // `fixedrange` (so we can avoid linking from OR TO a fixed axis).
  48631. // sets of axes linked by `scaleanchor` along with the scaleratios compounded
  48632. // together, populated in handleConstraintDefaults
  48633. layoutOut._axisConstraintGroups = [];
  48634. var allAxisIds = counterAxes.x.concat(counterAxes.y);
  48635. for(i = 0; i < axNames.length; i++) {
  48636. axName = axNames[i];
  48637. axLetter = axName.charAt(0);
  48638. axLayoutIn = layoutIn[axName];
  48639. axLayoutOut = layoutOut[axName];
  48640. handleConstraintDefaults(axLayoutIn, axLayoutOut, coerce, allAxisIds, layoutOut);
  48641. }
  48642. };
  48643. },{"../../components/color":51,"../../lib":168,"../../plot_api/plot_template":202,"../../registry":257,"../layout_attributes":243,"./axis_defaults":214,"./axis_ids":215,"./constraint_defaults":219,"./layout_attributes":225,"./position_defaults":228,"./type_defaults":236}],227:[function(_dereq_,module,exports){
  48644. /**
  48645. * Copyright 2012-2019, Plotly, Inc.
  48646. * All rights reserved.
  48647. *
  48648. * This source code is licensed under the MIT license found in the
  48649. * LICENSE file in the root directory of this source tree.
  48650. */
  48651. 'use strict';
  48652. var colorMix = _dereq_('tinycolor2').mix;
  48653. var lightFraction = _dereq_('../../components/color/attributes').lightFraction;
  48654. var Lib = _dereq_('../../lib');
  48655. /**
  48656. * @param {object} opts :
  48657. * - dfltColor {string} : default axis color
  48658. * - bgColor {string} : combined subplot bg color
  48659. * - blend {number, optional} : blend percentage (to compute dflt grid color)
  48660. * - showLine {boolean} : show line by default
  48661. * - showGrid {boolean} : show grid by default
  48662. * - noZeroLine {boolean} : don't coerce zeroline* attributes
  48663. * - attributes {object} : attribute object associated with input containers
  48664. */
  48665. module.exports = function handleLineGridDefaults(containerIn, containerOut, coerce, opts) {
  48666. opts = opts || {};
  48667. var dfltColor = opts.dfltColor;
  48668. function coerce2(attr, dflt) {
  48669. return Lib.coerce2(containerIn, containerOut, opts.attributes, attr, dflt);
  48670. }
  48671. var lineColor = coerce2('linecolor', dfltColor);
  48672. var lineWidth = coerce2('linewidth');
  48673. var showLine = coerce('showline', opts.showLine || !!lineColor || !!lineWidth);
  48674. if(!showLine) {
  48675. delete containerOut.linecolor;
  48676. delete containerOut.linewidth;
  48677. }
  48678. var gridColorDflt = colorMix(dfltColor, opts.bgColor, opts.blend || lightFraction).toRgbString();
  48679. var gridColor = coerce2('gridcolor', gridColorDflt);
  48680. var gridWidth = coerce2('gridwidth');
  48681. var showGridLines = coerce('showgrid', opts.showGrid || !!gridColor || !!gridWidth);
  48682. if(!showGridLines) {
  48683. delete containerOut.gridcolor;
  48684. delete containerOut.gridwidth;
  48685. }
  48686. if(!opts.noZeroLine) {
  48687. var zeroLineColor = coerce2('zerolinecolor', dfltColor);
  48688. var zeroLineWidth = coerce2('zerolinewidth');
  48689. var showZeroLine = coerce('zeroline', opts.showGrid || !!zeroLineColor || !!zeroLineWidth);
  48690. if(!showZeroLine) {
  48691. delete containerOut.zerolinecolor;
  48692. delete containerOut.zerolinewidth;
  48693. }
  48694. }
  48695. };
  48696. },{"../../components/color/attributes":50,"../../lib":168,"tinycolor2":34}],228:[function(_dereq_,module,exports){
  48697. /**
  48698. * Copyright 2012-2019, Plotly, Inc.
  48699. * All rights reserved.
  48700. *
  48701. * This source code is licensed under the MIT license found in the
  48702. * LICENSE file in the root directory of this source tree.
  48703. */
  48704. 'use strict';
  48705. var isNumeric = _dereq_('fast-isnumeric');
  48706. var Lib = _dereq_('../../lib');
  48707. module.exports = function handlePositionDefaults(containerIn, containerOut, coerce, options) {
  48708. var counterAxes = options.counterAxes || [];
  48709. var overlayableAxes = options.overlayableAxes || [];
  48710. var letter = options.letter;
  48711. var grid = options.grid;
  48712. var dfltAnchor, dfltDomain, dfltSide, dfltPosition;
  48713. if(grid) {
  48714. dfltDomain = grid._domains[letter][grid._axisMap[containerOut._id]];
  48715. dfltAnchor = grid._anchors[containerOut._id];
  48716. if(dfltDomain) {
  48717. dfltSide = grid[letter + 'side'].split(' ')[0];
  48718. dfltPosition = grid.domain[letter][dfltSide === 'right' || dfltSide === 'top' ? 1 : 0];
  48719. }
  48720. }
  48721. // Even if there's a grid, this axis may not be in it - fall back on non-grid defaults
  48722. dfltDomain = dfltDomain || [0, 1];
  48723. dfltAnchor = dfltAnchor || (isNumeric(containerIn.position) ? 'free' : (counterAxes[0] || 'free'));
  48724. dfltSide = dfltSide || (letter === 'x' ? 'bottom' : 'left');
  48725. dfltPosition = dfltPosition || 0;
  48726. var anchor = Lib.coerce(containerIn, containerOut, {
  48727. anchor: {
  48728. valType: 'enumerated',
  48729. values: ['free'].concat(counterAxes),
  48730. dflt: dfltAnchor
  48731. }
  48732. }, 'anchor');
  48733. if(anchor === 'free') coerce('position', dfltPosition);
  48734. Lib.coerce(containerIn, containerOut, {
  48735. side: {
  48736. valType: 'enumerated',
  48737. values: letter === 'x' ? ['bottom', 'top'] : ['left', 'right'],
  48738. dflt: dfltSide
  48739. }
  48740. }, 'side');
  48741. var overlaying = false;
  48742. if(overlayableAxes.length) {
  48743. overlaying = Lib.coerce(containerIn, containerOut, {
  48744. overlaying: {
  48745. valType: 'enumerated',
  48746. values: [false].concat(overlayableAxes),
  48747. dflt: false
  48748. }
  48749. }, 'overlaying');
  48750. }
  48751. if(!overlaying) {
  48752. // TODO: right now I'm copying this domain over to overlaying axes
  48753. // in ax.setscale()... but this means we still need (imperfect) logic
  48754. // in the axes popover to hide domain for the overlaying axis.
  48755. // perhaps I should make a private version _domain that all axes get???
  48756. var domain = coerce('domain', dfltDomain);
  48757. // according to https://www.npmjs.com/package/canvas-size
  48758. // the minimum value of max canvas width across browsers and devices is 4096
  48759. // which applied in the calculation below:
  48760. if(domain[0] > domain[1] - 1 / 4096) containerOut.domain = dfltDomain;
  48761. Lib.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain);
  48762. }
  48763. coerce('layer');
  48764. return containerOut;
  48765. };
  48766. },{"../../lib":168,"fast-isnumeric":18}],229:[function(_dereq_,module,exports){
  48767. /**
  48768. * Copyright 2012-2019, Plotly, Inc.
  48769. * All rights reserved.
  48770. *
  48771. * This source code is licensed under the MIT license found in the
  48772. * LICENSE file in the root directory of this source tree.
  48773. */
  48774. 'use strict';
  48775. var FROM_BL = _dereq_('../../constants/alignment').FROM_BL;
  48776. module.exports = function scaleZoom(ax, factor, centerFraction) {
  48777. if(centerFraction === undefined) {
  48778. centerFraction = FROM_BL[ax.constraintoward || 'center'];
  48779. }
  48780. var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])];
  48781. var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction;
  48782. ax.range = ax._input.range = [
  48783. ax.l2r(center + (rangeLinear[0] - center) * factor),
  48784. ax.l2r(center + (rangeLinear[1] - center) * factor)
  48785. ];
  48786. };
  48787. },{"../../constants/alignment":146}],230:[function(_dereq_,module,exports){
  48788. /**
  48789. * Copyright 2012-2019, Plotly, Inc.
  48790. * All rights reserved.
  48791. *
  48792. * This source code is licensed under the MIT license found in the
  48793. * LICENSE file in the root directory of this source tree.
  48794. */
  48795. 'use strict';
  48796. var polybool = _dereq_('polybooljs');
  48797. var Registry = _dereq_('../../registry');
  48798. var Color = _dereq_('../../components/color');
  48799. var Fx = _dereq_('../../components/fx');
  48800. var polygon = _dereq_('../../lib/polygon');
  48801. var throttle = _dereq_('../../lib/throttle');
  48802. var makeEventData = _dereq_('../../components/fx/helpers').makeEventData;
  48803. var getFromId = _dereq_('./axis_ids').getFromId;
  48804. var clearGlCanvases = _dereq_('../../lib/clear_gl_canvases');
  48805. var redrawReglTraces = _dereq_('../../plot_api/subroutines').redrawReglTraces;
  48806. var constants = _dereq_('./constants');
  48807. var MINSELECT = constants.MINSELECT;
  48808. var filteredPolygon = polygon.filter;
  48809. var polygonTester = polygon.tester;
  48810. function getAxId(ax) { return ax._id; }
  48811. function prepSelect(e, startX, startY, dragOptions, mode) {
  48812. var gd = dragOptions.gd;
  48813. var fullLayout = gd._fullLayout;
  48814. var zoomLayer = fullLayout._zoomlayer;
  48815. var dragBBox = dragOptions.element.getBoundingClientRect();
  48816. var plotinfo = dragOptions.plotinfo;
  48817. var xs = plotinfo.xaxis._offset;
  48818. var ys = plotinfo.yaxis._offset;
  48819. var x0 = startX - dragBBox.left;
  48820. var y0 = startY - dragBBox.top;
  48821. var x1 = x0;
  48822. var y1 = y0;
  48823. var path0 = 'M' + x0 + ',' + y0;
  48824. var pw = dragOptions.xaxes[0]._length;
  48825. var ph = dragOptions.yaxes[0]._length;
  48826. var allAxes = dragOptions.xaxes.concat(dragOptions.yaxes);
  48827. var subtract = e.altKey;
  48828. var filterPoly, selectionTester, mergedPolygons, currentPolygon;
  48829. var i, searchInfo, eventData;
  48830. coerceSelectionsCache(e, gd, dragOptions);
  48831. if(mode === 'lasso') {
  48832. filterPoly = filteredPolygon([[x0, y0]], constants.BENDPX);
  48833. }
  48834. var outlines = zoomLayer.selectAll('path.select-outline-' + plotinfo.id).data([1, 2]);
  48835. outlines.enter()
  48836. .append('path')
  48837. .attr('class', function(d) { return 'select-outline select-outline-' + d + ' select-outline-' + plotinfo.id; })
  48838. .attr('transform', 'translate(' + xs + ', ' + ys + ')')
  48839. .attr('d', path0 + 'Z');
  48840. var corners = zoomLayer.append('path')
  48841. .attr('class', 'zoombox-corners')
  48842. .style({
  48843. fill: Color.background,
  48844. stroke: Color.defaultLine,
  48845. 'stroke-width': 1
  48846. })
  48847. .attr('transform', 'translate(' + xs + ', ' + ys + ')')
  48848. .attr('d', 'M0,0Z');
  48849. var throttleID = fullLayout._uid + constants.SELECTID;
  48850. var selection = [];
  48851. // find the traces to search for selection points
  48852. var searchTraces = determineSearchTraces(gd, dragOptions.xaxes,
  48853. dragOptions.yaxes, dragOptions.subplot);
  48854. function axValue(ax) {
  48855. var index = (ax._id.charAt(0) === 'y') ? 1 : 0;
  48856. return function(v) { return ax.p2d(v[index]); };
  48857. }
  48858. function ascending(a, b) { return a - b; }
  48859. // allow subplots to override fillRangeItems routine
  48860. var fillRangeItems;
  48861. if(plotinfo.fillRangeItems) {
  48862. fillRangeItems = plotinfo.fillRangeItems;
  48863. } else {
  48864. if(mode === 'select') {
  48865. fillRangeItems = function(eventData, poly) {
  48866. var ranges = eventData.range = {};
  48867. for(i = 0; i < allAxes.length; i++) {
  48868. var ax = allAxes[i];
  48869. var axLetter = ax._id.charAt(0);
  48870. ranges[ax._id] = [
  48871. ax.p2d(poly[axLetter + 'min']),
  48872. ax.p2d(poly[axLetter + 'max'])
  48873. ].sort(ascending);
  48874. }
  48875. };
  48876. } else {
  48877. fillRangeItems = function(eventData, poly, filterPoly) {
  48878. var dataPts = eventData.lassoPoints = {};
  48879. for(i = 0; i < allAxes.length; i++) {
  48880. var ax = allAxes[i];
  48881. dataPts[ax._id] = filterPoly.filtered.map(axValue(ax));
  48882. }
  48883. };
  48884. }
  48885. }
  48886. dragOptions.moveFn = function(dx0, dy0) {
  48887. x1 = Math.max(0, Math.min(pw, dx0 + x0));
  48888. y1 = Math.max(0, Math.min(ph, dy0 + y0));
  48889. var dx = Math.abs(x1 - x0);
  48890. var dy = Math.abs(y1 - y0);
  48891. if(mode === 'select') {
  48892. var direction = fullLayout.selectdirection;
  48893. if(fullLayout.selectdirection === 'any') {
  48894. if(dy < Math.min(dx * 0.6, MINSELECT)) direction = 'h';
  48895. else if(dx < Math.min(dy * 0.6, MINSELECT)) direction = 'v';
  48896. else direction = 'd';
  48897. }
  48898. else {
  48899. direction = fullLayout.selectdirection;
  48900. }
  48901. if(direction === 'h') {
  48902. // horizontal motion: make a vertical box
  48903. currentPolygon = [[x0, 0], [x0, ph], [x1, ph], [x1, 0]];
  48904. currentPolygon.xmin = Math.min(x0, x1);
  48905. currentPolygon.xmax = Math.max(x0, x1);
  48906. currentPolygon.ymin = Math.min(0, ph);
  48907. currentPolygon.ymax = Math.max(0, ph);
  48908. // extras to guide users in keeping a straight selection
  48909. corners.attr('d', 'M' + currentPolygon.xmin + ',' + (y0 - MINSELECT) +
  48910. 'h-4v' + (2 * MINSELECT) + 'h4Z' +
  48911. 'M' + (currentPolygon.xmax - 1) + ',' + (y0 - MINSELECT) +
  48912. 'h4v' + (2 * MINSELECT) + 'h-4Z');
  48913. }
  48914. else if(direction === 'v') {
  48915. // vertical motion: make a horizontal box
  48916. currentPolygon = [[0, y0], [0, y1], [pw, y1], [pw, y0]];
  48917. currentPolygon.xmin = Math.min(0, pw);
  48918. currentPolygon.xmax = Math.max(0, pw);
  48919. currentPolygon.ymin = Math.min(y0, y1);
  48920. currentPolygon.ymax = Math.max(y0, y1);
  48921. corners.attr('d', 'M' + (x0 - MINSELECT) + ',' + currentPolygon.ymin +
  48922. 'v-4h' + (2 * MINSELECT) + 'v4Z' +
  48923. 'M' + (x0 - MINSELECT) + ',' + (currentPolygon.ymax - 1) +
  48924. 'v4h' + (2 * MINSELECT) + 'v-4Z');
  48925. }
  48926. else if(direction === 'd') {
  48927. // diagonal motion
  48928. currentPolygon = [[x0, y0], [x0, y1], [x1, y1], [x1, y0]];
  48929. currentPolygon.xmin = Math.min(x0, x1);
  48930. currentPolygon.xmax = Math.max(x0, x1);
  48931. currentPolygon.ymin = Math.min(y0, y1);
  48932. currentPolygon.ymax = Math.max(y0, y1);
  48933. corners.attr('d', 'M0,0Z');
  48934. }
  48935. }
  48936. else if(mode === 'lasso') {
  48937. filterPoly.addPt([x1, y1]);
  48938. currentPolygon = filterPoly.filtered;
  48939. }
  48940. // create outline & tester
  48941. if(dragOptions.selectionDefs && dragOptions.selectionDefs.length) {
  48942. mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract);
  48943. currentPolygon.subtract = subtract;
  48944. selectionTester = multiTester(dragOptions.selectionDefs.concat([currentPolygon]));
  48945. }
  48946. else {
  48947. mergedPolygons = [currentPolygon];
  48948. selectionTester = polygonTester(currentPolygon);
  48949. }
  48950. // draw selection
  48951. drawSelection(mergedPolygons, outlines);
  48952. throttle.throttle(
  48953. throttleID,
  48954. constants.SELECTDELAY,
  48955. function() {
  48956. selection = [];
  48957. var thisSelection;
  48958. var traceSelections = [];
  48959. var traceSelection;
  48960. for(i = 0; i < searchTraces.length; i++) {
  48961. searchInfo = searchTraces[i];
  48962. traceSelection = searchInfo._module.selectPoints(searchInfo, selectionTester);
  48963. traceSelections.push(traceSelection);
  48964. thisSelection = fillSelectionItem(traceSelection, searchInfo);
  48965. if(selection.length) {
  48966. for(var j = 0; j < thisSelection.length; j++) {
  48967. selection.push(thisSelection[j]);
  48968. }
  48969. }
  48970. else selection = thisSelection;
  48971. }
  48972. eventData = {points: selection};
  48973. updateSelectedState(gd, searchTraces, eventData);
  48974. fillRangeItems(eventData, currentPolygon, filterPoly);
  48975. dragOptions.gd.emit('plotly_selecting', eventData);
  48976. }
  48977. );
  48978. };
  48979. dragOptions.clickFn = function(numClicks, evt) {
  48980. var clickmode = fullLayout.clickmode;
  48981. corners.remove();
  48982. throttle.done(throttleID).then(function() {
  48983. throttle.clear(throttleID);
  48984. if(numClicks === 2) {
  48985. // clear selection on doubleclick
  48986. outlines.remove();
  48987. for(i = 0; i < searchTraces.length; i++) {
  48988. searchInfo = searchTraces[i];
  48989. searchInfo._module.selectPoints(searchInfo, false);
  48990. }
  48991. updateSelectedState(gd, searchTraces);
  48992. clearSelectionsCache(dragOptions);
  48993. gd.emit('plotly_deselect', null);
  48994. } else {
  48995. if(clickmode.indexOf('select') > -1) {
  48996. selectOnClick(evt, gd, dragOptions.xaxes, dragOptions.yaxes,
  48997. dragOptions.subplot, dragOptions, outlines);
  48998. }
  48999. if(clickmode === 'event') {
  49000. // TODO: remove in v2 - this was probably never intended to work as it does,
  49001. // but in case anyone depends on it we don't want to break it now.
  49002. // Note that click-to-select introduced pre v2 also emitts proper
  49003. // event data when clickmode is having 'select' in its flag list.
  49004. gd.emit('plotly_selected', undefined);
  49005. }
  49006. }
  49007. Fx.click(gd, evt);
  49008. });
  49009. };
  49010. dragOptions.doneFn = function() {
  49011. corners.remove();
  49012. throttle.done(throttleID).then(function() {
  49013. throttle.clear(throttleID);
  49014. dragOptions.gd.emit('plotly_selected', eventData);
  49015. if(currentPolygon && dragOptions.selectionDefs) {
  49016. // save last polygons
  49017. currentPolygon.subtract = subtract;
  49018. dragOptions.selectionDefs.push(currentPolygon);
  49019. // we have to keep reference to arrays container
  49020. dragOptions.mergedPolygons.length = 0;
  49021. [].push.apply(dragOptions.mergedPolygons, mergedPolygons);
  49022. }
  49023. });
  49024. };
  49025. }
  49026. function selectOnClick(evt, gd, xAxes, yAxes, subplot, dragOptions, polygonOutlines) {
  49027. var hoverData = gd._hoverdata;
  49028. var clickmode = gd._fullLayout.clickmode;
  49029. var sendEvents = clickmode.indexOf('event') > -1;
  49030. var selection = [];
  49031. var searchTraces, searchInfo, currentSelectionDef, selectionTester, traceSelection;
  49032. var thisTracesSelection, pointOrBinSelected, subtract, eventData, i;
  49033. if(isHoverDataSet(hoverData)) {
  49034. coerceSelectionsCache(evt, gd, dragOptions);
  49035. searchTraces = determineSearchTraces(gd, xAxes, yAxes, subplot);
  49036. var clickedPtInfo = extractClickedPtInfo(hoverData, searchTraces);
  49037. var isBinnedTrace = clickedPtInfo.pointNumbers.length > 0;
  49038. // Note: potentially costly operation isPointOrBinSelected is
  49039. // called as late as possible through the use of an assignment
  49040. // in an if condition.
  49041. if(isBinnedTrace ?
  49042. isOnlyThisBinSelected(searchTraces, clickedPtInfo) :
  49043. isOnlyOnePointSelected(searchTraces) &&
  49044. (pointOrBinSelected = isPointOrBinSelected(clickedPtInfo)))
  49045. {
  49046. if(polygonOutlines) polygonOutlines.remove();
  49047. for(i = 0; i < searchTraces.length; i++) {
  49048. searchInfo = searchTraces[i];
  49049. searchInfo._module.selectPoints(searchInfo, false);
  49050. }
  49051. updateSelectedState(gd, searchTraces);
  49052. clearSelectionsCache(dragOptions);
  49053. if(sendEvents) {
  49054. gd.emit('plotly_deselect', null);
  49055. }
  49056. } else {
  49057. subtract = evt.shiftKey &&
  49058. (pointOrBinSelected !== undefined ?
  49059. pointOrBinSelected :
  49060. isPointOrBinSelected(clickedPtInfo));
  49061. currentSelectionDef = newPointSelectionDef(clickedPtInfo.pointNumber, clickedPtInfo.searchInfo, subtract);
  49062. var allSelectionDefs = dragOptions.selectionDefs.concat([currentSelectionDef]);
  49063. selectionTester = multiTester(allSelectionDefs);
  49064. for(i = 0; i < searchTraces.length; i++) {
  49065. traceSelection = searchTraces[i]._module.selectPoints(searchTraces[i], selectionTester);
  49066. thisTracesSelection = fillSelectionItem(traceSelection, searchTraces[i]);
  49067. if(selection.length) {
  49068. for(var j = 0; j < thisTracesSelection.length; j++) {
  49069. selection.push(thisTracesSelection[j]);
  49070. }
  49071. }
  49072. else selection = thisTracesSelection;
  49073. }
  49074. eventData = {points: selection};
  49075. updateSelectedState(gd, searchTraces, eventData);
  49076. if(currentSelectionDef && dragOptions) {
  49077. dragOptions.selectionDefs.push(currentSelectionDef);
  49078. }
  49079. if(polygonOutlines) drawSelection(dragOptions.mergedPolygons, polygonOutlines);
  49080. if(sendEvents) {
  49081. gd.emit('plotly_selected', eventData);
  49082. }
  49083. }
  49084. }
  49085. }
  49086. /**
  49087. * Constructs a new point selection definition object.
  49088. */
  49089. function newPointSelectionDef(pointNumber, searchInfo, subtract) {
  49090. return {
  49091. pointNumber: pointNumber,
  49092. searchInfo: searchInfo,
  49093. subtract: subtract
  49094. };
  49095. }
  49096. function isPointSelectionDef(o) {
  49097. return 'pointNumber' in o && 'searchInfo' in o;
  49098. }
  49099. /*
  49100. * Constructs a new point number tester.
  49101. */
  49102. function newPointNumTester(pointSelectionDef) {
  49103. return {
  49104. xmin: 0,
  49105. xmax: 0,
  49106. ymin: 0,
  49107. ymax: 0,
  49108. pts: [],
  49109. contains: function(pt, omitFirstEdge, pointNumber, searchInfo) {
  49110. var idxWantedTrace = pointSelectionDef.searchInfo.cd[0].trace._expandedIndex;
  49111. var idxActualTrace = searchInfo.cd[0].trace._expandedIndex;
  49112. return idxActualTrace === idxWantedTrace &&
  49113. pointNumber === pointSelectionDef.pointNumber;
  49114. },
  49115. isRect: false,
  49116. degenerate: false,
  49117. subtract: pointSelectionDef.subtract
  49118. };
  49119. }
  49120. /**
  49121. * Wraps multiple selection testers.
  49122. *
  49123. * @param {Array} list - An array of selection testers.
  49124. *
  49125. * @return a selection tester object with a contains function
  49126. * that can be called to evaluate a point against all wrapped
  49127. * selection testers that were passed in list.
  49128. */
  49129. function multiTester(list) {
  49130. var testers = [];
  49131. var xmin = isPointSelectionDef(list[0]) ? 0 : list[0][0][0];
  49132. var xmax = xmin;
  49133. var ymin = isPointSelectionDef(list[0]) ? 0 : list[0][0][1];
  49134. var ymax = ymin;
  49135. for(var i = 0; i < list.length; i++) {
  49136. if(isPointSelectionDef(list[i])) {
  49137. testers.push(newPointNumTester(list[i]));
  49138. } else {
  49139. var tester = polygon.tester(list[i]);
  49140. tester.subtract = list[i].subtract;
  49141. testers.push(tester);
  49142. xmin = Math.min(xmin, tester.xmin);
  49143. xmax = Math.max(xmax, tester.xmax);
  49144. ymin = Math.min(ymin, tester.ymin);
  49145. ymax = Math.max(ymax, tester.ymax);
  49146. }
  49147. }
  49148. /**
  49149. * Tests if the given point is within this tester.
  49150. *
  49151. * @param {Array} pt - [0] is the x coordinate, [1] is the y coordinate of the point.
  49152. * @param {*} arg - An optional parameter to pass down to wrapped testers.
  49153. * @param {number} pointNumber - The point number of the point within the underlying data array.
  49154. * @param {number} searchInfo - An object identifying the trace the point is contained in.
  49155. *
  49156. * @return {boolean} true if point is considered to be selected, false otherwise.
  49157. */
  49158. function contains(pt, arg, pointNumber, searchInfo) {
  49159. var contained = false;
  49160. for(var i = 0; i < testers.length; i++) {
  49161. if(testers[i].contains(pt, arg, pointNumber, searchInfo)) {
  49162. // if contained by subtract tester - exclude the point
  49163. contained = testers[i].subtract === false;
  49164. }
  49165. }
  49166. return contained;
  49167. }
  49168. return {
  49169. xmin: xmin,
  49170. xmax: xmax,
  49171. ymin: ymin,
  49172. ymax: ymax,
  49173. pts: [],
  49174. contains: contains,
  49175. isRect: false,
  49176. degenerate: false
  49177. };
  49178. }
  49179. function coerceSelectionsCache(evt, gd, dragOptions) {
  49180. var fullLayout = gd._fullLayout;
  49181. var zoomLayer = fullLayout._zoomlayer;
  49182. var plotinfo = dragOptions.plotinfo;
  49183. var selectingOnSameSubplot = (
  49184. fullLayout._lastSelectedSubplot &&
  49185. fullLayout._lastSelectedSubplot === plotinfo.id
  49186. );
  49187. var hasModifierKey = evt.shiftKey || evt.altKey;
  49188. if(selectingOnSameSubplot && hasModifierKey &&
  49189. (plotinfo.selection && plotinfo.selection.selectionDefs) && !dragOptions.selectionDefs) {
  49190. // take over selection definitions from prev mode, if any
  49191. dragOptions.selectionDefs = plotinfo.selection.selectionDefs;
  49192. dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons;
  49193. } else if(!hasModifierKey || !plotinfo.selection) {
  49194. clearSelectionsCache(dragOptions);
  49195. }
  49196. // clear selection outline when selecting a different subplot
  49197. if(!selectingOnSameSubplot) {
  49198. clearSelect(zoomLayer);
  49199. fullLayout._lastSelectedSubplot = plotinfo.id;
  49200. }
  49201. }
  49202. function clearSelectionsCache(dragOptions) {
  49203. var plotinfo = dragOptions.plotinfo;
  49204. plotinfo.selection = {};
  49205. plotinfo.selection.selectionDefs = dragOptions.selectionDefs = [];
  49206. plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = [];
  49207. }
  49208. function determineSearchTraces(gd, xAxes, yAxes, subplot) {
  49209. var searchTraces = [];
  49210. var xAxisIds = xAxes.map(getAxId);
  49211. var yAxisIds = yAxes.map(getAxId);
  49212. var cd, trace, i;
  49213. for(i = 0; i < gd.calcdata.length; i++) {
  49214. cd = gd.calcdata[i];
  49215. trace = cd[0].trace;
  49216. if(trace.visible !== true || !trace._module || !trace._module.selectPoints) continue;
  49217. if(subplot && (trace.subplot === subplot || trace.geo === subplot)) {
  49218. searchTraces.push(createSearchInfo(trace._module, cd, xAxes[0], yAxes[0]));
  49219. } else if(
  49220. trace.type === 'splom' &&
  49221. // FIXME: make sure we don't have more than single axis for splom
  49222. trace._xaxes[xAxisIds[0]] && trace._yaxes[yAxisIds[0]]
  49223. ) {
  49224. var info = createSearchInfo(trace._module, cd, xAxes[0], yAxes[0]);
  49225. info.scene = gd._fullLayout._splomScenes[trace.uid];
  49226. searchTraces.push(info);
  49227. } else {
  49228. if(xAxisIds.indexOf(trace.xaxis) === -1) continue;
  49229. if(yAxisIds.indexOf(trace.yaxis) === -1) continue;
  49230. searchTraces.push(createSearchInfo(trace._module, cd,
  49231. getFromId(gd, trace.xaxis), getFromId(gd, trace.yaxis)));
  49232. }
  49233. }
  49234. return searchTraces;
  49235. function createSearchInfo(module, calcData, xaxis, yaxis) {
  49236. return {
  49237. _module: module,
  49238. cd: calcData,
  49239. xaxis: xaxis,
  49240. yaxis: yaxis
  49241. };
  49242. }
  49243. }
  49244. function drawSelection(polygons, outlines) {
  49245. var paths = [];
  49246. var i, d;
  49247. for(i = 0; i < polygons.length; i++) {
  49248. var ppts = polygons[i];
  49249. paths.push(ppts.join('L') + 'L' + ppts[0]);
  49250. }
  49251. d = polygons.length > 0 ?
  49252. 'M' + paths.join('M') + 'Z' :
  49253. 'M0,0Z';
  49254. outlines.attr('d', d);
  49255. }
  49256. function isHoverDataSet(hoverData) {
  49257. return hoverData &&
  49258. Array.isArray(hoverData) &&
  49259. hoverData[0].hoverOnBox !== true;
  49260. }
  49261. function extractClickedPtInfo(hoverData, searchTraces) {
  49262. var hoverDatum = hoverData[0];
  49263. var pointNumber = -1;
  49264. var pointNumbers = [];
  49265. var searchInfo, i;
  49266. for(i = 0; i < searchTraces.length; i++) {
  49267. searchInfo = searchTraces[i];
  49268. if(hoverDatum.fullData._expandedIndex === searchInfo.cd[0].trace._expandedIndex) {
  49269. // Special case for box (and violin)
  49270. if(hoverDatum.hoverOnBox === true) {
  49271. break;
  49272. }
  49273. // Hint: in some traces like histogram, one graphical element
  49274. // doesn't correspond to one particular data point, but to
  49275. // bins of data points. Thus, hoverDatum can have a binNumber
  49276. // property instead of pointNumber.
  49277. if(hoverDatum.pointNumber !== undefined) {
  49278. pointNumber = hoverDatum.pointNumber;
  49279. } else if(hoverDatum.binNumber !== undefined) {
  49280. pointNumber = hoverDatum.binNumber;
  49281. pointNumbers = hoverDatum.pointNumbers;
  49282. }
  49283. break;
  49284. }
  49285. }
  49286. return {
  49287. pointNumber: pointNumber,
  49288. pointNumbers: pointNumbers,
  49289. searchInfo: searchInfo
  49290. };
  49291. }
  49292. function isPointOrBinSelected(clickedPtInfo) {
  49293. var trace = clickedPtInfo.searchInfo.cd[0].trace;
  49294. var ptNum = clickedPtInfo.pointNumber;
  49295. var ptNums = clickedPtInfo.pointNumbers;
  49296. var ptNumsSet = ptNums.length > 0;
  49297. // When pointsNumbers is set (e.g. histogram's binning),
  49298. // it is assumed that when the first point of
  49299. // a bin is selected, all others are as well
  49300. var ptNumToTest = ptNumsSet ? ptNums[0] : ptNum;
  49301. // TODO potential performance improvement
  49302. // Primarily we need this function to determine if a click adds
  49303. // or subtracts from a selection.
  49304. // In cases `trace.selectedpoints` is a huge array, indexOf
  49305. // might be slow. One remedy would be to introduce a hash somewhere.
  49306. return trace.selectedpoints ? trace.selectedpoints.indexOf(ptNumToTest) > -1 : false;
  49307. }
  49308. function isOnlyThisBinSelected(searchTraces, clickedPtInfo) {
  49309. var tracesWithSelectedPts = [];
  49310. var searchInfo, trace, isSameTrace, i;
  49311. for(i = 0; i < searchTraces.length; i++) {
  49312. searchInfo = searchTraces[i];
  49313. if(searchInfo.cd[0].trace.selectedpoints && searchInfo.cd[0].trace.selectedpoints.length > 0) {
  49314. tracesWithSelectedPts.push(searchInfo);
  49315. }
  49316. }
  49317. if(tracesWithSelectedPts.length === 1) {
  49318. isSameTrace = tracesWithSelectedPts[0] === clickedPtInfo.searchInfo;
  49319. if(isSameTrace) {
  49320. trace = clickedPtInfo.searchInfo.cd[0].trace;
  49321. if(trace.selectedpoints.length === clickedPtInfo.pointNumbers.length) {
  49322. for(i = 0; i < clickedPtInfo.pointNumbers.length; i++) {
  49323. if(trace.selectedpoints.indexOf(clickedPtInfo.pointNumbers[i]) < 0) {
  49324. return false;
  49325. }
  49326. }
  49327. return true;
  49328. }
  49329. }
  49330. }
  49331. return false;
  49332. }
  49333. function isOnlyOnePointSelected(searchTraces) {
  49334. var len = 0;
  49335. var searchInfo, trace, i;
  49336. for(i = 0; i < searchTraces.length; i++) {
  49337. searchInfo = searchTraces[i];
  49338. trace = searchInfo.cd[0].trace;
  49339. if(trace.selectedpoints) {
  49340. if(trace.selectedpoints.length > 1) return false;
  49341. len += trace.selectedpoints.length;
  49342. if(len > 1) return false;
  49343. }
  49344. }
  49345. return len === 1;
  49346. }
  49347. function updateSelectedState(gd, searchTraces, eventData) {
  49348. var i, searchInfo, cd, trace;
  49349. // before anything else, update preGUI if necessary
  49350. for(i = 0; i < searchTraces.length; i++) {
  49351. var fullInputTrace = searchTraces[i].cd[0].trace._fullInput;
  49352. var tracePreGUI = gd._fullLayout._tracePreGUI[fullInputTrace.uid];
  49353. if(tracePreGUI.selectedpoints === undefined) {
  49354. tracePreGUI.selectedpoints = fullInputTrace._input.selectedpoints || null;
  49355. }
  49356. }
  49357. if(eventData) {
  49358. var pts = eventData.points || [];
  49359. for(i = 0; i < searchTraces.length; i++) {
  49360. trace = searchTraces[i].cd[0].trace;
  49361. trace._input.selectedpoints = trace._fullInput.selectedpoints = [];
  49362. if(trace._fullInput !== trace) trace.selectedpoints = [];
  49363. }
  49364. for(i = 0; i < pts.length; i++) {
  49365. var pt = pts[i];
  49366. var data = pt.data;
  49367. var fullData = pt.fullData;
  49368. if(pt.pointIndices) {
  49369. [].push.apply(data.selectedpoints, pt.pointIndices);
  49370. if(trace._fullInput !== trace) {
  49371. [].push.apply(fullData.selectedpoints, pt.pointIndices);
  49372. }
  49373. } else {
  49374. data.selectedpoints.push(pt.pointIndex);
  49375. if(trace._fullInput !== trace) {
  49376. fullData.selectedpoints.push(pt.pointIndex);
  49377. }
  49378. }
  49379. }
  49380. }
  49381. else {
  49382. for(i = 0; i < searchTraces.length; i++) {
  49383. trace = searchTraces[i].cd[0].trace;
  49384. delete trace.selectedpoints;
  49385. delete trace._input.selectedpoints;
  49386. if(trace._fullInput !== trace) {
  49387. delete trace._fullInput.selectedpoints;
  49388. }
  49389. }
  49390. }
  49391. var hasRegl = false;
  49392. for(i = 0; i < searchTraces.length; i++) {
  49393. searchInfo = searchTraces[i];
  49394. cd = searchInfo.cd;
  49395. trace = cd[0].trace;
  49396. if(Registry.traceIs(trace, 'regl')) {
  49397. hasRegl = true;
  49398. }
  49399. var _module = searchInfo._module;
  49400. var fn = _module.styleOnSelect || _module.style;
  49401. if(fn) fn(gd, cd);
  49402. }
  49403. if(hasRegl) {
  49404. clearGlCanvases(gd);
  49405. redrawReglTraces(gd);
  49406. }
  49407. }
  49408. function mergePolygons(list, poly, subtract) {
  49409. var res;
  49410. if(subtract) {
  49411. res = polybool.difference({
  49412. regions: list,
  49413. inverted: false
  49414. }, {
  49415. regions: [poly],
  49416. inverted: false
  49417. });
  49418. return res.regions;
  49419. }
  49420. res = polybool.union({
  49421. regions: list,
  49422. inverted: false
  49423. }, {
  49424. regions: [poly],
  49425. inverted: false
  49426. });
  49427. return res.regions;
  49428. }
  49429. function fillSelectionItem(selection, searchInfo) {
  49430. if(Array.isArray(selection)) {
  49431. var cd = searchInfo.cd;
  49432. var trace = searchInfo.cd[0].trace;
  49433. for(var i = 0; i < selection.length; i++) {
  49434. selection[i] = makeEventData(selection[i], trace, cd);
  49435. }
  49436. }
  49437. return selection;
  49438. }
  49439. function clearSelect(zoomlayer) {
  49440. // until we get around to persistent selections, remove the outline
  49441. // here. The selection itself will be removed when the plot redraws
  49442. // at the end.
  49443. zoomlayer.selectAll('.select-outline').remove();
  49444. }
  49445. module.exports = {
  49446. prepSelect: prepSelect,
  49447. clearSelect: clearSelect,
  49448. selectOnClick: selectOnClick
  49449. };
  49450. },{"../../components/color":51,"../../components/fx":90,"../../components/fx/helpers":86,"../../lib/clear_gl_canvases":157,"../../lib/polygon":180,"../../lib/throttle":190,"../../plot_api/subroutines":203,"../../registry":257,"./axis_ids":215,"./constants":218,"polybooljs":25}],231:[function(_dereq_,module,exports){
  49451. /**
  49452. * Copyright 2012-2019, Plotly, Inc.
  49453. * All rights reserved.
  49454. *
  49455. * This source code is licensed under the MIT license found in the
  49456. * LICENSE file in the root directory of this source tree.
  49457. */
  49458. 'use strict';
  49459. var d3 = _dereq_('d3');
  49460. var isNumeric = _dereq_('fast-isnumeric');
  49461. var Lib = _dereq_('../../lib');
  49462. var cleanNumber = Lib.cleanNumber;
  49463. var ms2DateTime = Lib.ms2DateTime;
  49464. var dateTime2ms = Lib.dateTime2ms;
  49465. var ensureNumber = Lib.ensureNumber;
  49466. var isArrayOrTypedArray = Lib.isArrayOrTypedArray;
  49467. var numConstants = _dereq_('../../constants/numerical');
  49468. var FP_SAFE = numConstants.FP_SAFE;
  49469. var BADNUM = numConstants.BADNUM;
  49470. var LOG_CLIP = numConstants.LOG_CLIP;
  49471. var constants = _dereq_('./constants');
  49472. var axisIds = _dereq_('./axis_ids');
  49473. function fromLog(v) {
  49474. return Math.pow(10, v);
  49475. }
  49476. function isValidCategory(v) {
  49477. return v !== null && v !== undefined;
  49478. }
  49479. /**
  49480. * Define the conversion functions for an axis data is used in 5 ways:
  49481. *
  49482. * d: data, in whatever form it's provided
  49483. * c: calcdata: turned into numbers, but not linearized
  49484. * l: linearized - same as c except for log axes (and other nonlinear
  49485. * mappings later?) this is used when we need to know if it's
  49486. * *possible* to show some data on this axis, without caring about
  49487. * the current range
  49488. * p: pixel value - mapped to the screen with current size and zoom
  49489. * r: ranges, tick0, and annotation positions match one of the above
  49490. * but are handled differently for different types:
  49491. * - linear and date: data format (d)
  49492. * - category: calcdata format (c), and will stay that way because
  49493. * the data format has no continuous mapping
  49494. * - log: linearized (l) format
  49495. * TODO: in v2.0 we plan to change it to data format. At that point
  49496. * shapes will work the same way as ranges, tick0, and annotations
  49497. * so they can use this conversion too.
  49498. *
  49499. * Creates/updates these conversion functions, and a few more utilities
  49500. * like cleanRange, and makeCalcdata
  49501. *
  49502. * also clears the autotick constraints ._minDtick, ._forceTick0
  49503. */
  49504. module.exports = function setConvert(ax, fullLayout) {
  49505. fullLayout = fullLayout || {};
  49506. var axLetter = (ax._id || 'x').charAt(0);
  49507. function toLog(v, clip) {
  49508. if(v > 0) return Math.log(v) / Math.LN10;
  49509. else if(v <= 0 && clip && ax.range && ax.range.length === 2) {
  49510. // clip NaN (ie past negative infinity) to LOG_CLIP axis
  49511. // length past the negative edge
  49512. var r0 = ax.range[0];
  49513. var r1 = ax.range[1];
  49514. return 0.5 * (r0 + r1 - 2 * LOG_CLIP * Math.abs(r0 - r1));
  49515. }
  49516. else return BADNUM;
  49517. }
  49518. /*
  49519. * wrapped dateTime2ms that:
  49520. * - accepts ms numbers for backward compatibility
  49521. * - inserts a dummy arg so calendar is the 3rd arg (see notes below).
  49522. * - defaults to ax.calendar
  49523. */
  49524. function dt2ms(v, _, calendar) {
  49525. // NOTE: Changed this behavior: previously we took any numeric value
  49526. // to be a ms, even if it was a string that could be a bare year.
  49527. // Now we convert it as a date if at all possible, and only try
  49528. // as (local) ms if that fails.
  49529. var ms = dateTime2ms(v, calendar || ax.calendar);
  49530. if(ms === BADNUM) {
  49531. if(isNumeric(v)) {
  49532. v = +v;
  49533. // keep track of tenths of ms, that `new Date` will drop
  49534. // same logic as in Lib.ms2DateTime
  49535. var msecTenths = Math.floor(Lib.mod(v + 0.05, 1) * 10);
  49536. var msRounded = Math.round(v - msecTenths / 10);
  49537. ms = dateTime2ms(new Date(msRounded)) + msecTenths / 10;
  49538. }
  49539. else return BADNUM;
  49540. }
  49541. return ms;
  49542. }
  49543. // wrapped ms2DateTime to insert default ax.calendar
  49544. function ms2dt(v, r, calendar) {
  49545. return ms2DateTime(v, r, calendar || ax.calendar);
  49546. }
  49547. function getCategoryName(v) {
  49548. return ax._categories[Math.round(v)];
  49549. }
  49550. /*
  49551. * setCategoryIndex: return the index of category v,
  49552. * inserting it in the list if it's not already there
  49553. *
  49554. * this will enter the categories in the order it
  49555. * encounters them, ie all the categories from the
  49556. * first data set, then all the ones from the second
  49557. * that aren't in the first etc.
  49558. *
  49559. * it is assumed that this function is being invoked in the
  49560. * already sorted category order; otherwise there would be
  49561. * a disconnect between the array and the index returned
  49562. */
  49563. function setCategoryIndex(v) {
  49564. if(isValidCategory(v)) {
  49565. if(ax._categoriesMap === undefined) {
  49566. ax._categoriesMap = {};
  49567. }
  49568. if(ax._categoriesMap[v] !== undefined) {
  49569. return ax._categoriesMap[v];
  49570. } else {
  49571. ax._categories.push(v);
  49572. var curLength = ax._categories.length - 1;
  49573. ax._categoriesMap[v] = curLength;
  49574. return curLength;
  49575. }
  49576. }
  49577. return BADNUM;
  49578. }
  49579. function setMultiCategoryIndex(arrayIn, len) {
  49580. var arrayOut = new Array(len);
  49581. for(var i = 0; i < len; i++) {
  49582. var v0 = (arrayIn[0] || [])[i];
  49583. var v1 = (arrayIn[1] || [])[i];
  49584. arrayOut[i] = getCategoryIndex([v0, v1]);
  49585. }
  49586. return arrayOut;
  49587. }
  49588. function getCategoryIndex(v) {
  49589. if(ax._categoriesMap) {
  49590. return ax._categoriesMap[v];
  49591. }
  49592. }
  49593. function getCategoryPosition(v) {
  49594. // d2l/d2c variant that that won't add categories but will also
  49595. // allow numbers to be mapped to the linearized axis positions
  49596. var index = getCategoryIndex(v);
  49597. if(index !== undefined) return index;
  49598. if(isNumeric(v)) return +v;
  49599. }
  49600. function l2p(v) {
  49601. if(!isNumeric(v)) return BADNUM;
  49602. // include 2 fractional digits on pixel, for PDF zooming etc
  49603. return d3.round(ax._b + ax._m * v, 2);
  49604. }
  49605. function p2l(px) { return (px - ax._b) / ax._m; }
  49606. // conversions among c/l/p are fairly simple - do them together for all axis types
  49607. ax.c2l = (ax.type === 'log') ? toLog : ensureNumber;
  49608. ax.l2c = (ax.type === 'log') ? fromLog : ensureNumber;
  49609. ax.l2p = l2p;
  49610. ax.p2l = p2l;
  49611. ax.c2p = (ax.type === 'log') ? function(v, clip) { return l2p(toLog(v, clip)); } : l2p;
  49612. ax.p2c = (ax.type === 'log') ? function(px) { return fromLog(p2l(px)); } : p2l;
  49613. /*
  49614. * now type-specific conversions for **ALL** other combinations
  49615. * they're all written out, instead of being combinations of each other, for
  49616. * both clarity and speed.
  49617. */
  49618. if(['linear', '-'].indexOf(ax.type) !== -1) {
  49619. // all are data vals, but d and r need cleaning
  49620. ax.d2r = ax.r2d = ax.d2c = ax.r2c = ax.d2l = ax.r2l = cleanNumber;
  49621. ax.c2d = ax.c2r = ax.l2d = ax.l2r = ensureNumber;
  49622. ax.d2p = ax.r2p = function(v) { return ax.l2p(cleanNumber(v)); };
  49623. ax.p2d = ax.p2r = p2l;
  49624. ax.cleanPos = ensureNumber;
  49625. }
  49626. else if(ax.type === 'log') {
  49627. // d and c are data vals, r and l are logged (but d and r need cleaning)
  49628. ax.d2r = ax.d2l = function(v, clip) { return toLog(cleanNumber(v), clip); };
  49629. ax.r2d = ax.r2c = function(v) { return fromLog(cleanNumber(v)); };
  49630. ax.d2c = ax.r2l = cleanNumber;
  49631. ax.c2d = ax.l2r = ensureNumber;
  49632. ax.c2r = toLog;
  49633. ax.l2d = fromLog;
  49634. ax.d2p = function(v, clip) { return ax.l2p(ax.d2r(v, clip)); };
  49635. ax.p2d = function(px) { return fromLog(p2l(px)); };
  49636. ax.r2p = function(v) { return ax.l2p(cleanNumber(v)); };
  49637. ax.p2r = p2l;
  49638. ax.cleanPos = ensureNumber;
  49639. }
  49640. else if(ax.type === 'date') {
  49641. // r and d are date strings, l and c are ms
  49642. /*
  49643. * Any of these functions with r and d on either side, calendar is the
  49644. * **3rd** argument. log has reserved the second argument.
  49645. *
  49646. * Unless you need the special behavior of the second arg (ms2DateTime
  49647. * uses this to limit precision, toLog uses true to clip negatives
  49648. * to offscreen low rather than undefined), it's safe to pass 0.
  49649. */
  49650. ax.d2r = ax.r2d = Lib.identity;
  49651. ax.d2c = ax.r2c = ax.d2l = ax.r2l = dt2ms;
  49652. ax.c2d = ax.c2r = ax.l2d = ax.l2r = ms2dt;
  49653. ax.d2p = ax.r2p = function(v, _, calendar) { return ax.l2p(dt2ms(v, 0, calendar)); };
  49654. ax.p2d = ax.p2r = function(px, r, calendar) { return ms2dt(p2l(px), r, calendar); };
  49655. ax.cleanPos = function(v) { return Lib.cleanDate(v, BADNUM, ax.calendar); };
  49656. }
  49657. else if(ax.type === 'category') {
  49658. // d is categories (string)
  49659. // c and l are indices (numbers)
  49660. // r is categories or numbers
  49661. ax.d2c = ax.d2l = setCategoryIndex;
  49662. ax.r2d = ax.c2d = ax.l2d = getCategoryName;
  49663. ax.d2r = ax.d2l_noadd = getCategoryPosition;
  49664. ax.r2c = function(v) {
  49665. var index = getCategoryPosition(v);
  49666. return index !== undefined ? index : ax.fraction2r(0.5);
  49667. };
  49668. ax.l2r = ax.c2r = ensureNumber;
  49669. ax.r2l = getCategoryPosition;
  49670. ax.d2p = function(v) { return ax.l2p(ax.r2c(v)); };
  49671. ax.p2d = function(px) { return getCategoryName(p2l(px)); };
  49672. ax.r2p = ax.d2p;
  49673. ax.p2r = p2l;
  49674. ax.cleanPos = function(v) {
  49675. if(typeof v === 'string' && v !== '') return v;
  49676. return ensureNumber(v);
  49677. };
  49678. }
  49679. else if(ax.type === 'multicategory') {
  49680. // N.B. multicategory axes don't define d2c and d2l,
  49681. // as 'data-to-calcdata' conversion needs to take into
  49682. // account all data array items as in ax.makeCalcdata.
  49683. ax.r2d = ax.c2d = ax.l2d = getCategoryName;
  49684. ax.d2r = ax.d2l_noadd = getCategoryPosition;
  49685. ax.r2c = function(v) {
  49686. var index = getCategoryPosition(v);
  49687. return index !== undefined ? index : ax.fraction2r(0.5);
  49688. };
  49689. ax.r2c_just_indices = getCategoryIndex;
  49690. ax.l2r = ax.c2r = ensureNumber;
  49691. ax.r2l = getCategoryPosition;
  49692. ax.d2p = function(v) { return ax.l2p(ax.r2c(v)); };
  49693. ax.p2d = function(px) { return getCategoryName(p2l(px)); };
  49694. ax.r2p = ax.d2p;
  49695. ax.p2r = p2l;
  49696. ax.cleanPos = function(v) {
  49697. if(Array.isArray(v) || (typeof v === 'string' && v !== '')) return v;
  49698. return ensureNumber(v);
  49699. };
  49700. ax.setupMultiCategory = function(fullData) {
  49701. var traceIndices = ax._traceIndices;
  49702. var i, j;
  49703. // [ [cnt, {$cat: index}], for 1,2 ]
  49704. var seen = ax._multicatSeen = [[0, {}], [0, {}]];
  49705. // [ [arrayIn[0][i], arrayIn[1][i]], for i .. N ]
  49706. var list = ax._multicatList = [];
  49707. for(i = 0; i < traceIndices.length; i++) {
  49708. var trace = fullData[traceIndices[i]];
  49709. if(axLetter in trace) {
  49710. var arrayIn = trace[axLetter];
  49711. var len = trace._length || Lib.minRowLength(arrayIn);
  49712. if(isArrayOrTypedArray(arrayIn[0]) && isArrayOrTypedArray(arrayIn[1])) {
  49713. for(j = 0; j < len; j++) {
  49714. var v0 = arrayIn[0][j];
  49715. var v1 = arrayIn[1][j];
  49716. if(isValidCategory(v0) && isValidCategory(v1)) {
  49717. list.push([v0, v1]);
  49718. if(!(v0 in seen[0][1])) {
  49719. seen[0][1][v0] = seen[0][0]++;
  49720. }
  49721. if(!(v1 in seen[1][1])) {
  49722. seen[1][1][v1] = seen[1][0]++;
  49723. }
  49724. }
  49725. }
  49726. }
  49727. }
  49728. }
  49729. list.sort(function(a, b) {
  49730. var ind0 = seen[0][1];
  49731. var d = ind0[a[0]] - ind0[b[0]];
  49732. if(d) return d;
  49733. var ind1 = seen[1][1];
  49734. return ind1[a[1]] - ind1[b[1]];
  49735. });
  49736. for(i = 0; i < list.length; i++) {
  49737. setCategoryIndex(list[i]);
  49738. }
  49739. };
  49740. }
  49741. // find the range value at the specified (linear) fraction of the axis
  49742. ax.fraction2r = function(v) {
  49743. var rl0 = ax.r2l(ax.range[0]);
  49744. var rl1 = ax.r2l(ax.range[1]);
  49745. return ax.l2r(rl0 + v * (rl1 - rl0));
  49746. };
  49747. // find the fraction of the range at the specified range value
  49748. ax.r2fraction = function(v) {
  49749. var rl0 = ax.r2l(ax.range[0]);
  49750. var rl1 = ax.r2l(ax.range[1]);
  49751. return (ax.r2l(v) - rl0) / (rl1 - rl0);
  49752. };
  49753. /*
  49754. * cleanRange: make sure range is a couplet of valid & distinct values
  49755. * keep numbers away from the limits of floating point numbers,
  49756. * and dates away from the ends of our date system (+/- 9999 years)
  49757. *
  49758. * optional param rangeAttr: operate on a different attribute, like
  49759. * ax._r, rather than ax.range
  49760. */
  49761. ax.cleanRange = function(rangeAttr, opts) {
  49762. if(!opts) opts = {};
  49763. if(!rangeAttr) rangeAttr = 'range';
  49764. var range = Lib.nestedProperty(ax, rangeAttr).get();
  49765. var i, dflt;
  49766. if(ax.type === 'date') dflt = Lib.dfltRange(ax.calendar);
  49767. else if(axLetter === 'y') dflt = constants.DFLTRANGEY;
  49768. else dflt = opts.dfltRange || constants.DFLTRANGEX;
  49769. // make sure we don't later mutate the defaults
  49770. dflt = dflt.slice();
  49771. if(!range || range.length !== 2) {
  49772. Lib.nestedProperty(ax, rangeAttr).set(dflt);
  49773. return;
  49774. }
  49775. if(ax.type === 'date') {
  49776. // check if milliseconds or js date objects are provided for range
  49777. // and convert to date strings
  49778. range[0] = Lib.cleanDate(range[0], BADNUM, ax.calendar);
  49779. range[1] = Lib.cleanDate(range[1], BADNUM, ax.calendar);
  49780. }
  49781. for(i = 0; i < 2; i++) {
  49782. if(ax.type === 'date') {
  49783. if(!Lib.isDateTime(range[i], ax.calendar)) {
  49784. ax[rangeAttr] = dflt;
  49785. break;
  49786. }
  49787. if(ax.r2l(range[0]) === ax.r2l(range[1])) {
  49788. // split by +/- 1 second
  49789. var linCenter = Lib.constrain(ax.r2l(range[0]),
  49790. Lib.MIN_MS + 1000, Lib.MAX_MS - 1000);
  49791. range[0] = ax.l2r(linCenter - 1000);
  49792. range[1] = ax.l2r(linCenter + 1000);
  49793. break;
  49794. }
  49795. }
  49796. else {
  49797. if(!isNumeric(range[i])) {
  49798. if(isNumeric(range[1 - i])) {
  49799. range[i] = range[1 - i] * (i ? 10 : 0.1);
  49800. }
  49801. else {
  49802. ax[rangeAttr] = dflt;
  49803. break;
  49804. }
  49805. }
  49806. if(range[i] < -FP_SAFE) range[i] = -FP_SAFE;
  49807. else if(range[i] > FP_SAFE) range[i] = FP_SAFE;
  49808. if(range[0] === range[1]) {
  49809. // somewhat arbitrary: split by 1 or 1ppm, whichever is bigger
  49810. var inc = Math.max(1, Math.abs(range[0] * 1e-6));
  49811. range[0] -= inc;
  49812. range[1] += inc;
  49813. }
  49814. }
  49815. }
  49816. };
  49817. // set scaling to pixels
  49818. ax.setScale = function(usePrivateRange) {
  49819. var gs = fullLayout._size;
  49820. // make sure we have a domain (pull it in from the axis
  49821. // this one is overlaying if necessary)
  49822. if(ax.overlaying) {
  49823. var ax2 = axisIds.getFromId({ _fullLayout: fullLayout }, ax.overlaying);
  49824. ax.domain = ax2.domain;
  49825. }
  49826. // While transitions are occuring, occurring, we get a double-transform
  49827. // issue if we transform the drawn layer *and* use the new axis range to
  49828. // draw the data. This allows us to construct setConvert using the pre-
  49829. // interaction values of the range:
  49830. var rangeAttr = (usePrivateRange && ax._r) ? '_r' : 'range';
  49831. var calendar = ax.calendar;
  49832. ax.cleanRange(rangeAttr);
  49833. var rl0 = ax.r2l(ax[rangeAttr][0], calendar);
  49834. var rl1 = ax.r2l(ax[rangeAttr][1], calendar);
  49835. if(axLetter === 'y') {
  49836. ax._offset = gs.t + (1 - ax.domain[1]) * gs.h;
  49837. ax._length = gs.h * (ax.domain[1] - ax.domain[0]);
  49838. ax._m = ax._length / (rl0 - rl1);
  49839. ax._b = -ax._m * rl1;
  49840. }
  49841. else {
  49842. ax._offset = gs.l + ax.domain[0] * gs.w;
  49843. ax._length = gs.w * (ax.domain[1] - ax.domain[0]);
  49844. ax._m = ax._length / (rl1 - rl0);
  49845. ax._b = -ax._m * rl0;
  49846. }
  49847. if(!isFinite(ax._m) || !isFinite(ax._b)) {
  49848. fullLayout._replotting = false;
  49849. throw new Error('Something went wrong with axis scaling');
  49850. }
  49851. };
  49852. // makeCalcdata: takes an x or y array and converts it
  49853. // to a position on the axis object "ax"
  49854. // inputs:
  49855. // trace - a data object from gd.data
  49856. // axLetter - a string, either 'x' or 'y', for which item
  49857. // to convert (TODO: is this now always the same as
  49858. // the first letter of ax._id?)
  49859. // in case the expected data isn't there, make a list of
  49860. // integers based on the opposite data
  49861. ax.makeCalcdata = function(trace, axLetter) {
  49862. var arrayIn, arrayOut, i, len;
  49863. var axType = ax.type;
  49864. var cal = axType === 'date' && trace[axLetter + 'calendar'];
  49865. if(axLetter in trace) {
  49866. arrayIn = trace[axLetter];
  49867. len = trace._length || Lib.minRowLength(arrayIn);
  49868. if(Lib.isTypedArray(arrayIn) && (axType === 'linear' || axType === 'log')) {
  49869. if(len === arrayIn.length) {
  49870. return arrayIn;
  49871. } else if(arrayIn.subarray) {
  49872. return arrayIn.subarray(0, len);
  49873. }
  49874. }
  49875. if(axType === 'multicategory') {
  49876. return setMultiCategoryIndex(arrayIn, len);
  49877. }
  49878. arrayOut = new Array(len);
  49879. for(i = 0; i < len; i++) {
  49880. arrayOut[i] = ax.d2c(arrayIn[i], 0, cal);
  49881. }
  49882. }
  49883. else {
  49884. var v0 = ((axLetter + '0') in trace) ? ax.d2c(trace[axLetter + '0'], 0, cal) : 0;
  49885. var dv = (trace['d' + axLetter]) ? Number(trace['d' + axLetter]) : 1;
  49886. // the opposing data, for size if we have x and dx etc
  49887. arrayIn = trace[{x: 'y', y: 'x'}[axLetter]];
  49888. len = trace._length || arrayIn.length;
  49889. arrayOut = new Array(len);
  49890. for(i = 0; i < len; i++) {
  49891. arrayOut[i] = v0 + i * dv;
  49892. }
  49893. }
  49894. return arrayOut;
  49895. };
  49896. ax.isValidRange = function(range) {
  49897. return (
  49898. Array.isArray(range) &&
  49899. range.length === 2 &&
  49900. isNumeric(ax.r2l(range[0])) &&
  49901. isNumeric(ax.r2l(range[1]))
  49902. );
  49903. };
  49904. ax.isPtWithinRange = function(d, calendar) {
  49905. var coord = ax.c2l(d[axLetter], null, calendar);
  49906. var r0 = ax.r2l(ax.range[0]);
  49907. var r1 = ax.r2l(ax.range[1]);
  49908. if(r0 < r1) {
  49909. return r0 <= coord && coord <= r1;
  49910. } else {
  49911. // Reversed axis case.
  49912. return r1 <= coord && coord <= r0;
  49913. }
  49914. };
  49915. ax.clearCalc = function() {
  49916. // initialize the category list, if there is one, so we start over
  49917. // to be filled in later by ax.d2c
  49918. ax._categories = (ax._initialCategories || []).slice();
  49919. // Build the lookup map for initialized categories
  49920. ax._categoriesMap = {};
  49921. for(var j = 0; j < ax._categories.length; j++) {
  49922. ax._categoriesMap[ax._categories[j]] = j;
  49923. }
  49924. };
  49925. // Propagate localization into the axis so that
  49926. // methods in Axes can use it w/o having to pass fullLayout
  49927. // Default (non-d3) number formatting uses separators directly
  49928. // dates and d3-formatted numbers use the d3 locale
  49929. // Fall back on default format for dummy axes that don't care about formatting
  49930. var locale = fullLayout._d3locale;
  49931. if(ax.type === 'date') {
  49932. ax._dateFormat = locale ? locale.timeFormat.utc : d3.time.format.utc;
  49933. ax._extraFormat = fullLayout._extraFormat;
  49934. }
  49935. // occasionally we need _numFormat to pass through
  49936. // even though it won't be needed by this axis
  49937. ax._separators = fullLayout.separators;
  49938. ax._numFormat = locale ? locale.numberFormat : d3.format;
  49939. // and for bar charts and box plots: reset forced minimum tick spacing
  49940. delete ax._minDtick;
  49941. delete ax._forceTick0;
  49942. };
  49943. },{"../../constants/numerical":149,"../../lib":168,"./axis_ids":215,"./constants":218,"d3":16,"fast-isnumeric":18}],232:[function(_dereq_,module,exports){
  49944. /**
  49945. * Copyright 2012-2019, Plotly, Inc.
  49946. * All rights reserved.
  49947. *
  49948. * This source code is licensed under the MIT license found in the
  49949. * LICENSE file in the root directory of this source tree.
  49950. */
  49951. 'use strict';
  49952. var Lib = _dereq_('../../lib');
  49953. var layoutAttributes = _dereq_('./layout_attributes');
  49954. var handleArrayContainerDefaults = _dereq_('../array_container_defaults');
  49955. module.exports = function handleTickLabelDefaults(containerIn, containerOut, coerce, axType, options) {
  49956. var showAttrDflt = getShowAttrDflt(containerIn);
  49957. var tickPrefix = coerce('tickprefix');
  49958. if(tickPrefix) coerce('showtickprefix', showAttrDflt);
  49959. var tickSuffix = coerce('ticksuffix', options.tickSuffixDflt);
  49960. if(tickSuffix) coerce('showticksuffix', showAttrDflt);
  49961. var showTickLabels = coerce('showticklabels');
  49962. if(showTickLabels) {
  49963. var font = options.font || {};
  49964. var contColor = containerOut.color;
  49965. // as with titlefont.color, inherit axis.color only if one was
  49966. // explicitly provided
  49967. var dfltFontColor = (contColor && contColor !== layoutAttributes.color.dflt) ?
  49968. contColor : font.color;
  49969. Lib.coerceFont(coerce, 'tickfont', {
  49970. family: font.family,
  49971. size: font.size,
  49972. color: dfltFontColor
  49973. });
  49974. coerce('tickangle');
  49975. if(axType !== 'category') {
  49976. var tickFormat = coerce('tickformat');
  49977. var tickformatStops = containerIn.tickformatstops;
  49978. if(Array.isArray(tickformatStops) && tickformatStops.length) {
  49979. handleArrayContainerDefaults(containerIn, containerOut, {
  49980. name: 'tickformatstops',
  49981. inclusionAttr: 'enabled',
  49982. handleItemDefaults: tickformatstopDefaults
  49983. });
  49984. }
  49985. if(!tickFormat && axType !== 'date') {
  49986. coerce('showexponent', showAttrDflt);
  49987. coerce('exponentformat');
  49988. coerce('separatethousands');
  49989. }
  49990. }
  49991. }
  49992. };
  49993. /*
  49994. * Attributes 'showexponent', 'showtickprefix' and 'showticksuffix'
  49995. * share values.
  49996. *
  49997. * If only 1 attribute is set,
  49998. * the remaining attributes inherit that value.
  49999. *
  50000. * If 2 attributes are set to the same value,
  50001. * the remaining attribute inherits that value.
  50002. *
  50003. * If 2 attributes are set to different values,
  50004. * the remaining is set to its dflt value.
  50005. *
  50006. */
  50007. function getShowAttrDflt(containerIn) {
  50008. var showAttrsAll = ['showexponent', 'showtickprefix', 'showticksuffix'];
  50009. var showAttrs = showAttrsAll.filter(function(a) {
  50010. return containerIn[a] !== undefined;
  50011. });
  50012. var sameVal = function(a) {
  50013. return containerIn[a] === containerIn[showAttrs[0]];
  50014. };
  50015. if(showAttrs.every(sameVal) || showAttrs.length === 1) {
  50016. return containerIn[showAttrs[0]];
  50017. }
  50018. }
  50019. function tickformatstopDefaults(valueIn, valueOut) {
  50020. function coerce(attr, dflt) {
  50021. return Lib.coerce(valueIn, valueOut, layoutAttributes.tickformatstops, attr, dflt);
  50022. }
  50023. var enabled = coerce('enabled');
  50024. if(enabled) {
  50025. coerce('dtickrange');
  50026. coerce('value');
  50027. }
  50028. }
  50029. },{"../../lib":168,"../array_container_defaults":208,"./layout_attributes":225}],233:[function(_dereq_,module,exports){
  50030. /**
  50031. * Copyright 2012-2019, Plotly, Inc.
  50032. * All rights reserved.
  50033. *
  50034. * This source code is licensed under the MIT license found in the
  50035. * LICENSE file in the root directory of this source tree.
  50036. */
  50037. 'use strict';
  50038. var Lib = _dereq_('../../lib');
  50039. var layoutAttributes = _dereq_('./layout_attributes');
  50040. /**
  50041. * options: inherits outerTicks from axes.handleAxisDefaults
  50042. */
  50043. module.exports = function handleTickDefaults(containerIn, containerOut, coerce, options) {
  50044. var tickLen = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'ticklen');
  50045. var tickWidth = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'tickwidth');
  50046. var tickColor = Lib.coerce2(containerIn, containerOut, layoutAttributes, 'tickcolor', containerOut.color);
  50047. var showTicks = coerce('ticks', (options.outerTicks || tickLen || tickWidth || tickColor) ? 'outside' : '');
  50048. if(!showTicks) {
  50049. delete containerOut.ticklen;
  50050. delete containerOut.tickwidth;
  50051. delete containerOut.tickcolor;
  50052. }
  50053. };
  50054. },{"../../lib":168,"./layout_attributes":225}],234:[function(_dereq_,module,exports){
  50055. /**
  50056. * Copyright 2012-2019, Plotly, Inc.
  50057. * All rights reserved.
  50058. *
  50059. * This source code is licensed under the MIT license found in the
  50060. * LICENSE file in the root directory of this source tree.
  50061. */
  50062. 'use strict';
  50063. var cleanTicks = _dereq_('./clean_ticks');
  50064. module.exports = function handleTickValueDefaults(containerIn, containerOut, coerce, axType) {
  50065. var tickmode;
  50066. if(containerIn.tickmode === 'array' &&
  50067. (axType === 'log' || axType === 'date')) {
  50068. tickmode = containerOut.tickmode = 'auto';
  50069. } else {
  50070. var tickmodeDefault = Array.isArray(containerIn.tickvals) ? 'array' :
  50071. containerIn.dtick ? 'linear' :
  50072. 'auto';
  50073. tickmode = coerce('tickmode', tickmodeDefault);
  50074. }
  50075. if(tickmode === 'auto') coerce('nticks');
  50076. else if(tickmode === 'linear') {
  50077. // dtick is usually a positive number, but there are some
  50078. // special strings available for log or date axes
  50079. // tick0 also has special logic
  50080. var dtick = containerOut.dtick = cleanTicks.dtick(
  50081. containerIn.dtick, axType);
  50082. containerOut.tick0 = cleanTicks.tick0(
  50083. containerIn.tick0, axType, containerOut.calendar, dtick);
  50084. } else if(axType !== 'multicategory') {
  50085. var tickvals = coerce('tickvals');
  50086. if(tickvals === undefined) containerOut.tickmode = 'auto';
  50087. else coerce('ticktext');
  50088. }
  50089. };
  50090. },{"./clean_ticks":217}],235:[function(_dereq_,module,exports){
  50091. /**
  50092. * Copyright 2012-2019, Plotly, Inc.
  50093. * All rights reserved.
  50094. *
  50095. * This source code is licensed under the MIT license found in the
  50096. * LICENSE file in the root directory of this source tree.
  50097. */
  50098. 'use strict';
  50099. var d3 = _dereq_('d3');
  50100. var Registry = _dereq_('../../registry');
  50101. var Drawing = _dereq_('../../components/drawing');
  50102. var Axes = _dereq_('./axes');
  50103. /**
  50104. * transitionAxes
  50105. *
  50106. * transition axes from one set of ranges to another, using a svg
  50107. * transformations, similar to during panning.
  50108. *
  50109. * @param {DOM element | object} gd
  50110. * @param {array} edits : array of 'edits', each item with
  50111. * - plotinfo {object} subplot object
  50112. * - xr0 {array} initial x-range
  50113. * - xr1 {array} end x-range
  50114. * - yr0 {array} initial y-range
  50115. * - yr1 {array} end y-range
  50116. * @param {object} transitionOpts
  50117. * @param {function} makeOnCompleteCallback
  50118. */
  50119. module.exports = function transitionAxes(gd, edits, transitionOpts, makeOnCompleteCallback) {
  50120. var fullLayout = gd._fullLayout;
  50121. // special case for redraw:false Plotly.animate that relies on this
  50122. // to update axis-referenced layout components
  50123. if(edits.length === 0) {
  50124. Axes.redrawComponents(gd);
  50125. return;
  50126. }
  50127. function unsetSubplotTransform(subplot) {
  50128. var xa = subplot.xaxis;
  50129. var ya = subplot.yaxis;
  50130. fullLayout._defs.select('#' + subplot.clipId + '> rect')
  50131. .call(Drawing.setTranslate, 0, 0)
  50132. .call(Drawing.setScale, 1, 1);
  50133. subplot.plot
  50134. .call(Drawing.setTranslate, xa._offset, ya._offset)
  50135. .call(Drawing.setScale, 1, 1);
  50136. var traceGroups = subplot.plot.selectAll('.scatterlayer .trace');
  50137. // This is specifically directed at scatter traces, applying an inverse
  50138. // scale to individual points to counteract the scale of the trace
  50139. // as a whole:
  50140. traceGroups.selectAll('.point')
  50141. .call(Drawing.setPointGroupScale, 1, 1);
  50142. traceGroups.selectAll('.textpoint')
  50143. .call(Drawing.setTextPointsScale, 1, 1);
  50144. traceGroups
  50145. .call(Drawing.hideOutsideRangePoints, subplot);
  50146. }
  50147. function updateSubplot(edit, progress) {
  50148. var plotinfo = edit.plotinfo;
  50149. var xa = plotinfo.xaxis;
  50150. var ya = plotinfo.yaxis;
  50151. var xr0 = edit.xr0;
  50152. var xr1 = edit.xr1;
  50153. var xlen = xa._length;
  50154. var yr0 = edit.yr0;
  50155. var yr1 = edit.yr1;
  50156. var ylen = ya._length;
  50157. var editX = !!xr1;
  50158. var editY = !!yr1;
  50159. var viewBox = [];
  50160. if(editX) {
  50161. var dx0 = xr0[1] - xr0[0];
  50162. var dx1 = xr1[1] - xr1[0];
  50163. viewBox[0] = (xr0[0] * (1 - progress) + progress * xr1[0] - xr0[0]) / (xr0[1] - xr0[0]) * xlen;
  50164. viewBox[2] = xlen * ((1 - progress) + progress * dx1 / dx0);
  50165. xa.range[0] = xr0[0] * (1 - progress) + progress * xr1[0];
  50166. xa.range[1] = xr0[1] * (1 - progress) + progress * xr1[1];
  50167. } else {
  50168. viewBox[0] = 0;
  50169. viewBox[2] = xlen;
  50170. }
  50171. if(editY) {
  50172. var dy0 = yr0[1] - yr0[0];
  50173. var dy1 = yr1[1] - yr1[0];
  50174. viewBox[1] = (yr0[1] * (1 - progress) + progress * yr1[1] - yr0[1]) / (yr0[0] - yr0[1]) * ylen;
  50175. viewBox[3] = ylen * ((1 - progress) + progress * dy1 / dy0);
  50176. ya.range[0] = yr0[0] * (1 - progress) + progress * yr1[0];
  50177. ya.range[1] = yr0[1] * (1 - progress) + progress * yr1[1];
  50178. } else {
  50179. viewBox[1] = 0;
  50180. viewBox[3] = ylen;
  50181. }
  50182. Axes.drawOne(gd, xa, {skipTitle: true});
  50183. Axes.drawOne(gd, ya, {skipTitle: true});
  50184. Axes.redrawComponents(gd, [xa._id, ya._id]);
  50185. var xScaleFactor = editX ? xlen / viewBox[2] : 1;
  50186. var yScaleFactor = editY ? ylen / viewBox[3] : 1;
  50187. var clipDx = editX ? viewBox[0] : 0;
  50188. var clipDy = editY ? viewBox[1] : 0;
  50189. var fracDx = editX ? (viewBox[0] / viewBox[2] * xlen) : 0;
  50190. var fracDy = editY ? (viewBox[1] / viewBox[3] * ylen) : 0;
  50191. var plotDx = xa._offset - fracDx;
  50192. var plotDy = ya._offset - fracDy;
  50193. plotinfo.clipRect
  50194. .call(Drawing.setTranslate, clipDx, clipDy)
  50195. .call(Drawing.setScale, 1 / xScaleFactor, 1 / yScaleFactor);
  50196. plotinfo.plot
  50197. .call(Drawing.setTranslate, plotDx, plotDy)
  50198. .call(Drawing.setScale, xScaleFactor, yScaleFactor);
  50199. // apply an inverse scale to individual points to counteract
  50200. // the scale of the trace group.
  50201. Drawing.setPointGroupScale(plotinfo.zoomScalePts, 1 / xScaleFactor, 1 / yScaleFactor);
  50202. Drawing.setTextPointsScale(plotinfo.zoomScaleTxt, 1 / xScaleFactor, 1 / yScaleFactor);
  50203. }
  50204. var onComplete;
  50205. if(makeOnCompleteCallback) {
  50206. // This module makes the choice whether or not it notifies Plotly.transition
  50207. // about completion:
  50208. onComplete = makeOnCompleteCallback();
  50209. }
  50210. function transitionComplete() {
  50211. var aobj = {};
  50212. for(var i = 0; i < edits.length; i++) {
  50213. var edit = edits[i];
  50214. if(edit.xr1) aobj[edit.plotinfo.xaxis._name + '.range'] = edit.xr1.slice();
  50215. if(edit.yr1) aobj[edit.plotinfo.yaxis._name + '.range'] = edit.yr1.slice();
  50216. }
  50217. // Signal that this transition has completed:
  50218. onComplete && onComplete();
  50219. return Registry.call('relayout', gd, aobj).then(function() {
  50220. for(var i = 0; i < edits.length; i++) {
  50221. unsetSubplotTransform(edits[i].plotinfo);
  50222. }
  50223. });
  50224. }
  50225. function transitionInterrupt() {
  50226. var aobj = {};
  50227. for(var i = 0; i < edits.length; i++) {
  50228. var edit = edits[i];
  50229. if(edit.xr0) aobj[edit.plotinfo.xaxis._name + '.range'] = edit.xr0.slice();
  50230. if(edit.yr0) aobj[edit.plotinfo.yaxis._name + '.range'] = edit.yr0.slice();
  50231. }
  50232. return Registry.call('relayout', gd, aobj).then(function() {
  50233. for(var i = 0; i < edits.length; i++) {
  50234. unsetSubplotTransform(edits[i].plotinfo);
  50235. }
  50236. });
  50237. }
  50238. var t1, t2, raf;
  50239. var easeFn = d3.ease(transitionOpts.easing);
  50240. gd._transitionData._interruptCallbacks.push(function() {
  50241. window.cancelAnimationFrame(raf);
  50242. raf = null;
  50243. return transitionInterrupt();
  50244. });
  50245. function doFrame() {
  50246. t2 = Date.now();
  50247. var tInterp = Math.min(1, (t2 - t1) / transitionOpts.duration);
  50248. var progress = easeFn(tInterp);
  50249. for(var i = 0; i < edits.length; i++) {
  50250. updateSubplot(edits[i], progress);
  50251. }
  50252. if(t2 - t1 > transitionOpts.duration) {
  50253. transitionComplete();
  50254. raf = window.cancelAnimationFrame(doFrame);
  50255. } else {
  50256. raf = window.requestAnimationFrame(doFrame);
  50257. }
  50258. }
  50259. t1 = Date.now();
  50260. raf = window.requestAnimationFrame(doFrame);
  50261. return Promise.resolve();
  50262. };
  50263. },{"../../components/drawing":72,"../../registry":257,"./axes":212,"d3":16}],236:[function(_dereq_,module,exports){
  50264. /**
  50265. * Copyright 2012-2019, Plotly, Inc.
  50266. * All rights reserved.
  50267. *
  50268. * This source code is licensed under the MIT license found in the
  50269. * LICENSE file in the root directory of this source tree.
  50270. */
  50271. 'use strict';
  50272. var traceIs = _dereq_('../../registry').traceIs;
  50273. var autoType = _dereq_('./axis_autotype');
  50274. /*
  50275. * data: the plot data to use in choosing auto type
  50276. * name: axis object name (ie 'xaxis') if one should be stored
  50277. */
  50278. module.exports = function handleTypeDefaults(containerIn, containerOut, coerce, options) {
  50279. var axType = coerce('type', (options.splomStash || {}).type);
  50280. if(axType === '-') {
  50281. setAutoType(containerOut, options.data);
  50282. if(containerOut.type === '-') {
  50283. containerOut.type = 'linear';
  50284. } else {
  50285. // copy autoType back to input axis
  50286. // note that if this object didn't exist
  50287. // in the input layout, we have to put it in
  50288. // this happens in the main supplyDefaults function
  50289. containerIn.type = containerOut.type;
  50290. }
  50291. }
  50292. };
  50293. function setAutoType(ax, data) {
  50294. // new logic: let people specify any type they want,
  50295. // only autotype if type is '-'
  50296. if(ax.type !== '-') return;
  50297. var id = ax._id;
  50298. var axLetter = id.charAt(0);
  50299. // support 3d
  50300. if(id.indexOf('scene') !== -1) id = axLetter;
  50301. var d0 = getFirstNonEmptyTrace(data, id, axLetter);
  50302. if(!d0) return;
  50303. // first check for histograms, as the count direction
  50304. // should always default to a linear axis
  50305. if(d0.type === 'histogram' &&
  50306. axLetter === {v: 'y', h: 'x'}[d0.orientation || 'v']) {
  50307. ax.type = 'linear';
  50308. return;
  50309. }
  50310. var calAttr = axLetter + 'calendar';
  50311. var calendar = d0[calAttr];
  50312. var opts = {noMultiCategory: !traceIs(d0, 'cartesian') || traceIs(d0, 'noMultiCategory')};
  50313. var i;
  50314. // check all boxes on this x axis to see
  50315. // if they're dates, numbers, or categories
  50316. if(isBoxWithoutPositionCoords(d0, axLetter)) {
  50317. var posLetter = getBoxPosLetter(d0);
  50318. var boxPositions = [];
  50319. for(i = 0; i < data.length; i++) {
  50320. var trace = data[i];
  50321. if(!traceIs(trace, 'box-violin') || (trace[axLetter + 'axis'] || axLetter) !== id) continue;
  50322. if(trace[posLetter] !== undefined) boxPositions.push(trace[posLetter][0]);
  50323. else if(trace.name !== undefined) boxPositions.push(trace.name);
  50324. else boxPositions.push('text');
  50325. if(trace[calAttr] !== calendar) calendar = undefined;
  50326. }
  50327. ax.type = autoType(boxPositions, calendar, opts);
  50328. }
  50329. else if(d0.type === 'splom') {
  50330. var dimensions = d0.dimensions;
  50331. var diag = d0._diag;
  50332. for(i = 0; i < dimensions.length; i++) {
  50333. var dim = dimensions[i];
  50334. if(dim.visible && (diag[i][0] === id || diag[i][1] === id)) {
  50335. ax.type = autoType(dim.values, calendar, opts);
  50336. break;
  50337. }
  50338. }
  50339. }
  50340. else {
  50341. ax.type = autoType(d0[axLetter] || [d0[axLetter + '0']], calendar, opts);
  50342. }
  50343. }
  50344. function getFirstNonEmptyTrace(data, id, axLetter) {
  50345. for(var i = 0; i < data.length; i++) {
  50346. var trace = data[i];
  50347. if(trace.type === 'splom' &&
  50348. trace._length > 0 &&
  50349. (trace['_' + axLetter + 'axes'] || {})[id]
  50350. ) {
  50351. return trace;
  50352. }
  50353. if((trace[axLetter + 'axis'] || axLetter) === id) {
  50354. if(isBoxWithoutPositionCoords(trace, axLetter)) {
  50355. return trace;
  50356. }
  50357. else if((trace[axLetter] || []).length || trace[axLetter + '0']) {
  50358. return trace;
  50359. }
  50360. }
  50361. }
  50362. }
  50363. function getBoxPosLetter(trace) {
  50364. return {v: 'x', h: 'y'}[trace.orientation || 'v'];
  50365. }
  50366. function isBoxWithoutPositionCoords(trace, axLetter) {
  50367. var posLetter = getBoxPosLetter(trace);
  50368. var isBox = traceIs(trace, 'box-violin');
  50369. var isCandlestick = traceIs(trace._fullInput || {}, 'candlestick');
  50370. return (
  50371. isBox &&
  50372. !isCandlestick &&
  50373. axLetter === posLetter &&
  50374. trace[posLetter] === undefined &&
  50375. trace[posLetter + '0'] === undefined
  50376. );
  50377. }
  50378. },{"../../registry":257,"./axis_autotype":213}],237:[function(_dereq_,module,exports){
  50379. /**
  50380. * Copyright 2012-2019, Plotly, Inc.
  50381. * All rights reserved.
  50382. *
  50383. * This source code is licensed under the MIT license found in the
  50384. * LICENSE file in the root directory of this source tree.
  50385. */
  50386. 'use strict';
  50387. var Registry = _dereq_('../registry');
  50388. var Lib = _dereq_('../lib');
  50389. /*
  50390. * Create or update an observer. This function is designed to be
  50391. * idempotent so that it can be called over and over as the component
  50392. * updates, and will attach and detach listeners as needed.
  50393. *
  50394. * @param {optional object} container
  50395. * An object on which the observer is stored. This is the mechanism
  50396. * by which it is idempotent. If it already exists, another won't be
  50397. * added. Each time it's called, the value lookup table is updated.
  50398. * @param {array} commandList
  50399. * An array of commands, following either `buttons` of `updatemenus`
  50400. * or `steps` of `sliders`.
  50401. * @param {function} onchange
  50402. * A listener called when the value is changed. Receives data object
  50403. * with information about the new state.
  50404. */
  50405. exports.manageCommandObserver = function(gd, container, commandList, onchange) {
  50406. var ret = {};
  50407. var enabled = true;
  50408. if(container && container._commandObserver) {
  50409. ret = container._commandObserver;
  50410. }
  50411. if(!ret.cache) {
  50412. ret.cache = {};
  50413. }
  50414. // Either create or just recompute this:
  50415. ret.lookupTable = {};
  50416. var binding = exports.hasSimpleAPICommandBindings(gd, commandList, ret.lookupTable);
  50417. if(container && container._commandObserver) {
  50418. if(!binding) {
  50419. // If container exists and there are no longer any bindings,
  50420. // remove existing:
  50421. if(container._commandObserver.remove) {
  50422. container._commandObserver.remove();
  50423. container._commandObserver = null;
  50424. return ret;
  50425. }
  50426. } else {
  50427. // If container exists and there *are* bindings, then the lookup
  50428. // table should have been updated and check is already attached,
  50429. // so there's nothing to be done:
  50430. return ret;
  50431. }
  50432. }
  50433. // Determine whether there's anything to do for this binding:
  50434. if(binding) {
  50435. // Build the cache:
  50436. bindingValueHasChanged(gd, binding, ret.cache);
  50437. ret.check = function check() {
  50438. if(!enabled) return;
  50439. var update = bindingValueHasChanged(gd, binding, ret.cache);
  50440. if(update.changed && onchange) {
  50441. // Disable checks for the duration of this command in order to avoid
  50442. // infinite loops:
  50443. if(ret.lookupTable[update.value] !== undefined) {
  50444. ret.disable();
  50445. Promise.resolve(onchange({
  50446. value: update.value,
  50447. type: binding.type,
  50448. prop: binding.prop,
  50449. traces: binding.traces,
  50450. index: ret.lookupTable[update.value]
  50451. })).then(ret.enable, ret.enable);
  50452. }
  50453. }
  50454. return update.changed;
  50455. };
  50456. var checkEvents = [
  50457. 'plotly_relayout',
  50458. 'plotly_redraw',
  50459. 'plotly_restyle',
  50460. 'plotly_update',
  50461. 'plotly_animatingframe',
  50462. 'plotly_afterplot'
  50463. ];
  50464. for(var i = 0; i < checkEvents.length; i++) {
  50465. gd._internalOn(checkEvents[i], ret.check);
  50466. }
  50467. ret.remove = function() {
  50468. for(var i = 0; i < checkEvents.length; i++) {
  50469. gd._removeInternalListener(checkEvents[i], ret.check);
  50470. }
  50471. };
  50472. } else {
  50473. // TODO: It'd be really neat to actually give a *reason* for this, but at least a warning
  50474. // is a start
  50475. Lib.log('Unable to automatically bind plot updates to API command');
  50476. ret.lookupTable = {};
  50477. ret.remove = function() {};
  50478. }
  50479. ret.disable = function disable() {
  50480. enabled = false;
  50481. };
  50482. ret.enable = function enable() {
  50483. enabled = true;
  50484. };
  50485. if(container) {
  50486. container._commandObserver = ret;
  50487. }
  50488. return ret;
  50489. };
  50490. /*
  50491. * This function checks to see if an array of objects containing
  50492. * method and args properties is compatible with automatic two-way
  50493. * binding. The criteria right now are that
  50494. *
  50495. * 1. multiple traces may be affected
  50496. * 2. only one property may be affected
  50497. * 3. the same property must be affected by all commands
  50498. */
  50499. exports.hasSimpleAPICommandBindings = function(gd, commandList, bindingsByValue) {
  50500. var i;
  50501. var n = commandList.length;
  50502. var refBinding;
  50503. for(i = 0; i < n; i++) {
  50504. var binding;
  50505. var command = commandList[i];
  50506. var method = command.method;
  50507. var args = command.args;
  50508. if(!Array.isArray(args)) args = [];
  50509. // If any command has no method, refuse to bind:
  50510. if(!method) {
  50511. return false;
  50512. }
  50513. var bindings = exports.computeAPICommandBindings(gd, method, args);
  50514. // Right now, handle one and *only* one property being set:
  50515. if(bindings.length !== 1) {
  50516. return false;
  50517. }
  50518. if(!refBinding) {
  50519. refBinding = bindings[0];
  50520. if(Array.isArray(refBinding.traces)) {
  50521. refBinding.traces.sort();
  50522. }
  50523. } else {
  50524. binding = bindings[0];
  50525. if(binding.type !== refBinding.type) {
  50526. return false;
  50527. }
  50528. if(binding.prop !== refBinding.prop) {
  50529. return false;
  50530. }
  50531. if(Array.isArray(refBinding.traces)) {
  50532. if(Array.isArray(binding.traces)) {
  50533. binding.traces.sort();
  50534. for(var j = 0; j < refBinding.traces.length; j++) {
  50535. if(refBinding.traces[j] !== binding.traces[j]) {
  50536. return false;
  50537. }
  50538. }
  50539. } else {
  50540. return false;
  50541. }
  50542. } else {
  50543. if(binding.prop !== refBinding.prop) {
  50544. return false;
  50545. }
  50546. }
  50547. }
  50548. binding = bindings[0];
  50549. var value = binding.value;
  50550. if(Array.isArray(value)) {
  50551. if(value.length === 1) {
  50552. value = value[0];
  50553. } else {
  50554. return false;
  50555. }
  50556. }
  50557. if(bindingsByValue) {
  50558. bindingsByValue[value] = i;
  50559. }
  50560. }
  50561. return refBinding;
  50562. };
  50563. function bindingValueHasChanged(gd, binding, cache) {
  50564. var container, value, obj;
  50565. var changed = false;
  50566. if(binding.type === 'data') {
  50567. // If it's data, we need to get a trace. Based on the limited scope
  50568. // of what we cover, we can just take the first trace from the list,
  50569. // or otherwise just the first trace:
  50570. container = gd._fullData[binding.traces !== null ? binding.traces[0] : 0];
  50571. } else if(binding.type === 'layout') {
  50572. container = gd._fullLayout;
  50573. } else {
  50574. return false;
  50575. }
  50576. value = Lib.nestedProperty(container, binding.prop).get();
  50577. obj = cache[binding.type] = cache[binding.type] || {};
  50578. if(obj.hasOwnProperty(binding.prop)) {
  50579. if(obj[binding.prop] !== value) {
  50580. changed = true;
  50581. }
  50582. }
  50583. obj[binding.prop] = value;
  50584. return {
  50585. changed: changed,
  50586. value: value
  50587. };
  50588. }
  50589. /*
  50590. * Execute an API command. There's really not much to this; it just provides
  50591. * a common hook so that implementations don't need to be synchronized across
  50592. * multiple components with the ability to invoke API commands.
  50593. *
  50594. * @param {string} method
  50595. * The name of the plotly command to execute. Must be one of 'animate',
  50596. * 'restyle', 'relayout', 'update'.
  50597. * @param {array} args
  50598. * A list of arguments passed to the API command
  50599. */
  50600. exports.executeAPICommand = function(gd, method, args) {
  50601. if(method === 'skip') return Promise.resolve();
  50602. var _method = Registry.apiMethodRegistry[method];
  50603. var allArgs = [gd];
  50604. if(!Array.isArray(args)) args = [];
  50605. for(var i = 0; i < args.length; i++) {
  50606. allArgs.push(args[i]);
  50607. }
  50608. return _method.apply(null, allArgs).catch(function(err) {
  50609. Lib.warn('API call to Plotly.' + method + ' rejected.', err);
  50610. return Promise.reject(err);
  50611. });
  50612. };
  50613. exports.computeAPICommandBindings = function(gd, method, args) {
  50614. var bindings;
  50615. if(!Array.isArray(args)) args = [];
  50616. switch(method) {
  50617. case 'restyle':
  50618. bindings = computeDataBindings(gd, args);
  50619. break;
  50620. case 'relayout':
  50621. bindings = computeLayoutBindings(gd, args);
  50622. break;
  50623. case 'update':
  50624. bindings = computeDataBindings(gd, [args[0], args[2]])
  50625. .concat(computeLayoutBindings(gd, [args[1]]));
  50626. break;
  50627. case 'animate':
  50628. bindings = computeAnimateBindings(gd, args);
  50629. break;
  50630. default:
  50631. // This is the case where intelligent logic about what affects
  50632. // this command is not implemented. It causes no ill effects.
  50633. // For example, addFrames simply won't bind to a control component.
  50634. bindings = [];
  50635. }
  50636. return bindings;
  50637. };
  50638. function computeAnimateBindings(gd, args) {
  50639. // We'll assume that the only relevant modification an animation
  50640. // makes that's meaningfully tracked is the frame:
  50641. if(Array.isArray(args[0]) && args[0].length === 1 && ['string', 'number'].indexOf(typeof args[0][0]) !== -1) {
  50642. return [{type: 'layout', prop: '_currentFrame', value: args[0][0].toString()}];
  50643. } else {
  50644. return [];
  50645. }
  50646. }
  50647. function computeLayoutBindings(gd, args) {
  50648. var bindings = [];
  50649. var astr = args[0];
  50650. var aobj = {};
  50651. if(typeof astr === 'string') {
  50652. aobj[astr] = args[1];
  50653. } else if(Lib.isPlainObject(astr)) {
  50654. aobj = astr;
  50655. } else {
  50656. return bindings;
  50657. }
  50658. crawl(aobj, function(path, attrName, attr) {
  50659. bindings.push({type: 'layout', prop: path, value: attr});
  50660. }, '', 0);
  50661. return bindings;
  50662. }
  50663. function computeDataBindings(gd, args) {
  50664. var traces, astr, val, aobj;
  50665. var bindings = [];
  50666. // Logic copied from Plotly.restyle:
  50667. astr = args[0];
  50668. val = args[1];
  50669. traces = args[2];
  50670. aobj = {};
  50671. if(typeof astr === 'string') {
  50672. aobj[astr] = val;
  50673. } else if(Lib.isPlainObject(astr)) {
  50674. // the 3-arg form
  50675. aobj = astr;
  50676. if(traces === undefined) {
  50677. traces = val;
  50678. }
  50679. } else {
  50680. return bindings;
  50681. }
  50682. if(traces === undefined) {
  50683. // Explicitly assign this to null instead of undefined:
  50684. traces = null;
  50685. }
  50686. crawl(aobj, function(path, attrName, attr) {
  50687. var thisTraces;
  50688. if(Array.isArray(attr)) {
  50689. var nAttr = Math.min(attr.length, gd.data.length);
  50690. if(traces) {
  50691. nAttr = Math.min(nAttr, traces.length);
  50692. }
  50693. thisTraces = [];
  50694. for(var j = 0; j < nAttr; j++) {
  50695. thisTraces[j] = traces ? traces[j] : j;
  50696. }
  50697. } else {
  50698. thisTraces = traces ? traces.slice(0) : null;
  50699. }
  50700. // Convert [7] to just 7 when traces is null:
  50701. if(thisTraces === null) {
  50702. if(Array.isArray(attr)) {
  50703. attr = attr[0];
  50704. }
  50705. } else if(Array.isArray(thisTraces)) {
  50706. if(!Array.isArray(attr)) {
  50707. var tmp = attr;
  50708. attr = [];
  50709. for(var i = 0; i < thisTraces.length; i++) {
  50710. attr[i] = tmp;
  50711. }
  50712. }
  50713. attr.length = Math.min(thisTraces.length, attr.length);
  50714. }
  50715. bindings.push({
  50716. type: 'data',
  50717. prop: path,
  50718. traces: thisTraces,
  50719. value: attr
  50720. });
  50721. }, '', 0);
  50722. return bindings;
  50723. }
  50724. function crawl(attrs, callback, path, depth) {
  50725. Object.keys(attrs).forEach(function(attrName) {
  50726. var attr = attrs[attrName];
  50727. if(attrName[0] === '_') return;
  50728. var thisPath = path + (depth > 0 ? '.' : '') + attrName;
  50729. if(Lib.isPlainObject(attr)) {
  50730. crawl(attr, callback, thisPath, depth + 1);
  50731. } else {
  50732. // Only execute the callback on leaf nodes:
  50733. callback(thisPath, attrName, attr);
  50734. }
  50735. });
  50736. }
  50737. },{"../lib":168,"../registry":257}],238:[function(_dereq_,module,exports){
  50738. /**
  50739. * Copyright 2012-2019, Plotly, Inc.
  50740. * All rights reserved.
  50741. *
  50742. * This source code is licensed under the MIT license found in the
  50743. * LICENSE file in the root directory of this source tree.
  50744. */
  50745. 'use strict';
  50746. var extendFlat = _dereq_('../lib/extend').extendFlat;
  50747. /**
  50748. * Make a xy domain attribute group
  50749. *
  50750. * @param {object} opts
  50751. * @param {string}
  50752. * opts.name: name to be inserted in the default description
  50753. * @param {boolean}
  50754. * opts.trace: set to true for trace containers
  50755. * @param {string}
  50756. * opts.editType: editType for all pieces
  50757. * @param {boolean}
  50758. * opts.noGridCell: set to true to omit `row` and `column`
  50759. *
  50760. * @param {object} extra
  50761. * @param {string}
  50762. * extra.description: extra description. N.B we use
  50763. * a separate extra container to make it compatible with
  50764. * the compress_attributes transform.
  50765. *
  50766. * @return {object} attributes object containing {x,y} as specified
  50767. */
  50768. exports.attributes = function(opts, extra) {
  50769. opts = opts || {};
  50770. extra = extra || {};
  50771. var base = {
  50772. valType: 'info_array',
  50773. editType: opts.editType,
  50774. items: [
  50775. {valType: 'number', min: 0, max: 1, editType: opts.editType},
  50776. {valType: 'number', min: 0, max: 1, editType: opts.editType}
  50777. ],
  50778. dflt: [0, 1]
  50779. };
  50780. var namePart = opts.name ? opts.name + ' ' : '';
  50781. var contPart = opts.trace ? 'trace ' : 'subplot ';
  50782. var descPart = extra.description ? ' ' + extra.description : '';
  50783. var out = {
  50784. x: extendFlat({}, base, {
  50785. }),
  50786. y: extendFlat({}, base, {
  50787. }),
  50788. editType: opts.editType
  50789. };
  50790. if(!opts.noGridCell) {
  50791. out.row = {
  50792. valType: 'integer',
  50793. min: 0,
  50794. dflt: 0,
  50795. editType: opts.editType,
  50796. };
  50797. out.column = {
  50798. valType: 'integer',
  50799. min: 0,
  50800. dflt: 0,
  50801. editType: opts.editType,
  50802. };
  50803. }
  50804. return out;
  50805. };
  50806. exports.defaults = function(containerOut, layout, coerce, dfltDomains) {
  50807. var dfltX = (dfltDomains && dfltDomains.x) || [0, 1];
  50808. var dfltY = (dfltDomains && dfltDomains.y) || [0, 1];
  50809. var grid = layout.grid;
  50810. if(grid) {
  50811. var column = coerce('domain.column');
  50812. if(column !== undefined) {
  50813. if(column < grid.columns) dfltX = grid._domains.x[column];
  50814. else delete containerOut.domain.column;
  50815. }
  50816. var row = coerce('domain.row');
  50817. if(row !== undefined) {
  50818. if(row < grid.rows) dfltY = grid._domains.y[row];
  50819. else delete containerOut.domain.row;
  50820. }
  50821. }
  50822. coerce('domain.x', dfltX);
  50823. coerce('domain.y', dfltY);
  50824. };
  50825. },{"../lib/extend":162}],239:[function(_dereq_,module,exports){
  50826. /**
  50827. * Copyright 2012-2019, Plotly, Inc.
  50828. * All rights reserved.
  50829. *
  50830. * This source code is licensed under the MIT license found in the
  50831. * LICENSE file in the root directory of this source tree.
  50832. */
  50833. 'use strict';
  50834. /*
  50835. * make a font attribute group
  50836. *
  50837. * @param {object} opts
  50838. * @param {string}
  50839. * opts.description: where & how this font is used
  50840. * @param {optional bool} arrayOk:
  50841. * should each part (family, size, color) be arrayOk? default false.
  50842. * @param {string} editType:
  50843. * the editType for all pieces of this font
  50844. * @param {optional string} colorEditType:
  50845. * a separate editType just for color
  50846. *
  50847. * @return {object} attributes object containing {family, size, color} as specified
  50848. */
  50849. module.exports = function(opts) {
  50850. var editType = opts.editType;
  50851. var colorEditType = opts.colorEditType;
  50852. if(colorEditType === undefined) colorEditType = editType;
  50853. var attrs = {
  50854. family: {
  50855. valType: 'string',
  50856. noBlank: true,
  50857. strict: true,
  50858. editType: editType,
  50859. },
  50860. size: {
  50861. valType: 'number',
  50862. min: 1,
  50863. editType: editType
  50864. },
  50865. color: {
  50866. valType: 'color',
  50867. editType: colorEditType
  50868. },
  50869. editType: editType,
  50870. // blank strings so compress_attributes can remove
  50871. // TODO - that's uber hacky... better solution?
  50872. };
  50873. if(opts.arrayOk) {
  50874. attrs.family.arrayOk = true;
  50875. attrs.size.arrayOk = true;
  50876. attrs.color.arrayOk = true;
  50877. }
  50878. return attrs;
  50879. };
  50880. },{}],240:[function(_dereq_,module,exports){
  50881. /**
  50882. * Copyright 2012-2019, Plotly, Inc.
  50883. * All rights reserved.
  50884. *
  50885. * This source code is licensed under the MIT license found in the
  50886. * LICENSE file in the root directory of this source tree.
  50887. */
  50888. 'use strict';
  50889. module.exports = {
  50890. _isLinkedToArray: 'frames_entry',
  50891. group: {
  50892. valType: 'string',
  50893. },
  50894. name: {
  50895. valType: 'string',
  50896. },
  50897. traces: {
  50898. valType: 'any',
  50899. },
  50900. baseframe: {
  50901. valType: 'string',
  50902. },
  50903. data: {
  50904. valType: 'any',
  50905. },
  50906. layout: {
  50907. valType: 'any',
  50908. }
  50909. };
  50910. },{}],241:[function(_dereq_,module,exports){
  50911. /**
  50912. * Copyright 2012-2019, Plotly, Inc.
  50913. * All rights reserved.
  50914. *
  50915. * This source code is licensed under the MIT license found in the
  50916. * LICENSE file in the root directory of this source tree.
  50917. */
  50918. 'use strict';
  50919. var Registry = _dereq_('../registry');
  50920. var SUBPLOT_PATTERN = _dereq_('./cartesian/constants').SUBPLOT_PATTERN;
  50921. /**
  50922. * Get calcdata trace(s) associated with a given subplot
  50923. *
  50924. * @param {array} calcData: as in gd.calcdata
  50925. * @param {string} type: subplot type
  50926. * @param {string} subplotId: subplot id to look for
  50927. *
  50928. * @return {array} array of calcdata traces
  50929. */
  50930. exports.getSubplotCalcData = function(calcData, type, subplotId) {
  50931. var basePlotModule = Registry.subplotsRegistry[type];
  50932. if(!basePlotModule) return [];
  50933. var attr = basePlotModule.attr;
  50934. var subplotCalcData = [];
  50935. for(var i = 0; i < calcData.length; i++) {
  50936. var calcTrace = calcData[i];
  50937. var trace = calcTrace[0].trace;
  50938. if(trace[attr] === subplotId) subplotCalcData.push(calcTrace);
  50939. }
  50940. return subplotCalcData;
  50941. };
  50942. /**
  50943. * Get calcdata trace(s) that can be plotted with a given module
  50944. * NOTE: this isn't necessarily just exactly matching trace type,
  50945. * if multiple trace types use the same plotting routine, they will be
  50946. * collected here.
  50947. * In order to not plot the same thing multiple times, we return two arrays,
  50948. * the calcdata we *will* plot with this module, and the ones we *won't*
  50949. *
  50950. * @param {array} calcdata: as in gd.calcdata
  50951. * @param {object|string|fn} arg1:
  50952. * the plotting module, or its name, or its plot method
  50953. *
  50954. * @return {array[array]} [foundCalcdata, remainingCalcdata]
  50955. */
  50956. exports.getModuleCalcData = function(calcdata, arg1) {
  50957. var moduleCalcData = [];
  50958. var remainingCalcData = [];
  50959. var plotMethod;
  50960. if(typeof arg1 === 'string') {
  50961. plotMethod = Registry.getModule(arg1).plot;
  50962. } else if(typeof arg1 === 'function') {
  50963. plotMethod = arg1;
  50964. } else {
  50965. plotMethod = arg1.plot;
  50966. }
  50967. if(!plotMethod) {
  50968. return [moduleCalcData, calcdata];
  50969. }
  50970. for(var i = 0; i < calcdata.length; i++) {
  50971. var cd = calcdata[i];
  50972. var trace = cd[0].trace;
  50973. // N.B. 'legendonly' traces do not make it past here
  50974. if(trace.visible !== true) continue;
  50975. // group calcdata trace not by 'module' (as the name of this function
  50976. // would suggest), but by 'module plot method' so that if some traces
  50977. // share the same module plot method (e.g. bar and histogram), we
  50978. // only call it one!
  50979. if(trace._module.plot === plotMethod) {
  50980. moduleCalcData.push(cd);
  50981. } else {
  50982. remainingCalcData.push(cd);
  50983. }
  50984. }
  50985. return [moduleCalcData, remainingCalcData];
  50986. };
  50987. /**
  50988. * Get the data trace(s) associated with a given subplot.
  50989. *
  50990. * @param {array} data plotly full data array.
  50991. * @param {string} type subplot type to look for.
  50992. * @param {string} subplotId subplot id to look for.
  50993. *
  50994. * @return {array} list of trace objects.
  50995. *
  50996. */
  50997. exports.getSubplotData = function getSubplotData(data, type, subplotId) {
  50998. if(!Registry.subplotsRegistry[type]) return [];
  50999. var attr = Registry.subplotsRegistry[type].attr;
  51000. var subplotData = [];
  51001. var trace, subplotX, subplotY;
  51002. if(type === 'gl2d') {
  51003. var spmatch = subplotId.match(SUBPLOT_PATTERN);
  51004. subplotX = 'x' + spmatch[1];
  51005. subplotY = 'y' + spmatch[2];
  51006. }
  51007. for(var i = 0; i < data.length; i++) {
  51008. trace = data[i];
  51009. if(type === 'gl2d' && Registry.traceIs(trace, 'gl2d')) {
  51010. if(trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) {
  51011. subplotData.push(trace);
  51012. }
  51013. }
  51014. else {
  51015. if(trace[attr] === subplotId) subplotData.push(trace);
  51016. }
  51017. }
  51018. return subplotData;
  51019. };
  51020. },{"../registry":257,"./cartesian/constants":218}],242:[function(_dereq_,module,exports){
  51021. /**
  51022. * Copyright 2012-2019, Plotly, Inc.
  51023. * All rights reserved.
  51024. *
  51025. * This source code is licensed under the MIT license found in the
  51026. * LICENSE file in the root directory of this source tree.
  51027. */
  51028. 'use strict';
  51029. function xformMatrix(m, v) {
  51030. var out = [0, 0, 0, 0];
  51031. var i, j;
  51032. for(i = 0; i < 4; ++i) {
  51033. for(j = 0; j < 4; ++j) {
  51034. out[j] += m[4 * i + j] * v[i];
  51035. }
  51036. }
  51037. return out;
  51038. }
  51039. function project(camera, v) {
  51040. var p = xformMatrix(camera.projection,
  51041. xformMatrix(camera.view,
  51042. xformMatrix(camera.model, [v[0], v[1], v[2], 1])));
  51043. return p;
  51044. }
  51045. module.exports = project;
  51046. },{}],243:[function(_dereq_,module,exports){
  51047. /**
  51048. * Copyright 2012-2019, Plotly, Inc.
  51049. * All rights reserved.
  51050. *
  51051. * This source code is licensed under the MIT license found in the
  51052. * LICENSE file in the root directory of this source tree.
  51053. */
  51054. 'use strict';
  51055. var fontAttrs = _dereq_('./font_attributes');
  51056. var animationAttrs = _dereq_('./animation_attributes');
  51057. var colorAttrs = _dereq_('../components/color/attributes');
  51058. var colorscaleAttrs = _dereq_('../components/colorscale/layout_attributes');
  51059. var padAttrs = _dereq_('./pad_attributes');
  51060. var extendFlat = _dereq_('../lib/extend').extendFlat;
  51061. var globalFont = fontAttrs({
  51062. editType: 'calc',
  51063. });
  51064. globalFont.family.dflt = '"Open Sans", verdana, arial, sans-serif';
  51065. globalFont.size.dflt = 12;
  51066. globalFont.color.dflt = colorAttrs.defaultLine;
  51067. module.exports = {
  51068. font: globalFont,
  51069. title: {
  51070. text: {
  51071. valType: 'string',
  51072. editType: 'layoutstyle',
  51073. },
  51074. font: fontAttrs({
  51075. editType: 'layoutstyle',
  51076. }),
  51077. xref: {
  51078. valType: 'enumerated',
  51079. dflt: 'container',
  51080. values: ['container', 'paper'],
  51081. editType: 'layoutstyle',
  51082. },
  51083. yref: {
  51084. valType: 'enumerated',
  51085. dflt: 'container',
  51086. values: ['container', 'paper'],
  51087. editType: 'layoutstyle',
  51088. },
  51089. x: {
  51090. valType: 'number',
  51091. min: 0,
  51092. max: 1,
  51093. dflt: 0.5,
  51094. editType: 'layoutstyle',
  51095. },
  51096. y: {
  51097. valType: 'number',
  51098. min: 0,
  51099. max: 1,
  51100. dflt: 'auto',
  51101. editType: 'layoutstyle',
  51102. },
  51103. xanchor: {
  51104. valType: 'enumerated',
  51105. dflt: 'auto',
  51106. values: ['auto', 'left', 'center', 'right'],
  51107. editType: 'layoutstyle',
  51108. },
  51109. yanchor: {
  51110. valType: 'enumerated',
  51111. dflt: 'auto',
  51112. values: ['auto', 'top', 'middle', 'bottom'],
  51113. editType: 'layoutstyle',
  51114. },
  51115. pad: extendFlat(padAttrs({editType: 'layoutstyle'}), {
  51116. }),
  51117. editType: 'layoutstyle'
  51118. },
  51119. autosize: {
  51120. valType: 'boolean',
  51121. dflt: false,
  51122. // autosize, width, and height get special editType treatment in _relayout
  51123. // so we can handle noop resizes more efficiently
  51124. editType: 'none',
  51125. },
  51126. width: {
  51127. valType: 'number',
  51128. min: 10,
  51129. dflt: 700,
  51130. editType: 'plot',
  51131. },
  51132. height: {
  51133. valType: 'number',
  51134. min: 10,
  51135. dflt: 450,
  51136. editType: 'plot',
  51137. },
  51138. margin: {
  51139. l: {
  51140. valType: 'number',
  51141. min: 0,
  51142. dflt: 80,
  51143. editType: 'plot',
  51144. },
  51145. r: {
  51146. valType: 'number',
  51147. min: 0,
  51148. dflt: 80,
  51149. editType: 'plot',
  51150. },
  51151. t: {
  51152. valType: 'number',
  51153. min: 0,
  51154. dflt: 100,
  51155. editType: 'plot',
  51156. },
  51157. b: {
  51158. valType: 'number',
  51159. min: 0,
  51160. dflt: 80,
  51161. editType: 'plot',
  51162. },
  51163. pad: {
  51164. valType: 'number',
  51165. min: 0,
  51166. dflt: 0,
  51167. editType: 'plot',
  51168. },
  51169. autoexpand: {
  51170. valType: 'boolean',
  51171. dflt: true,
  51172. editType: 'plot'
  51173. },
  51174. editType: 'plot'
  51175. },
  51176. paper_bgcolor: {
  51177. valType: 'color',
  51178. dflt: colorAttrs.background,
  51179. editType: 'plot',
  51180. },
  51181. plot_bgcolor: {
  51182. // defined here, but set in cartesian.supplyLayoutDefaults
  51183. // because it needs to know if there are (2D) axes or not
  51184. valType: 'color',
  51185. dflt: colorAttrs.background,
  51186. editType: 'layoutstyle',
  51187. },
  51188. separators: {
  51189. valType: 'string',
  51190. editType: 'plot',
  51191. },
  51192. hidesources: {
  51193. valType: 'boolean',
  51194. dflt: false,
  51195. editType: 'plot',
  51196. },
  51197. showlegend: {
  51198. // handled in legend.supplyLayoutDefaults
  51199. // but included here because it's not in the legend object
  51200. valType: 'boolean',
  51201. editType: 'legend',
  51202. },
  51203. colorway: {
  51204. valType: 'colorlist',
  51205. dflt: colorAttrs.defaults,
  51206. editType: 'calc',
  51207. },
  51208. colorscale: colorscaleAttrs,
  51209. datarevision: {
  51210. valType: 'any',
  51211. editType: 'calc',
  51212. },
  51213. uirevision: {
  51214. valType: 'any',
  51215. editType: 'none',
  51216. },
  51217. editrevision: {
  51218. valType: 'any',
  51219. editType: 'none',
  51220. },
  51221. selectionrevision: {
  51222. valType: 'any',
  51223. editType: 'none',
  51224. },
  51225. template: {
  51226. valType: 'any',
  51227. editType: 'calc',
  51228. },
  51229. modebar: {
  51230. orientation: {
  51231. valType: 'enumerated',
  51232. values: ['v', 'h'],
  51233. dflt: 'h',
  51234. editType: 'modebar',
  51235. },
  51236. bgcolor: {
  51237. valType: 'color',
  51238. editType: 'modebar',
  51239. },
  51240. color: {
  51241. valType: 'color',
  51242. editType: 'modebar',
  51243. },
  51244. activecolor: {
  51245. valType: 'color',
  51246. editType: 'modebar',
  51247. },
  51248. uirevision: {
  51249. valType: 'any',
  51250. editType: 'none',
  51251. },
  51252. editType: 'modebar'
  51253. },
  51254. meta: {
  51255. valType: 'data_array',
  51256. editType: 'plot',
  51257. },
  51258. transition: extendFlat({}, animationAttrs.transition, {
  51259. editType: 'none'
  51260. }),
  51261. _deprecated: {
  51262. title: {
  51263. valType: 'string',
  51264. editType: 'layoutstyle',
  51265. },
  51266. titlefont: fontAttrs({
  51267. editType: 'layoutstyle',
  51268. })
  51269. }
  51270. };
  51271. },{"../components/color/attributes":50,"../components/colorscale/layout_attributes":64,"../lib/extend":162,"./animation_attributes":207,"./font_attributes":239,"./pad_attributes":244}],244:[function(_dereq_,module,exports){
  51272. /**
  51273. * Copyright 2012-2019, Plotly, Inc.
  51274. * All rights reserved.
  51275. *
  51276. * This source code is licensed under the MIT license found in the
  51277. * LICENSE file in the root directory of this source tree.
  51278. */
  51279. 'use strict';
  51280. /**
  51281. * Creates a set of padding attributes.
  51282. *
  51283. * @param {object} opts
  51284. * @param {string} editType:
  51285. * the editType for all pieces of this padding definition
  51286. *
  51287. * @return {object} attributes object containing {t, r, b, l} as specified
  51288. */
  51289. module.exports = function(opts) {
  51290. var editType = opts.editType;
  51291. return {
  51292. t: {
  51293. valType: 'number',
  51294. dflt: 0,
  51295. editType: editType,
  51296. },
  51297. r: {
  51298. valType: 'number',
  51299. dflt: 0,
  51300. editType: editType,
  51301. },
  51302. b: {
  51303. valType: 'number',
  51304. dflt: 0,
  51305. editType: editType,
  51306. },
  51307. l: {
  51308. valType: 'number',
  51309. dflt: 0,
  51310. editType: editType,
  51311. },
  51312. editType: editType
  51313. };
  51314. };
  51315. },{}],245:[function(_dereq_,module,exports){
  51316. /**
  51317. * Copyright 2012-2019, Plotly, Inc.
  51318. * All rights reserved.
  51319. *
  51320. * This source code is licensed under the MIT license found in the
  51321. * LICENSE file in the root directory of this source tree.
  51322. */
  51323. 'use strict';
  51324. var d3 = _dereq_('d3');
  51325. var isNumeric = _dereq_('fast-isnumeric');
  51326. var Registry = _dereq_('../registry');
  51327. var PlotSchema = _dereq_('../plot_api/plot_schema');
  51328. var Template = _dereq_('../plot_api/plot_template');
  51329. var Lib = _dereq_('../lib');
  51330. var Color = _dereq_('../components/color');
  51331. var BADNUM = _dereq_('../constants/numerical').BADNUM;
  51332. var axisIDs = _dereq_('../plots/cartesian/axis_ids');
  51333. var animationAttrs = _dereq_('./animation_attributes');
  51334. var frameAttrs = _dereq_('./frame_attributes');
  51335. var relinkPrivateKeys = Lib.relinkPrivateKeys;
  51336. var _ = Lib._;
  51337. var plots = module.exports = {};
  51338. // Expose registry methods on Plots for backward-compatibility
  51339. Lib.extendFlat(plots, Registry);
  51340. plots.attributes = _dereq_('./attributes');
  51341. plots.attributes.type.values = plots.allTypes;
  51342. plots.fontAttrs = _dereq_('./font_attributes');
  51343. plots.layoutAttributes = _dereq_('./layout_attributes');
  51344. // TODO make this a plot attribute?
  51345. plots.fontWeight = 'normal';
  51346. var transformsRegistry = plots.transformsRegistry;
  51347. var commandModule = _dereq_('./command');
  51348. plots.executeAPICommand = commandModule.executeAPICommand;
  51349. plots.computeAPICommandBindings = commandModule.computeAPICommandBindings;
  51350. plots.manageCommandObserver = commandModule.manageCommandObserver;
  51351. plots.hasSimpleAPICommandBindings = commandModule.hasSimpleAPICommandBindings;
  51352. // in some cases the browser doesn't seem to know how big
  51353. // the text is at first, so it needs to draw it,
  51354. // then wait a little, then draw it again
  51355. plots.redrawText = function(gd) {
  51356. gd = Lib.getGraphDiv(gd);
  51357. // do not work if polar is present
  51358. if((gd.data && gd.data[0] && gd.data[0].r)) return;
  51359. return new Promise(function(resolve) {
  51360. setTimeout(function() {
  51361. Registry.getComponentMethod('annotations', 'draw')(gd);
  51362. Registry.getComponentMethod('legend', 'draw')(gd);
  51363. (gd.calcdata || []).forEach(function(d) {
  51364. if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb();
  51365. });
  51366. resolve(plots.previousPromises(gd));
  51367. }, 300);
  51368. });
  51369. };
  51370. // resize plot about the container size
  51371. plots.resize = function(gd) {
  51372. gd = Lib.getGraphDiv(gd);
  51373. return new Promise(function(resolve, reject) {
  51374. function isHidden(gd) {
  51375. var display = window.getComputedStyle(gd).display;
  51376. return !display || display === 'none';
  51377. }
  51378. if(!gd || isHidden(gd)) {
  51379. reject(new Error('Resize must be passed a displayed plot div element.'));
  51380. }
  51381. if(gd._redrawTimer) clearTimeout(gd._redrawTimer);
  51382. gd._redrawTimer = setTimeout(function() {
  51383. // return if there is nothing to resize or is hidden
  51384. if(!gd.layout || (gd.layout.width && gd.layout.height) || isHidden(gd)) {
  51385. resolve(gd);
  51386. return;
  51387. }
  51388. delete gd.layout.width;
  51389. delete gd.layout.height;
  51390. // autosizing doesn't count as a change that needs saving
  51391. var oldchanged = gd.changed;
  51392. // nor should it be included in the undo queue
  51393. gd.autoplay = true;
  51394. Registry.call('relayout', gd, {autosize: true}).then(function() {
  51395. gd.changed = oldchanged;
  51396. resolve(gd);
  51397. });
  51398. }, 100);
  51399. });
  51400. };
  51401. // for use in Lib.syncOrAsync, check if there are any
  51402. // pending promises in this plot and wait for them
  51403. plots.previousPromises = function(gd) {
  51404. if((gd._promises || []).length) {
  51405. return Promise.all(gd._promises)
  51406. .then(function() { gd._promises = []; });
  51407. }
  51408. };
  51409. /**
  51410. * Adds the 'Edit chart' link.
  51411. * Note that now Plotly.plot() calls this so it can regenerate whenever it replots
  51412. *
  51413. * Add source links to your graph inside the 'showSources' config argument.
  51414. */
  51415. plots.addLinks = function(gd) {
  51416. // Do not do anything if showLink and showSources are not set to true in config
  51417. if(!gd._context.showLink && !gd._context.showSources) return;
  51418. var fullLayout = gd._fullLayout;
  51419. var linkContainer = Lib.ensureSingle(fullLayout._paper, 'text', 'js-plot-link-container', function(s) {
  51420. s.style({
  51421. 'font-family': '"Open Sans", Arial, sans-serif',
  51422. 'font-size': '12px',
  51423. 'fill': Color.defaultLine,
  51424. 'pointer-events': 'all'
  51425. })
  51426. .each(function() {
  51427. var links = d3.select(this);
  51428. links.append('tspan').classed('js-link-to-tool', true);
  51429. links.append('tspan').classed('js-link-spacer', true);
  51430. links.append('tspan').classed('js-sourcelinks', true);
  51431. });
  51432. });
  51433. // The text node inside svg
  51434. var text = linkContainer.node();
  51435. var attrs = {y: fullLayout._paper.attr('height') - 9};
  51436. // If text's width is bigger than the layout
  51437. // Check that text is a child node or document.body
  51438. // because otherwise IE/Edge might throw an exception
  51439. // when calling getComputedTextLength().
  51440. // Apparently offsetParent is null for invisibles.
  51441. if(document.body.contains(text) && text.getComputedTextLength() >= (fullLayout.width - 20)) {
  51442. // Align the text at the left
  51443. attrs['text-anchor'] = 'start';
  51444. attrs.x = 5;
  51445. }
  51446. else {
  51447. // Align the text at the right
  51448. attrs['text-anchor'] = 'end';
  51449. attrs.x = fullLayout._paper.attr('width') - 7;
  51450. }
  51451. linkContainer.attr(attrs);
  51452. var toolspan = linkContainer.select('.js-link-to-tool');
  51453. var spacespan = linkContainer.select('.js-link-spacer');
  51454. var sourcespan = linkContainer.select('.js-sourcelinks');
  51455. if(gd._context.showSources) gd._context.showSources(gd);
  51456. // 'view in plotly' link for embedded plots
  51457. if(gd._context.showLink) positionPlayWithData(gd, toolspan);
  51458. // separator if we have both sources and tool link
  51459. spacespan.text((toolspan.text() && sourcespan.text()) ? ' - ' : '');
  51460. };
  51461. // note that now this function is only adding the brand in
  51462. // iframes and 3rd-party apps
  51463. function positionPlayWithData(gd, container) {
  51464. container.text('');
  51465. var link = container.append('a')
  51466. .attr({
  51467. 'xlink:xlink:href': '#',
  51468. 'class': 'link--impt link--embedview',
  51469. 'font-weight': 'bold'
  51470. })
  51471. .text(gd._context.linkText + ' ' + String.fromCharCode(187));
  51472. if(gd._context.sendData) {
  51473. link.on('click', function() {
  51474. plots.sendDataToCloud(gd);
  51475. });
  51476. }
  51477. else {
  51478. var path = window.location.pathname.split('/');
  51479. var query = window.location.search;
  51480. link.attr({
  51481. 'xlink:xlink:show': 'new',
  51482. 'xlink:xlink:href': '/' + path[2].split('.')[0] + '/' + path[1] + query
  51483. });
  51484. }
  51485. }
  51486. plots.sendDataToCloud = function(gd) {
  51487. gd.emit('plotly_beforeexport');
  51488. var baseUrl = (window.PLOTLYENV || {}).BASE_URL || gd._context.plotlyServerURL;
  51489. var hiddenformDiv = d3.select(gd)
  51490. .append('div')
  51491. .attr('id', 'hiddenform')
  51492. .style('display', 'none');
  51493. var hiddenform = hiddenformDiv
  51494. .append('form')
  51495. .attr({
  51496. action: baseUrl + '/external',
  51497. method: 'post',
  51498. target: '_blank'
  51499. });
  51500. var hiddenformInput = hiddenform
  51501. .append('input')
  51502. .attr({
  51503. type: 'text',
  51504. name: 'data'
  51505. });
  51506. hiddenformInput.node().value = plots.graphJson(gd, false, 'keepdata');
  51507. hiddenform.node().submit();
  51508. hiddenformDiv.remove();
  51509. gd.emit('plotly_afterexport');
  51510. return false;
  51511. };
  51512. var d3FormatKeys = [
  51513. 'days', 'shortDays', 'months', 'shortMonths', 'periods',
  51514. 'dateTime', 'date', 'time',
  51515. 'decimal', 'thousands', 'grouping', 'currency'
  51516. ];
  51517. var extraFormatKeys = [
  51518. 'year', 'month', 'dayMonth', 'dayMonthYear'
  51519. ];
  51520. /*
  51521. * Fill in default values
  51522. * @param {DOM element} gd
  51523. * @param {object} opts
  51524. * @param {boolean} opts.skipUpdateCalc: normally if the existing gd.calcdata looks
  51525. * compatible with the new gd._fullData we finish by linking the new _fullData traces
  51526. * to the old gd.calcdata, so it's correctly set if we're not going to recalc. But also,
  51527. * if there are calcTransforms on the trace, we first remap data arrays from the old full
  51528. * trace into the new one. Use skipUpdateCalc to defer this (needed by Plotly.react)
  51529. *
  51530. * gd.data, gd.layout:
  51531. * are precisely what the user specified (except as modified by cleanData/cleanLayout),
  51532. * these fields shouldn't be modified (except for filling in some auto values)
  51533. * nor used directly after the supply defaults step.
  51534. *
  51535. * gd._fullData, gd._fullLayout:
  51536. * are complete descriptions of how to draw the plot,
  51537. * use these fields in all required computations.
  51538. *
  51539. * gd._fullLayout._modules
  51540. * is a list of all the trace modules required to draw the plot.
  51541. *
  51542. * gd._fullLayout._visibleModules
  51543. * subset of _modules, a list of modules corresponding to visible:true traces.
  51544. *
  51545. * gd._fullLayout._basePlotModules
  51546. * is a list of all the plot modules required to draw the plot.
  51547. *
  51548. * gd._fullLayout._transformModules
  51549. * is a list of all the transform modules invoked.
  51550. *
  51551. */
  51552. plots.supplyDefaults = function(gd, opts) {
  51553. var skipUpdateCalc = opts && opts.skipUpdateCalc;
  51554. var oldFullLayout = gd._fullLayout || {};
  51555. if(oldFullLayout._skipDefaults) {
  51556. delete oldFullLayout._skipDefaults;
  51557. return;
  51558. }
  51559. var newFullLayout = gd._fullLayout = {};
  51560. var newLayout = gd.layout || {};
  51561. var oldFullData = gd._fullData || [];
  51562. var newFullData = gd._fullData = [];
  51563. var newData = gd.data || [];
  51564. var oldCalcdata = gd.calcdata || [];
  51565. var context = gd._context || {};
  51566. var i;
  51567. // Create all the storage space for frames, but only if doesn't already exist
  51568. if(!gd._transitionData) plots.createTransitionData(gd);
  51569. // So we only need to do this once (and since we have gd here)
  51570. // get the translated placeholder titles.
  51571. // These ones get used as default values so need to be known at supplyDefaults
  51572. // others keep their blank defaults but render the placeholder as desired later
  51573. // TODO: make these work the same way, only inserting the placeholder text at draw time?
  51574. // The challenge is that this has slightly different behavior right now in editable mode:
  51575. // using the placeholder as default makes this text permanently (but lightly) visible,
  51576. // but explicit '' for these titles gives you a placeholder that's hidden until you mouse
  51577. // over it - so you're not distracted by it if you really don't want a title, but if you do
  51578. // and you're new to plotly you may not be able to find it.
  51579. // When editable=false the two behave the same, no title is drawn.
  51580. newFullLayout._dfltTitle = {
  51581. plot: _(gd, 'Click to enter Plot title'),
  51582. x: _(gd, 'Click to enter X axis title'),
  51583. y: _(gd, 'Click to enter Y axis title'),
  51584. colorbar: _(gd, 'Click to enter Colorscale title'),
  51585. annotation: _(gd, 'new text')
  51586. };
  51587. newFullLayout._traceWord = _(gd, 'trace');
  51588. var formatObj = getFormatObj(gd, d3FormatKeys);
  51589. // stash the token from context so mapbox subplots can use it as default
  51590. newFullLayout._mapboxAccessToken = context.mapboxAccessToken;
  51591. // first fill in what we can of layout without looking at data
  51592. // because fullData needs a few things from layout
  51593. if(oldFullLayout._initialAutoSizeIsDone) {
  51594. // coerce the updated layout while preserving width and height
  51595. var oldWidth = oldFullLayout.width;
  51596. var oldHeight = oldFullLayout.height;
  51597. plots.supplyLayoutGlobalDefaults(newLayout, newFullLayout, formatObj);
  51598. if(!newLayout.width) newFullLayout.width = oldWidth;
  51599. if(!newLayout.height) newFullLayout.height = oldHeight;
  51600. plots.sanitizeMargins(newFullLayout);
  51601. }
  51602. else {
  51603. // coerce the updated layout and autosize if needed
  51604. plots.supplyLayoutGlobalDefaults(newLayout, newFullLayout, formatObj);
  51605. var missingWidthOrHeight = (!newLayout.width || !newLayout.height);
  51606. var autosize = newFullLayout.autosize;
  51607. var autosizable = context.autosizable;
  51608. var initialAutoSize = missingWidthOrHeight && (autosize || autosizable);
  51609. if(initialAutoSize) plots.plotAutoSize(gd, newLayout, newFullLayout);
  51610. else if(missingWidthOrHeight) plots.sanitizeMargins(newFullLayout);
  51611. // for backwards-compatibility with Plotly v1.x.x
  51612. if(!autosize && missingWidthOrHeight) {
  51613. newLayout.width = newFullLayout.width;
  51614. newLayout.height = newFullLayout.height;
  51615. }
  51616. }
  51617. newFullLayout._d3locale = getFormatter(formatObj, newFullLayout.separators);
  51618. newFullLayout._extraFormat = getFormatObj(gd, extraFormatKeys);
  51619. newFullLayout._initialAutoSizeIsDone = true;
  51620. // keep track of how many traces are inputted
  51621. newFullLayout._dataLength = newData.length;
  51622. // clear the lists of trace and baseplot modules, and subplots
  51623. newFullLayout._modules = [];
  51624. newFullLayout._visibleModules = [];
  51625. newFullLayout._basePlotModules = [];
  51626. var subplots = newFullLayout._subplots = emptySubplotLists();
  51627. // initialize axis and subplot hash objects for splom-generated grids
  51628. var splomAxes = newFullLayout._splomAxes = {x: {}, y: {}};
  51629. var splomSubplots = newFullLayout._splomSubplots = {};
  51630. // initialize splom grid defaults
  51631. newFullLayout._splomGridDflt = {};
  51632. // for stacked area traces to share config across traces
  51633. newFullLayout._scatterStackOpts = {};
  51634. // for the first scatter trace on each subplot (so it knows tonext->tozero)
  51635. newFullLayout._firstScatter = {};
  51636. // for traces to request a default rangeslider on their x axes
  51637. // eg set `_requestRangeslider.x2 = true` for xaxis2
  51638. newFullLayout._requestRangeslider = {};
  51639. // pull uids from old data to use as new defaults
  51640. newFullLayout._traceUids = getTraceUids(oldFullData, newData);
  51641. // then do the data
  51642. newFullLayout._globalTransforms = (gd._context || {}).globalTransforms;
  51643. plots.supplyDataDefaults(newData, newFullData, newLayout, newFullLayout);
  51644. // redo grid size defaults with info about splom x/y axes,
  51645. // and fill in generated cartesian axes and subplots
  51646. var splomXa = Object.keys(splomAxes.x);
  51647. var splomYa = Object.keys(splomAxes.y);
  51648. if(splomXa.length > 1 && splomYa.length > 1) {
  51649. Registry.getComponentMethod('grid', 'sizeDefaults')(newLayout, newFullLayout);
  51650. for(i = 0; i < splomXa.length; i++) {
  51651. Lib.pushUnique(subplots.xaxis, splomXa[i]);
  51652. }
  51653. for(i = 0; i < splomYa.length; i++) {
  51654. Lib.pushUnique(subplots.yaxis, splomYa[i]);
  51655. }
  51656. for(var k in splomSubplots) {
  51657. Lib.pushUnique(subplots.cartesian, k);
  51658. }
  51659. }
  51660. // attach helper method to check whether a plot type is present on graph
  51661. newFullLayout._has = plots._hasPlotType.bind(newFullLayout);
  51662. if(oldFullData.length === newFullData.length) {
  51663. for(i = 0; i < newFullData.length; i++) {
  51664. relinkPrivateKeys(newFullData[i], oldFullData[i]);
  51665. }
  51666. }
  51667. // finally, fill in the pieces of layout that may need to look at data
  51668. plots.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData, gd._transitionData);
  51669. // Special cases that introduce interactions between traces.
  51670. // This is after relinkPrivateKeys so we can use those in crossTraceDefaults
  51671. // and after layout module defaults, so we can use eg barmode
  51672. var _modules = newFullLayout._visibleModules;
  51673. var crossTraceDefaultsFuncs = [];
  51674. for(i = 0; i < _modules.length; i++) {
  51675. var funci = _modules[i].crossTraceDefaults;
  51676. // some trace types share crossTraceDefaults (ie histogram2d, histogram2dcontour)
  51677. if(funci) Lib.pushUnique(crossTraceDefaultsFuncs, funci);
  51678. }
  51679. for(i = 0; i < crossTraceDefaultsFuncs.length; i++) {
  51680. crossTraceDefaultsFuncs[i](newFullData, newFullLayout);
  51681. }
  51682. Registry.getComponentMethod('colorscale', 'crossTraceDefaults')(newFullData, newFullLayout);
  51683. // turn on flag to optimize large splom-only graphs
  51684. // mostly by omitting SVG layers during Cartesian.drawFramework
  51685. newFullLayout._hasOnlyLargeSploms = (
  51686. newFullLayout._basePlotModules.length === 1 &&
  51687. newFullLayout._basePlotModules[0].name === 'splom' &&
  51688. splomXa.length > 15 &&
  51689. splomYa.length > 15 &&
  51690. newFullLayout.shapes.length === 0 &&
  51691. newFullLayout.images.length === 0
  51692. );
  51693. // TODO remove in v2.0.0
  51694. // add has-plot-type refs to fullLayout for backward compatibility
  51695. newFullLayout._hasCartesian = newFullLayout._has('cartesian');
  51696. newFullLayout._hasGeo = newFullLayout._has('geo');
  51697. newFullLayout._hasGL3D = newFullLayout._has('gl3d');
  51698. newFullLayout._hasGL2D = newFullLayout._has('gl2d');
  51699. newFullLayout._hasTernary = newFullLayout._has('ternary');
  51700. newFullLayout._hasPie = newFullLayout._has('pie');
  51701. // relink / initialize subplot axis objects
  51702. plots.linkSubplots(newFullData, newFullLayout, oldFullData, oldFullLayout);
  51703. // clean subplots and other artifacts from previous plot calls
  51704. plots.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout);
  51705. // relink functions and _ attributes to promote consistency between plots
  51706. relinkPrivateKeys(newFullLayout, oldFullLayout);
  51707. // For persisting GUI-driven changes in layout
  51708. // _preGUI and _tracePreGUI were already copied over in relinkPrivateKeys
  51709. if(!newFullLayout._preGUI) newFullLayout._preGUI = {};
  51710. // track trace GUI changes by uid rather than by trace index
  51711. if(!newFullLayout._tracePreGUI) newFullLayout._tracePreGUI = {};
  51712. var tracePreGUI = newFullLayout._tracePreGUI;
  51713. var uids = {};
  51714. var uid;
  51715. for(uid in tracePreGUI) uids[uid] = 'old';
  51716. for(i = 0; i < newFullData.length; i++) {
  51717. uid = newFullData[i]._fullInput.uid;
  51718. if(!uids[uid]) tracePreGUI[uid] = {};
  51719. uids[uid] = 'new';
  51720. }
  51721. for(uid in uids) {
  51722. if(uids[uid] === 'old') delete tracePreGUI[uid];
  51723. }
  51724. // set up containers for margin calculations
  51725. initMargins(newFullLayout);
  51726. // collect and do some initial calculations for rangesliders
  51727. Registry.getComponentMethod('rangeslider', 'makeData')(newFullLayout);
  51728. // update object references in calcdata
  51729. if(!skipUpdateCalc && oldCalcdata.length === newFullData.length) {
  51730. plots.supplyDefaultsUpdateCalc(oldCalcdata, newFullData);
  51731. }
  51732. };
  51733. plots.supplyDefaultsUpdateCalc = function(oldCalcdata, newFullData) {
  51734. for(var i = 0; i < newFullData.length; i++) {
  51735. var newTrace = newFullData[i];
  51736. var cd0 = (oldCalcdata[i] || [])[0];
  51737. if(cd0 && cd0.trace) {
  51738. var oldTrace = cd0.trace;
  51739. if(oldTrace._hasCalcTransform) {
  51740. var arrayAttrs = oldTrace._arrayAttrs;
  51741. var j, astr, oldArrayVal;
  51742. for(j = 0; j < arrayAttrs.length; j++) {
  51743. astr = arrayAttrs[j];
  51744. oldArrayVal = Lib.nestedProperty(oldTrace, astr).get().slice();
  51745. Lib.nestedProperty(newTrace, astr).set(oldArrayVal);
  51746. }
  51747. }
  51748. cd0.trace = newTrace;
  51749. }
  51750. }
  51751. };
  51752. /**
  51753. * Create a list of uid strings satisfying (in this order of importance):
  51754. * 1. all unique, all strings
  51755. * 2. matches input uids if provided
  51756. * 3. matches previous data uids
  51757. */
  51758. function getTraceUids(oldFullData, newData) {
  51759. var len = newData.length;
  51760. var oldFullInput = [];
  51761. var i, prevFullInput;
  51762. for(i = 0; i < oldFullData.length; i++) {
  51763. var thisFullInput = oldFullData[i]._fullInput;
  51764. if(thisFullInput !== prevFullInput) oldFullInput.push(thisFullInput);
  51765. prevFullInput = thisFullInput;
  51766. }
  51767. var oldLen = oldFullInput.length;
  51768. var out = new Array(len);
  51769. var seenUids = {};
  51770. function setUid(uid, i) {
  51771. out[i] = uid;
  51772. seenUids[uid] = 1;
  51773. }
  51774. function tryUid(uid, i) {
  51775. if(uid && typeof uid === 'string' && !seenUids[uid]) {
  51776. setUid(uid, i);
  51777. return true;
  51778. }
  51779. }
  51780. for(i = 0; i < len; i++) {
  51781. var newUid = newData[i].uid;
  51782. if(typeof newUid === 'number') newUid = String(newUid);
  51783. if(tryUid(newUid, i)) continue;
  51784. if(i < oldLen && tryUid(oldFullInput[i].uid, i)) continue;
  51785. setUid(Lib.randstr(seenUids), i);
  51786. }
  51787. return out;
  51788. }
  51789. /**
  51790. * Make a container for collecting subplots we need to display.
  51791. *
  51792. * Finds all subplot types we need to enumerate once and caches it,
  51793. * but makes a new output object each time.
  51794. * Single-trace subplots (which have no `id`) such as pie, table, etc
  51795. * do not need to be collected because we just draw all visible traces.
  51796. */
  51797. function emptySubplotLists() {
  51798. var collectableSubplotTypes = Registry.collectableSubplotTypes;
  51799. var out = {};
  51800. var i, j;
  51801. if(!collectableSubplotTypes) {
  51802. collectableSubplotTypes = [];
  51803. var subplotsRegistry = Registry.subplotsRegistry;
  51804. for(var subplotType in subplotsRegistry) {
  51805. var subplotModule = subplotsRegistry[subplotType];
  51806. var subplotAttr = subplotModule.attr;
  51807. if(subplotAttr) {
  51808. collectableSubplotTypes.push(subplotType);
  51809. // special case, currently just for cartesian:
  51810. // we need to enumerate axes, not just subplots
  51811. if(Array.isArray(subplotAttr)) {
  51812. for(j = 0; j < subplotAttr.length; j++) {
  51813. Lib.pushUnique(collectableSubplotTypes, subplotAttr[j]);
  51814. }
  51815. }
  51816. }
  51817. }
  51818. }
  51819. for(i = 0; i < collectableSubplotTypes.length; i++) {
  51820. out[collectableSubplotTypes[i]] = [];
  51821. }
  51822. return out;
  51823. }
  51824. /**
  51825. * getFormatObj: use _context to get the format object from locale.
  51826. * Used to get d3.locale argument object and extraFormat argument object
  51827. *
  51828. * Regarding d3.locale argument :
  51829. * decimal and thousands can be overridden later by layout.separators
  51830. * grouping and currency are not presently used by our automatic number
  51831. * formatting system but can be used by custom formats.
  51832. *
  51833. * @returns {object} d3.locale format object
  51834. */
  51835. function getFormatObj(gd, formatKeys) {
  51836. var locale = gd._context.locale;
  51837. if(!locale) locale === 'en-US';
  51838. var formatDone = false;
  51839. var formatObj = {};
  51840. function includeFormat(newFormat) {
  51841. var formatFinished = true;
  51842. for(var i = 0; i < formatKeys.length; i++) {
  51843. var formatKey = formatKeys[i];
  51844. if(!formatObj[formatKey]) {
  51845. if(newFormat[formatKey]) {
  51846. formatObj[formatKey] = newFormat[formatKey];
  51847. }
  51848. else formatFinished = false;
  51849. }
  51850. }
  51851. if(formatFinished) formatDone = true;
  51852. }
  51853. // same as localize, look for format parts in each format spec in the chain
  51854. for(var i = 0; i < 2; i++) {
  51855. var locales = gd._context.locales;
  51856. for(var j = 0; j < 2; j++) {
  51857. var formatj = (locales[locale] || {}).format;
  51858. if(formatj) {
  51859. includeFormat(formatj);
  51860. if(formatDone) break;
  51861. }
  51862. locales = Registry.localeRegistry;
  51863. }
  51864. var baseLocale = locale.split('-')[0];
  51865. if(formatDone || baseLocale === locale) break;
  51866. locale = baseLocale;
  51867. }
  51868. // lastly pick out defaults from english (non-US, as DMY is so much more common)
  51869. if(!formatDone) includeFormat(Registry.localeRegistry.en.format);
  51870. return formatObj;
  51871. }
  51872. /**
  51873. * getFormatter: combine the final separators with the locale formatting object
  51874. * we pulled earlier to generate number and time formatters
  51875. * TODO: remove separators in v2, only use locale, so we don't need this step?
  51876. *
  51877. * @param {object} formatObj: d3.locale format object
  51878. * @param {string} separators: length-2 string to override decimal and thousands
  51879. * separators in number formatting
  51880. *
  51881. * @returns {object} {numberFormat, timeFormat} d3 formatter factory functions
  51882. * for numbers and time
  51883. */
  51884. function getFormatter(formatObj, separators) {
  51885. formatObj.decimal = separators.charAt(0);
  51886. formatObj.thousands = separators.charAt(1);
  51887. return d3.locale(formatObj);
  51888. }
  51889. // Create storage for all of the data related to frames and transitions:
  51890. plots.createTransitionData = function(gd) {
  51891. // Set up the default keyframe if it doesn't exist:
  51892. if(!gd._transitionData) {
  51893. gd._transitionData = {};
  51894. }
  51895. if(!gd._transitionData._frames) {
  51896. gd._transitionData._frames = [];
  51897. }
  51898. if(!gd._transitionData._frameHash) {
  51899. gd._transitionData._frameHash = {};
  51900. }
  51901. if(!gd._transitionData._counter) {
  51902. gd._transitionData._counter = 0;
  51903. }
  51904. if(!gd._transitionData._interruptCallbacks) {
  51905. gd._transitionData._interruptCallbacks = [];
  51906. }
  51907. };
  51908. // helper function to be bound to fullLayout to check
  51909. // whether a certain plot type is present on plot
  51910. // or trace has a category
  51911. plots._hasPlotType = function(category) {
  51912. var i;
  51913. // check base plot modules
  51914. var basePlotModules = this._basePlotModules || [];
  51915. for(i = 0; i < basePlotModules.length; i++) {
  51916. if(basePlotModules[i].name === category) return true;
  51917. }
  51918. // check trace modules (including non-visible:true)
  51919. var modules = this._modules || [];
  51920. for(i = 0; i < modules.length; i++) {
  51921. var name = modules[i].name;
  51922. if(name === category) return true;
  51923. // N.B. this is modules[i] along with 'categories' as a hash object
  51924. var _module = Registry.modules[name];
  51925. if(_module && _module.categories[category]) return true;
  51926. }
  51927. return false;
  51928. };
  51929. plots.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
  51930. var i, j;
  51931. var basePlotModules = oldFullLayout._basePlotModules || [];
  51932. for(i = 0; i < basePlotModules.length; i++) {
  51933. var _module = basePlotModules[i];
  51934. if(_module.clean) {
  51935. _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout);
  51936. }
  51937. }
  51938. var hadGl = oldFullLayout._has && oldFullLayout._has('gl');
  51939. var hasGl = newFullLayout._has && newFullLayout._has('gl');
  51940. if(hadGl && !hasGl) {
  51941. if(oldFullLayout._glcontainer !== undefined) {
  51942. oldFullLayout._glcontainer.selectAll('.gl-canvas').remove();
  51943. oldFullLayout._glcontainer.selectAll('.no-webgl').remove();
  51944. oldFullLayout._glcanvas = null;
  51945. }
  51946. }
  51947. var hasInfoLayer = !!oldFullLayout._infolayer;
  51948. oldLoop:
  51949. for(i = 0; i < oldFullData.length; i++) {
  51950. var oldTrace = oldFullData[i];
  51951. var oldUid = oldTrace.uid;
  51952. for(j = 0; j < newFullData.length; j++) {
  51953. var newTrace = newFullData[j];
  51954. if(oldUid === newTrace.uid) continue oldLoop;
  51955. }
  51956. // clean old colorbars
  51957. if(hasInfoLayer) {
  51958. oldFullLayout._infolayer.select('.cb' + oldUid).remove();
  51959. }
  51960. }
  51961. if(oldFullLayout._zoomlayer) {
  51962. oldFullLayout._zoomlayer.selectAll('.select-outline').remove();
  51963. }
  51964. };
  51965. plots.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
  51966. var i, j;
  51967. var oldSubplots = oldFullLayout._plots || {};
  51968. var newSubplots = newFullLayout._plots = {};
  51969. var newSubplotList = newFullLayout._subplots;
  51970. var mockGd = {
  51971. _fullData: newFullData,
  51972. _fullLayout: newFullLayout
  51973. };
  51974. var ids = newSubplotList.cartesian.concat(newSubplotList.gl2d || []);
  51975. for(i = 0; i < ids.length; i++) {
  51976. var id = ids[i];
  51977. var oldSubplot = oldSubplots[id];
  51978. var xaxis = axisIDs.getFromId(mockGd, id, 'x');
  51979. var yaxis = axisIDs.getFromId(mockGd, id, 'y');
  51980. var plotinfo;
  51981. // link or create subplot object
  51982. if(oldSubplot) {
  51983. plotinfo = newSubplots[id] = oldSubplot;
  51984. } else {
  51985. plotinfo = newSubplots[id] = {};
  51986. plotinfo.id = id;
  51987. }
  51988. // add these axis ids to each others' subplot lists
  51989. xaxis._counterAxes.push(yaxis._id);
  51990. yaxis._counterAxes.push(xaxis._id);
  51991. xaxis._subplotsWith.push(id);
  51992. yaxis._subplotsWith.push(id);
  51993. // update x and y axis layout object refs
  51994. plotinfo.xaxis = xaxis;
  51995. plotinfo.yaxis = yaxis;
  51996. // By default, we clip at the subplot level,
  51997. // but if one trace on a given subplot has *cliponaxis* set to false,
  51998. // we need to clip at the trace module layer level;
  51999. // find this out here, once of for all.
  52000. plotinfo._hasClipOnAxisFalse = false;
  52001. for(j = 0; j < newFullData.length; j++) {
  52002. var trace = newFullData[j];
  52003. if(
  52004. trace.xaxis === plotinfo.xaxis._id &&
  52005. trace.yaxis === plotinfo.yaxis._id &&
  52006. trace.cliponaxis === false
  52007. ) {
  52008. plotinfo._hasClipOnAxisFalse = true;
  52009. break;
  52010. }
  52011. }
  52012. }
  52013. // while we're at it, link overlaying axes to their main axes and
  52014. // anchored axes to the axes they're anchored to
  52015. var axList = axisIDs.list(mockGd, null, true);
  52016. var ax;
  52017. for(i = 0; i < axList.length; i++) {
  52018. ax = axList[i];
  52019. var mainAx = null;
  52020. if(ax.overlaying) {
  52021. mainAx = axisIDs.getFromId(mockGd, ax.overlaying);
  52022. // you cannot overlay an axis that's already overlaying another
  52023. if(mainAx && mainAx.overlaying) {
  52024. ax.overlaying = false;
  52025. mainAx = null;
  52026. }
  52027. }
  52028. ax._mainAxis = mainAx || ax;
  52029. /*
  52030. * For now force overlays to overlay completely... so they
  52031. * can drag together correctly and share backgrounds.
  52032. * Later perhaps we make separate axis domain and
  52033. * tick/line domain or something, so they can still share
  52034. * the (possibly larger) dragger and background but don't
  52035. * have to both be drawn over that whole domain
  52036. */
  52037. if(mainAx) ax.domain = mainAx.domain.slice();
  52038. ax._anchorAxis = ax.anchor === 'free' ?
  52039. null :
  52040. axisIDs.getFromId(mockGd, ax.anchor);
  52041. }
  52042. // finally, we can find the main subplot for each axis
  52043. // (on which the ticks & labels are drawn)
  52044. for(i = 0; i < axList.length; i++) {
  52045. ax = axList[i];
  52046. ax._counterAxes.sort(axisIDs.idSort);
  52047. ax._subplotsWith.sort(Lib.subplotSort);
  52048. ax._mainSubplot = findMainSubplot(ax, newFullLayout);
  52049. }
  52050. };
  52051. function findMainSubplot(ax, fullLayout) {
  52052. var mockGd = {_fullLayout: fullLayout};
  52053. var isX = ax._id.charAt(0) === 'x';
  52054. var anchorAx = ax._mainAxis._anchorAxis;
  52055. var mainSubplotID = '';
  52056. var nextBestMainSubplotID = '';
  52057. var anchorID = '';
  52058. // First try the main ID with the anchor
  52059. if(anchorAx) {
  52060. anchorID = anchorAx._mainAxis._id;
  52061. mainSubplotID = isX ? (ax._id + anchorID) : (anchorID + ax._id);
  52062. }
  52063. // Then look for a subplot with the counteraxis overlaying the anchor
  52064. // If that fails just use the first subplot including this axis
  52065. if(!mainSubplotID || !fullLayout._plots[mainSubplotID]) {
  52066. mainSubplotID = '';
  52067. var counterIDs = ax._counterAxes;
  52068. for(var j = 0; j < counterIDs.length; j++) {
  52069. var counterPart = counterIDs[j];
  52070. var id = isX ? (ax._id + counterPart) : (counterPart + ax._id);
  52071. if(!nextBestMainSubplotID) nextBestMainSubplotID = id;
  52072. var counterAx = axisIDs.getFromId(mockGd, counterPart);
  52073. if(anchorID && counterAx.overlaying === anchorID) {
  52074. mainSubplotID = id;
  52075. break;
  52076. }
  52077. }
  52078. }
  52079. return mainSubplotID || nextBestMainSubplotID;
  52080. }
  52081. // This function clears any trace attributes with valType: color and
  52082. // no set dflt filed in the plot schema. This is needed because groupby (which
  52083. // is the only transform for which this currently applies) supplies parent
  52084. // trace defaults, then expanded trace defaults. The result is that `null`
  52085. // colors are default-supplied and inherited as a color instead of a null.
  52086. // The result is that expanded trace default colors have no effect, with
  52087. // the final result that groups are indistinguishable. This function clears
  52088. // those colors so that individual groupby groups get unique colors.
  52089. plots.clearExpandedTraceDefaultColors = function(trace) {
  52090. var colorAttrs, path, i;
  52091. // This uses weird closure state in order to satisfy the linter rule
  52092. // that we can't create functions in a loop.
  52093. function locateColorAttrs(attr, attrName, attrs, level) {
  52094. path[level] = attrName;
  52095. path.length = level + 1;
  52096. if(attr.valType === 'color' && attr.dflt === undefined) {
  52097. colorAttrs.push(path.join('.'));
  52098. }
  52099. }
  52100. path = [];
  52101. // Get the cached colorAttrs:
  52102. colorAttrs = trace._module._colorAttrs;
  52103. // Or else compute and cache the colorAttrs on the module:
  52104. if(!colorAttrs) {
  52105. trace._module._colorAttrs = colorAttrs = [];
  52106. PlotSchema.crawl(
  52107. trace._module.attributes,
  52108. locateColorAttrs
  52109. );
  52110. }
  52111. for(i = 0; i < colorAttrs.length; i++) {
  52112. var origprop = Lib.nestedProperty(trace, '_input.' + colorAttrs[i]);
  52113. if(!origprop.get()) {
  52114. Lib.nestedProperty(trace, colorAttrs[i]).set(null);
  52115. }
  52116. }
  52117. };
  52118. plots.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) {
  52119. var modules = fullLayout._modules;
  52120. var visibleModules = fullLayout._visibleModules;
  52121. var basePlotModules = fullLayout._basePlotModules;
  52122. var cnt = 0;
  52123. var colorCnt = 0;
  52124. var i, fullTrace, trace;
  52125. fullLayout._transformModules = [];
  52126. function pushModule(fullTrace) {
  52127. dataOut.push(fullTrace);
  52128. var _module = fullTrace._module;
  52129. if(!_module) return;
  52130. Lib.pushUnique(modules, _module);
  52131. if(fullTrace.visible === true) Lib.pushUnique(visibleModules, _module);
  52132. Lib.pushUnique(basePlotModules, fullTrace._module.basePlotModule);
  52133. cnt++;
  52134. // TODO: do we really want color not to increment for explicitly invisible traces?
  52135. // This logic is weird, but matches previous behavior: traces that you explicitly
  52136. // set to visible:false do not increment the color, but traces WE determine to be
  52137. // empty or invalid (and thus set to visible:false) DO increment color.
  52138. // I kind of think we should just let all traces increment color, visible or not.
  52139. // see mock: axes-autotype-empty vs. a test of restyling visible: false that
  52140. // I can't find right now...
  52141. if(fullTrace._input.visible !== false) colorCnt++;
  52142. }
  52143. var carpetIndex = {};
  52144. var carpetDependents = [];
  52145. var dataTemplate = (layout.template || {}).data || {};
  52146. var templater = Template.traceTemplater(dataTemplate);
  52147. for(i = 0; i < dataIn.length; i++) {
  52148. trace = dataIn[i];
  52149. // reuse uid we may have pulled out of oldFullData
  52150. // Note: templater supplies trace type
  52151. fullTrace = templater.newTrace(trace);
  52152. fullTrace.uid = fullLayout._traceUids[i];
  52153. plots.supplyTraceDefaults(trace, fullTrace, colorCnt, fullLayout, i);
  52154. fullTrace.index = i;
  52155. fullTrace._input = trace;
  52156. fullTrace._expandedIndex = cnt;
  52157. if(fullTrace.transforms && fullTrace.transforms.length) {
  52158. var sdInvisible = trace.visible !== false && fullTrace.visible === false;
  52159. var expandedTraces = applyTransforms(fullTrace, dataOut, layout, fullLayout);
  52160. for(var j = 0; j < expandedTraces.length; j++) {
  52161. var expandedTrace = expandedTraces[j];
  52162. // No further templating during transforms.
  52163. var fullExpandedTrace = {
  52164. _template: fullTrace._template,
  52165. type: fullTrace.type,
  52166. // set uid using parent uid and expanded index
  52167. // to promote consistency between update calls
  52168. uid: fullTrace.uid + j
  52169. };
  52170. // If the first supplyDefaults created `visible: false`,
  52171. // clear it before running supplyDefaults a second time,
  52172. // because sometimes there are items we still want to coerce
  52173. // inside trace modules before determining that the trace is
  52174. // again `visible: false`, for example partial visibilities
  52175. // in `splom` traces.
  52176. if(sdInvisible && expandedTrace.visible === false) {
  52177. delete expandedTrace.visible;
  52178. }
  52179. plots.supplyTraceDefaults(expandedTrace, fullExpandedTrace, cnt, fullLayout, i);
  52180. // relink private (i.e. underscore) keys expanded trace to full expanded trace so
  52181. // that transform supply-default methods can set _ keys for future use.
  52182. relinkPrivateKeys(fullExpandedTrace, expandedTrace);
  52183. // add info about parent data trace
  52184. fullExpandedTrace.index = i;
  52185. fullExpandedTrace._input = trace;
  52186. fullExpandedTrace._fullInput = fullTrace;
  52187. // add info about the expanded data
  52188. fullExpandedTrace._expandedIndex = cnt;
  52189. fullExpandedTrace._expandedInput = expandedTrace;
  52190. pushModule(fullExpandedTrace);
  52191. }
  52192. }
  52193. else {
  52194. // add identify refs for consistency with transformed traces
  52195. fullTrace._fullInput = fullTrace;
  52196. fullTrace._expandedInput = fullTrace;
  52197. pushModule(fullTrace);
  52198. }
  52199. if(Registry.traceIs(fullTrace, 'carpetAxis')) {
  52200. carpetIndex[fullTrace.carpet] = fullTrace;
  52201. }
  52202. if(Registry.traceIs(fullTrace, 'carpetDependent')) {
  52203. carpetDependents.push(i);
  52204. }
  52205. }
  52206. for(i = 0; i < carpetDependents.length; i++) {
  52207. fullTrace = dataOut[carpetDependents[i]];
  52208. if(!fullTrace.visible) continue;
  52209. var carpetAxis = carpetIndex[fullTrace.carpet];
  52210. fullTrace._carpet = carpetAxis;
  52211. if(!carpetAxis || !carpetAxis.visible) {
  52212. fullTrace.visible = false;
  52213. continue;
  52214. }
  52215. fullTrace.xaxis = carpetAxis.xaxis;
  52216. fullTrace.yaxis = carpetAxis.yaxis;
  52217. }
  52218. };
  52219. plots.supplyAnimationDefaults = function(opts) {
  52220. opts = opts || {};
  52221. var i;
  52222. var optsOut = {};
  52223. function coerce(attr, dflt) {
  52224. return Lib.coerce(opts || {}, optsOut, animationAttrs, attr, dflt);
  52225. }
  52226. coerce('mode');
  52227. coerce('direction');
  52228. coerce('fromcurrent');
  52229. if(Array.isArray(opts.frame)) {
  52230. optsOut.frame = [];
  52231. for(i = 0; i < opts.frame.length; i++) {
  52232. optsOut.frame[i] = plots.supplyAnimationFrameDefaults(opts.frame[i] || {});
  52233. }
  52234. } else {
  52235. optsOut.frame = plots.supplyAnimationFrameDefaults(opts.frame || {});
  52236. }
  52237. if(Array.isArray(opts.transition)) {
  52238. optsOut.transition = [];
  52239. for(i = 0; i < opts.transition.length; i++) {
  52240. optsOut.transition[i] = plots.supplyAnimationTransitionDefaults(opts.transition[i] || {});
  52241. }
  52242. } else {
  52243. optsOut.transition = plots.supplyAnimationTransitionDefaults(opts.transition || {});
  52244. }
  52245. return optsOut;
  52246. };
  52247. plots.supplyAnimationFrameDefaults = function(opts) {
  52248. var optsOut = {};
  52249. function coerce(attr, dflt) {
  52250. return Lib.coerce(opts || {}, optsOut, animationAttrs.frame, attr, dflt);
  52251. }
  52252. coerce('duration');
  52253. coerce('redraw');
  52254. return optsOut;
  52255. };
  52256. plots.supplyAnimationTransitionDefaults = function(opts) {
  52257. var optsOut = {};
  52258. function coerce(attr, dflt) {
  52259. return Lib.coerce(opts || {}, optsOut, animationAttrs.transition, attr, dflt);
  52260. }
  52261. coerce('duration');
  52262. coerce('easing');
  52263. return optsOut;
  52264. };
  52265. plots.supplyFrameDefaults = function(frameIn) {
  52266. var frameOut = {};
  52267. function coerce(attr, dflt) {
  52268. return Lib.coerce(frameIn, frameOut, frameAttrs, attr, dflt);
  52269. }
  52270. coerce('group');
  52271. coerce('name');
  52272. coerce('traces');
  52273. coerce('baseframe');
  52274. coerce('data');
  52275. coerce('layout');
  52276. return frameOut;
  52277. };
  52278. plots.supplyTraceDefaults = function(traceIn, traceOut, colorIndex, layout, traceInIndex) {
  52279. var colorway = layout.colorway || Color.defaults;
  52280. var defaultColor = colorway[colorIndex % colorway.length];
  52281. var i;
  52282. function coerce(attr, dflt) {
  52283. return Lib.coerce(traceIn, traceOut, plots.attributes, attr, dflt);
  52284. }
  52285. var visible = coerce('visible');
  52286. coerce('type');
  52287. coerce('name', layout._traceWord + ' ' + traceInIndex);
  52288. coerce('uirevision', layout.uirevision);
  52289. // we want even invisible traces to make their would-be subplots visible
  52290. // so coerce the subplot id(s) now no matter what
  52291. var _module = plots.getModule(traceOut);
  52292. traceOut._module = _module;
  52293. if(_module) {
  52294. var basePlotModule = _module.basePlotModule;
  52295. var subplotAttr = basePlotModule.attr;
  52296. var subplotAttrs = basePlotModule.attributes;
  52297. if(subplotAttr && subplotAttrs) {
  52298. var subplots = layout._subplots;
  52299. var subplotId = '';
  52300. // TODO - currently if we draw an empty gl2d subplot, it draws
  52301. // nothing then gets stuck and you can't get it back without newPlot
  52302. // sort this out in the regl refactor? but for now just drop empty gl2d subplots
  52303. if(basePlotModule.name !== 'gl2d' || visible) {
  52304. if(Array.isArray(subplotAttr)) {
  52305. for(i = 0; i < subplotAttr.length; i++) {
  52306. var attri = subplotAttr[i];
  52307. var vali = Lib.coerce(traceIn, traceOut, subplotAttrs, attri);
  52308. if(subplots[attri]) Lib.pushUnique(subplots[attri], vali);
  52309. subplotId += vali;
  52310. }
  52311. }
  52312. else {
  52313. subplotId = Lib.coerce(traceIn, traceOut, subplotAttrs, subplotAttr);
  52314. }
  52315. if(subplots[basePlotModule.name]) {
  52316. Lib.pushUnique(subplots[basePlotModule.name], subplotId);
  52317. }
  52318. }
  52319. }
  52320. }
  52321. function coerceUnlessPruned(attr, dflt, cb) {
  52322. if(_module && (attr in _module.attributes) && _module.attributes[attr] === undefined) {
  52323. // Pruned
  52324. } else {
  52325. if(cb && typeof cb === 'function') {
  52326. cb();
  52327. } else {
  52328. coerce(attr, dflt);
  52329. }
  52330. }
  52331. }
  52332. if(visible) {
  52333. coerce('customdata');
  52334. coerce('ids');
  52335. if(Registry.traceIs(traceOut, 'showLegend')) {
  52336. traceOut._dfltShowLegend = true;
  52337. coerce('showlegend');
  52338. coerce('legendgroup');
  52339. }
  52340. else {
  52341. traceOut._dfltShowLegend = false;
  52342. }
  52343. coerceUnlessPruned('hoverlabel', '', function() {
  52344. Registry.getComponentMethod(
  52345. 'fx',
  52346. 'supplyDefaults'
  52347. )(traceIn, traceOut, defaultColor, layout);
  52348. });
  52349. // TODO add per-base-plot-module trace defaults step
  52350. if(_module) {
  52351. _module.supplyDefaults(traceIn, traceOut, defaultColor, layout);
  52352. if(!traceOut.hovertemplate) Lib.coerceHoverinfo(traceIn, traceOut, layout);
  52353. }
  52354. if(!Registry.traceIs(traceOut, 'noOpacity')) coerce('opacity');
  52355. if(Registry.traceIs(traceOut, 'notLegendIsolatable')) {
  52356. // This clears out the legendonly state for traces like carpet that
  52357. // cannot be isolated in the legend
  52358. traceOut.visible = !!traceOut.visible;
  52359. }
  52360. if(_module && _module.selectPoints) {
  52361. coerce('selectedpoints');
  52362. }
  52363. plots.supplyTransformDefaults(traceIn, traceOut, layout);
  52364. }
  52365. return traceOut;
  52366. };
  52367. /**
  52368. * hasMakesDataTransform: does this trace have a transform that makes its own
  52369. * data, either by grabbing it from somewhere else or by creating it from input
  52370. * parameters? If so, we should still keep going with supplyDefaults
  52371. * even if the trace is invisible, which may just be because it has no data yet.
  52372. */
  52373. function hasMakesDataTransform(trace) {
  52374. var transforms = trace.transforms;
  52375. if(Array.isArray(transforms) && transforms.length) {
  52376. for(var i = 0; i < transforms.length; i++) {
  52377. var ti = transforms[i];
  52378. var _module = ti._module || transformsRegistry[ti.type];
  52379. if(_module && _module.makesData) return true;
  52380. }
  52381. }
  52382. return false;
  52383. }
  52384. plots.hasMakesDataTransform = hasMakesDataTransform;
  52385. plots.supplyTransformDefaults = function(traceIn, traceOut, layout) {
  52386. // For now we only allow transforms on 1D traces, ie those that specify a _length.
  52387. // If we were to implement 2D transforms, we'd need to have each transform
  52388. // describe its own applicability and disable itself when it doesn't apply.
  52389. // Also allow transforms that make their own data, but not in globalTransforms
  52390. if(!(traceOut._length || hasMakesDataTransform(traceIn))) return;
  52391. var globalTransforms = layout._globalTransforms || [];
  52392. var transformModules = layout._transformModules || [];
  52393. if(!Array.isArray(traceIn.transforms) && globalTransforms.length === 0) return;
  52394. var containerIn = traceIn.transforms || [];
  52395. var transformList = globalTransforms.concat(containerIn);
  52396. var containerOut = traceOut.transforms = [];
  52397. for(var i = 0; i < transformList.length; i++) {
  52398. var transformIn = transformList[i];
  52399. var type = transformIn.type;
  52400. var _module = transformsRegistry[type];
  52401. var transformOut;
  52402. /*
  52403. * Supply defaults may run twice. First pass runs all supply defaults steps
  52404. * and adds the _module to any output transforms.
  52405. * If transforms exist another pass is run so that any generated traces also
  52406. * go through supply defaults. This has the effect of rerunning
  52407. * supplyTransformDefaults. If the transform does not have a `transform`
  52408. * function it could not have generated any new traces and the second stage
  52409. * is unnecessary. We detect this case with the following variables.
  52410. */
  52411. var isFirstStage = !(transformIn._module && transformIn._module === _module);
  52412. var doLaterStages = _module && typeof _module.transform === 'function';
  52413. if(!_module) Lib.warn('Unrecognized transform type ' + type + '.');
  52414. if(_module && _module.supplyDefaults && (isFirstStage || doLaterStages)) {
  52415. transformOut = _module.supplyDefaults(transformIn, traceOut, layout, traceIn);
  52416. transformOut.type = type;
  52417. transformOut._module = _module;
  52418. Lib.pushUnique(transformModules, _module);
  52419. }
  52420. else {
  52421. transformOut = Lib.extendFlat({}, transformIn);
  52422. }
  52423. containerOut.push(transformOut);
  52424. }
  52425. };
  52426. function applyTransforms(fullTrace, fullData, layout, fullLayout) {
  52427. var container = fullTrace.transforms;
  52428. var dataOut = [fullTrace];
  52429. for(var i = 0; i < container.length; i++) {
  52430. var transform = container[i];
  52431. var _module = transformsRegistry[transform.type];
  52432. if(_module && _module.transform) {
  52433. dataOut = _module.transform(dataOut, {
  52434. transform: transform,
  52435. fullTrace: fullTrace,
  52436. fullData: fullData,
  52437. layout: layout,
  52438. fullLayout: fullLayout,
  52439. transformIndex: i
  52440. });
  52441. }
  52442. }
  52443. return dataOut;
  52444. }
  52445. plots.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) {
  52446. function coerce(attr, dflt) {
  52447. return Lib.coerce(layoutIn, layoutOut, plots.layoutAttributes, attr, dflt);
  52448. }
  52449. var template = layoutIn.template;
  52450. if(Lib.isPlainObject(template)) {
  52451. layoutOut.template = template;
  52452. layoutOut._template = template.layout;
  52453. layoutOut._dataTemplate = template.data;
  52454. }
  52455. var globalFont = Lib.coerceFont(coerce, 'font');
  52456. coerce('title.text', layoutOut._dfltTitle.plot);
  52457. Lib.coerceFont(coerce, 'title.font', {
  52458. family: globalFont.family,
  52459. size: Math.round(globalFont.size * 1.4),
  52460. color: globalFont.color
  52461. });
  52462. coerce('title.xref');
  52463. coerce('title.yref');
  52464. coerce('title.x');
  52465. coerce('title.y');
  52466. coerce('title.xanchor');
  52467. coerce('title.yanchor');
  52468. coerce('title.pad.t');
  52469. coerce('title.pad.r');
  52470. coerce('title.pad.b');
  52471. coerce('title.pad.l');
  52472. // Make sure that autosize is defaulted to *true*
  52473. // on layouts with no set width and height for backward compatibly,
  52474. // in particular https://plot.ly/javascript/responsive-fluid-layout/
  52475. //
  52476. // Before https://github.com/plotly/plotly.js/pull/635 ,
  52477. // layouts with no set width and height were set temporary set to 'initial'
  52478. // to pass through the autosize routine
  52479. //
  52480. // This behavior is subject to change in v2.
  52481. coerce('autosize', !(layoutIn.width && layoutIn.height));
  52482. coerce('width');
  52483. coerce('height');
  52484. coerce('margin.l');
  52485. coerce('margin.r');
  52486. coerce('margin.t');
  52487. coerce('margin.b');
  52488. coerce('margin.pad');
  52489. coerce('margin.autoexpand');
  52490. if(layoutIn.width && layoutIn.height) plots.sanitizeMargins(layoutOut);
  52491. Registry.getComponentMethod('grid', 'sizeDefaults')(layoutIn, layoutOut);
  52492. coerce('paper_bgcolor');
  52493. coerce('separators', formatObj.decimal + formatObj.thousands);
  52494. coerce('hidesources');
  52495. coerce('colorway');
  52496. coerce('datarevision');
  52497. var uirevision = coerce('uirevision');
  52498. coerce('editrevision', uirevision);
  52499. coerce('selectionrevision', uirevision);
  52500. coerce('modebar.orientation');
  52501. coerce('modebar.bgcolor', Color.addOpacity(layoutOut.paper_bgcolor, 0.5));
  52502. var modebarDefaultColor = Color.contrast(Color.rgb(layoutOut.modebar.bgcolor));
  52503. coerce('modebar.color', Color.addOpacity(modebarDefaultColor, 0.3));
  52504. coerce('modebar.activecolor', Color.addOpacity(modebarDefaultColor, 0.7));
  52505. coerce('modebar.uirevision', uirevision);
  52506. coerce('meta');
  52507. // do not include defaults in fullLayout when users do not set transition
  52508. if(Lib.isPlainObject(layoutIn.transition)) {
  52509. coerce('transition.duration');
  52510. coerce('transition.easing');
  52511. coerce('transition.ordering');
  52512. }
  52513. Registry.getComponentMethod(
  52514. 'calendars',
  52515. 'handleDefaults'
  52516. )(layoutIn, layoutOut, 'calendar');
  52517. Registry.getComponentMethod(
  52518. 'fx',
  52519. 'supplyLayoutGlobalDefaults'
  52520. )(layoutIn, layoutOut, coerce);
  52521. };
  52522. plots.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) {
  52523. var context = gd._context || {};
  52524. var frameMargins = context.frameMargins;
  52525. var newWidth;
  52526. var newHeight;
  52527. var isPlotDiv = Lib.isPlotDiv(gd);
  52528. if(isPlotDiv) gd.emit('plotly_autosize');
  52529. // embedded in an iframe - just take the full iframe size
  52530. // if we get to this point, with no aspect ratio restrictions
  52531. if(context.fillFrame) {
  52532. newWidth = window.innerWidth;
  52533. newHeight = window.innerHeight;
  52534. // somehow we get a few extra px height sometimes...
  52535. // just hide it
  52536. document.body.style.overflow = 'hidden';
  52537. }
  52538. else {
  52539. // plotly.js - let the developers do what they want, either
  52540. // provide height and width for the container div,
  52541. // specify size in layout, or take the defaults,
  52542. // but don't enforce any ratio restrictions
  52543. var computedStyle = isPlotDiv ? window.getComputedStyle(gd) : {};
  52544. newWidth = parseFloat(computedStyle.width) || parseFloat(computedStyle.maxWidth) || fullLayout.width;
  52545. newHeight = parseFloat(computedStyle.height) || parseFloat(computedStyle.maxHeight) || fullLayout.height;
  52546. if(isNumeric(frameMargins) && frameMargins > 0) {
  52547. var factor = 1 - 2 * frameMargins;
  52548. newWidth = Math.round(factor * newWidth);
  52549. newHeight = Math.round(factor * newHeight);
  52550. }
  52551. }
  52552. var minWidth = plots.layoutAttributes.width.min;
  52553. var minHeight = plots.layoutAttributes.height.min;
  52554. if(newWidth < minWidth) newWidth = minWidth;
  52555. if(newHeight < minHeight) newHeight = minHeight;
  52556. var widthHasChanged = !layout.width &&
  52557. (Math.abs(fullLayout.width - newWidth) > 1);
  52558. var heightHasChanged = !layout.height &&
  52559. (Math.abs(fullLayout.height - newHeight) > 1);
  52560. if(heightHasChanged || widthHasChanged) {
  52561. if(widthHasChanged) fullLayout.width = newWidth;
  52562. if(heightHasChanged) fullLayout.height = newHeight;
  52563. }
  52564. // cache initial autosize value, used in relayout when
  52565. // width or height values are set to null
  52566. if(!gd._initialAutoSize) {
  52567. gd._initialAutoSize = { width: newWidth, height: newHeight };
  52568. }
  52569. plots.sanitizeMargins(fullLayout);
  52570. };
  52571. plots.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, transitionData) {
  52572. var componentsRegistry = Registry.componentsRegistry;
  52573. var basePlotModules = layoutOut._basePlotModules;
  52574. var component, i, _module;
  52575. var Cartesian = Registry.subplotsRegistry.cartesian;
  52576. // check if any components need to add more base plot modules
  52577. // that weren't captured by traces
  52578. for(component in componentsRegistry) {
  52579. _module = componentsRegistry[component];
  52580. if(_module.includeBasePlot) {
  52581. _module.includeBasePlot(layoutIn, layoutOut);
  52582. }
  52583. }
  52584. // make sure we *at least* have some cartesian axes
  52585. if(!basePlotModules.length) {
  52586. basePlotModules.push(Cartesian);
  52587. }
  52588. // ensure all cartesian axes have at least one subplot
  52589. if(layoutOut._has('cartesian')) {
  52590. Registry.getComponentMethod('grid', 'contentDefaults')(layoutIn, layoutOut);
  52591. Cartesian.finalizeSubplots(layoutIn, layoutOut);
  52592. }
  52593. // sort subplot lists
  52594. for(var subplotType in layoutOut._subplots) {
  52595. layoutOut._subplots[subplotType].sort(Lib.subplotSort);
  52596. }
  52597. // base plot module layout defaults
  52598. for(i = 0; i < basePlotModules.length; i++) {
  52599. _module = basePlotModules[i];
  52600. // e.g. pie does not have a layout-defaults step
  52601. if(_module.supplyLayoutDefaults) {
  52602. _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
  52603. }
  52604. }
  52605. // trace module layout defaults
  52606. // use _modules rather than _visibleModules so that even
  52607. // legendonly traces can include settings - eg barmode, which affects
  52608. // legend.traceorder default value.
  52609. var modules = layoutOut._modules;
  52610. for(i = 0; i < modules.length; i++) {
  52611. _module = modules[i];
  52612. if(_module.supplyLayoutDefaults) {
  52613. _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
  52614. }
  52615. }
  52616. // transform module layout defaults
  52617. var transformModules = layoutOut._transformModules;
  52618. for(i = 0; i < transformModules.length; i++) {
  52619. _module = transformModules[i];
  52620. if(_module.supplyLayoutDefaults) {
  52621. _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData, transitionData);
  52622. }
  52623. }
  52624. for(component in componentsRegistry) {
  52625. _module = componentsRegistry[component];
  52626. if(_module.supplyLayoutDefaults) {
  52627. _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData);
  52628. }
  52629. }
  52630. };
  52631. // Remove all plotly attributes from a div so it can be replotted fresh
  52632. // TODO: these really need to be encapsulated into a much smaller set...
  52633. plots.purge = function(gd) {
  52634. // note: we DO NOT remove _context because it doesn't change when we insert
  52635. // a new plot, and may have been set outside of our scope.
  52636. var fullLayout = gd._fullLayout || {};
  52637. if(fullLayout._glcontainer !== undefined) {
  52638. fullLayout._glcontainer.selectAll('.gl-canvas').remove();
  52639. fullLayout._glcontainer.remove();
  52640. fullLayout._glcanvas = null;
  52641. }
  52642. if(fullLayout._geocontainer !== undefined) fullLayout._geocontainer.remove();
  52643. // remove modebar
  52644. if(fullLayout._modeBar) fullLayout._modeBar.destroy();
  52645. if(gd._transitionData) {
  52646. // Ensure any dangling callbacks are simply dropped if the plot is purged.
  52647. // This is more or less only actually important for testing.
  52648. if(gd._transitionData._interruptCallbacks) {
  52649. gd._transitionData._interruptCallbacks.length = 0;
  52650. }
  52651. if(gd._transitionData._animationRaf) {
  52652. window.cancelAnimationFrame(gd._transitionData._animationRaf);
  52653. }
  52654. }
  52655. // remove any planned throttles
  52656. Lib.clearThrottle();
  52657. // remove responsive handler
  52658. Lib.clearResponsive(gd);
  52659. // data and layout
  52660. delete gd.data;
  52661. delete gd.layout;
  52662. delete gd._fullData;
  52663. delete gd._fullLayout;
  52664. delete gd.calcdata;
  52665. delete gd.framework;
  52666. delete gd.empty;
  52667. delete gd.fid;
  52668. delete gd.undoqueue; // action queue
  52669. delete gd.undonum;
  52670. delete gd.autoplay; // are we doing an action that doesn't go in undo queue?
  52671. delete gd.changed;
  52672. // these get recreated on Plotly.plot anyway, but just to be safe
  52673. // (and to have a record of them...)
  52674. delete gd._promises;
  52675. delete gd._redrawTimer;
  52676. delete gd._hmlumcount;
  52677. delete gd._hmpixcount;
  52678. delete gd._transitionData;
  52679. delete gd._transitioning;
  52680. delete gd._initialAutoSize;
  52681. delete gd._transitioningWithDuration;
  52682. // created during certain events, that *should* clean them up
  52683. // themselves, but may not if there was an error
  52684. delete gd._dragging;
  52685. delete gd._dragged;
  52686. delete gd._hoverdata;
  52687. delete gd._snapshotInProgress;
  52688. delete gd._editing;
  52689. delete gd._replotPending;
  52690. delete gd._mouseDownTime;
  52691. delete gd._legendMouseDownTime;
  52692. // remove all event listeners
  52693. if(gd.removeAllListeners) gd.removeAllListeners();
  52694. };
  52695. plots.style = function(gd) {
  52696. var _modules = gd._fullLayout._visibleModules;
  52697. var styleModules = [];
  52698. var i;
  52699. // some trace modules reuse the same style method,
  52700. // make sure to not unnecessary call them multiple times.
  52701. for(i = 0; i < _modules.length; i++) {
  52702. var _module = _modules[i];
  52703. if(_module.style) {
  52704. Lib.pushUnique(styleModules, _module.style);
  52705. }
  52706. }
  52707. for(i = 0; i < styleModules.length; i++) {
  52708. styleModules[i](gd);
  52709. }
  52710. };
  52711. plots.sanitizeMargins = function(fullLayout) {
  52712. // polar doesn't do margins...
  52713. if(!fullLayout || !fullLayout.margin) return;
  52714. var width = fullLayout.width;
  52715. var height = fullLayout.height;
  52716. var margin = fullLayout.margin;
  52717. var plotWidth = width - (margin.l + margin.r);
  52718. var plotHeight = height - (margin.t + margin.b);
  52719. var correction;
  52720. // if margin.l + margin.r = 0 then plotWidth > 0
  52721. // as width >= 10 by supplyDefaults
  52722. // similarly for margin.t + margin.b
  52723. if(plotWidth < 0) {
  52724. correction = (width - 1) / (margin.l + margin.r);
  52725. margin.l = Math.floor(correction * margin.l);
  52726. margin.r = Math.floor(correction * margin.r);
  52727. }
  52728. if(plotHeight < 0) {
  52729. correction = (height - 1) / (margin.t + margin.b);
  52730. margin.t = Math.floor(correction * margin.t);
  52731. margin.b = Math.floor(correction * margin.b);
  52732. }
  52733. };
  52734. plots.clearAutoMarginIds = function(gd) {
  52735. gd._fullLayout._pushmarginIds = {};
  52736. };
  52737. plots.allowAutoMargin = function(gd, id) {
  52738. gd._fullLayout._pushmarginIds[id] = 1;
  52739. };
  52740. function initMargins(fullLayout) {
  52741. var margin = fullLayout.margin;
  52742. if(!fullLayout._size) {
  52743. var gs = fullLayout._size = {
  52744. l: Math.round(margin.l),
  52745. r: Math.round(margin.r),
  52746. t: Math.round(margin.t),
  52747. b: Math.round(margin.b),
  52748. p: Math.round(margin.pad)
  52749. };
  52750. gs.w = Math.round(fullLayout.width) - gs.l - gs.r;
  52751. gs.h = Math.round(fullLayout.height) - gs.t - gs.b;
  52752. }
  52753. if(!fullLayout._pushmargin) fullLayout._pushmargin = {};
  52754. if(!fullLayout._pushmarginIds) fullLayout._pushmarginIds = {};
  52755. }
  52756. /**
  52757. * autoMargin: called by components that may need to expand the margins to
  52758. * be rendered on-plot.
  52759. *
  52760. * @param {DOM element} gd
  52761. * @param {string} id - an identifier unique (within this plot) to this object,
  52762. * so we can remove a previous margin expansion from the same object.
  52763. * @param {object} o - the margin requirements of this object, or omit to delete
  52764. * this entry (like if it's hidden). Keys are:
  52765. * x, y: plot fraction of the anchor point.
  52766. * xl, xr, yt, yb: if the object has an extent defined in plot fraction,
  52767. * you can specify both edges as plot fractions in each dimension
  52768. * l, r, t, b: the pixels to pad past the plot fraction x[l|r] and y[t|b]
  52769. * pad: extra pixels to add in all directions, default 12 (why?)
  52770. */
  52771. plots.autoMargin = function(gd, id, o) {
  52772. var fullLayout = gd._fullLayout;
  52773. var pushMargin = fullLayout._pushmargin;
  52774. var pushMarginIds = fullLayout._pushmarginIds;
  52775. if(fullLayout.margin.autoexpand !== false) {
  52776. if(!o) {
  52777. delete pushMargin[id];
  52778. delete pushMarginIds[id];
  52779. }
  52780. else {
  52781. var pad = o.pad;
  52782. if(pad === undefined) {
  52783. var margin = fullLayout.margin;
  52784. // if no explicit pad is given, use 12px unless there's a
  52785. // specified margin that's smaller than that
  52786. pad = Math.min(12, margin.l, margin.r, margin.t, margin.b);
  52787. }
  52788. // if the item is too big, just give it enough automargin to
  52789. // make sure you can still grab it and bring it back
  52790. if(o.l + o.r > fullLayout.width * 0.5) o.l = o.r = 0;
  52791. if(o.b + o.t > fullLayout.height * 0.5) o.b = o.t = 0;
  52792. var xl = o.xl !== undefined ? o.xl : o.x;
  52793. var xr = o.xr !== undefined ? o.xr : o.x;
  52794. var yt = o.yt !== undefined ? o.yt : o.y;
  52795. var yb = o.yb !== undefined ? o.yb : o.y;
  52796. pushMargin[id] = {
  52797. l: {val: xl, size: o.l + pad},
  52798. r: {val: xr, size: o.r + pad},
  52799. b: {val: yb, size: o.b + pad},
  52800. t: {val: yt, size: o.t + pad}
  52801. };
  52802. pushMarginIds[id] = 1;
  52803. }
  52804. if(!fullLayout._replotting) plots.doAutoMargin(gd);
  52805. }
  52806. };
  52807. plots.doAutoMargin = function(gd) {
  52808. var fullLayout = gd._fullLayout;
  52809. if(!fullLayout._size) fullLayout._size = {};
  52810. initMargins(fullLayout);
  52811. var gs = fullLayout._size;
  52812. var oldmargins = JSON.stringify(gs);
  52813. var margin = fullLayout.margin;
  52814. // adjust margins for outside components
  52815. // fullLayout.margin is the requested margin,
  52816. // fullLayout._size has margins and plotsize after adjustment
  52817. var ml = margin.l;
  52818. var mr = margin.r;
  52819. var mt = margin.t;
  52820. var mb = margin.b;
  52821. var pushMargin = fullLayout._pushmargin;
  52822. var pushMarginIds = fullLayout._pushmarginIds;
  52823. if(fullLayout.margin.autoexpand !== false) {
  52824. for(var k in pushMargin) {
  52825. if(!pushMarginIds[k]) delete pushMargin[k];
  52826. }
  52827. // fill in the requested margins
  52828. pushMargin.base = {
  52829. l: {val: 0, size: ml},
  52830. r: {val: 1, size: mr},
  52831. t: {val: 1, size: mt},
  52832. b: {val: 0, size: mb}
  52833. };
  52834. // now cycle through all the combinations of l and r
  52835. // (and t and b) to find the required margins
  52836. for(var k1 in pushMargin) {
  52837. var pushleft = pushMargin[k1].l || {};
  52838. var pushbottom = pushMargin[k1].b || {};
  52839. var fl = pushleft.val;
  52840. var pl = pushleft.size;
  52841. var fb = pushbottom.val;
  52842. var pb = pushbottom.size;
  52843. for(var k2 in pushMargin) {
  52844. if(isNumeric(pl) && pushMargin[k2].r) {
  52845. var fr = pushMargin[k2].r.val;
  52846. var pr = pushMargin[k2].r.size;
  52847. if(fr > fl) {
  52848. var newl = (pl * fr +
  52849. (pr - fullLayout.width) * fl) / (fr - fl);
  52850. var newr = (pr * (1 - fl) +
  52851. (pl - fullLayout.width) * (1 - fr)) / (fr - fl);
  52852. if(newl >= 0 && newr >= 0 && newl + newr > ml + mr) {
  52853. ml = newl;
  52854. mr = newr;
  52855. }
  52856. }
  52857. }
  52858. if(isNumeric(pb) && pushMargin[k2].t) {
  52859. var ft = pushMargin[k2].t.val;
  52860. var pt = pushMargin[k2].t.size;
  52861. if(ft > fb) {
  52862. var newb = (pb * ft +
  52863. (pt - fullLayout.height) * fb) / (ft - fb);
  52864. var newt = (pt * (1 - fb) +
  52865. (pb - fullLayout.height) * (1 - ft)) / (ft - fb);
  52866. if(newb >= 0 && newt >= 0 && newb + newt > mb + mt) {
  52867. mb = newb;
  52868. mt = newt;
  52869. }
  52870. }
  52871. }
  52872. }
  52873. }
  52874. }
  52875. gs.l = Math.round(ml);
  52876. gs.r = Math.round(mr);
  52877. gs.t = Math.round(mt);
  52878. gs.b = Math.round(mb);
  52879. gs.p = Math.round(margin.pad);
  52880. gs.w = Math.round(fullLayout.width) - gs.l - gs.r;
  52881. gs.h = Math.round(fullLayout.height) - gs.t - gs.b;
  52882. // if things changed and we're not already redrawing, trigger a redraw
  52883. if(!fullLayout._replotting &&
  52884. oldmargins !== '{}' &&
  52885. oldmargins !== JSON.stringify(fullLayout._size)
  52886. ) {
  52887. if('_redrawFromAutoMarginCount' in fullLayout) {
  52888. fullLayout._redrawFromAutoMarginCount++;
  52889. } else {
  52890. fullLayout._redrawFromAutoMarginCount = 1;
  52891. }
  52892. return Registry.call('plot', gd);
  52893. }
  52894. };
  52895. /**
  52896. * JSONify the graph data and layout
  52897. *
  52898. * This function needs to recurse because some src can be inside
  52899. * sub-objects.
  52900. *
  52901. * It also strips out functions and private (starts with _) elements.
  52902. * Therefore, we can add temporary things to data and layout that don't
  52903. * get saved.
  52904. *
  52905. * @param gd The graphDiv
  52906. * @param {Boolean} dataonly If true, don't return layout.
  52907. * @param {'keepref'|'keepdata'|'keepall'} [mode='keepref'] Filter what's kept
  52908. * keepref: remove data for which there's a src present
  52909. * eg if there's xsrc present (and xsrc is well-formed,
  52910. * ie has : and some chars before it), strip out x
  52911. * keepdata: remove all src tags, don't remove the data itself
  52912. * keepall: keep data and src
  52913. * @param {String} output If you specify 'object', the result will not be stringified
  52914. * @param {Boolean} useDefaults If truthy, use _fullLayout and _fullData
  52915. * @returns {Object|String}
  52916. */
  52917. plots.graphJson = function(gd, dataonly, mode, output, useDefaults) {
  52918. // if the defaults aren't supplied yet, we need to do that...
  52919. if((useDefaults && dataonly && !gd._fullData) ||
  52920. (useDefaults && !dataonly && !gd._fullLayout)) {
  52921. plots.supplyDefaults(gd);
  52922. }
  52923. var data = (useDefaults) ? gd._fullData : gd.data;
  52924. var layout = (useDefaults) ? gd._fullLayout : gd.layout;
  52925. var frames = (gd._transitionData || {})._frames;
  52926. function stripObj(d) {
  52927. if(typeof d === 'function') {
  52928. return null;
  52929. }
  52930. if(Lib.isPlainObject(d)) {
  52931. var o = {};
  52932. var v, src;
  52933. for(v in d) {
  52934. // remove private elements and functions
  52935. // _ is for private, [ is a mistake ie [object Object]
  52936. if(typeof d[v] === 'function' ||
  52937. ['_', '['].indexOf(v.charAt(0)) !== -1) {
  52938. continue;
  52939. }
  52940. // look for src/data matches and remove the appropriate one
  52941. if(mode === 'keepdata') {
  52942. // keepdata: remove all ...src tags
  52943. if(v.substr(v.length - 3) === 'src') {
  52944. continue;
  52945. }
  52946. }
  52947. else if(mode === 'keepstream') {
  52948. // keep sourced data if it's being streamed.
  52949. // similar to keepref, but if the 'stream' object exists
  52950. // in a trace, we will keep the data array.
  52951. src = d[v + 'src'];
  52952. if(typeof src === 'string' && src.indexOf(':') > 0) {
  52953. if(!Lib.isPlainObject(d.stream)) {
  52954. continue;
  52955. }
  52956. }
  52957. }
  52958. else if(mode !== 'keepall') {
  52959. // keepref: remove sourced data but only
  52960. // if the source tag is well-formed
  52961. src = d[v + 'src'];
  52962. if(typeof src === 'string' && src.indexOf(':') > 0) {
  52963. continue;
  52964. }
  52965. }
  52966. // OK, we're including this... recurse into it
  52967. o[v] = stripObj(d[v]);
  52968. }
  52969. return o;
  52970. }
  52971. if(Array.isArray(d)) {
  52972. return d.map(stripObj);
  52973. }
  52974. if(Lib.isTypedArray(d)) {
  52975. return Lib.simpleMap(d, Lib.identity);
  52976. }
  52977. // convert native dates to date strings...
  52978. // mostly for external users exporting to plotly
  52979. if(Lib.isJSDate(d)) return Lib.ms2DateTimeLocal(+d);
  52980. return d;
  52981. }
  52982. var obj = {
  52983. data: (data || []).map(function(v) {
  52984. var d = stripObj(v);
  52985. // fit has some little arrays in it that don't contain data,
  52986. // just fit params and meta
  52987. if(dataonly) { delete d.fit; }
  52988. return d;
  52989. })
  52990. };
  52991. if(!dataonly) { obj.layout = stripObj(layout); }
  52992. if(gd.framework && gd.framework.isPolar) obj = gd.framework.getConfig();
  52993. if(frames) obj.frames = stripObj(frames);
  52994. return (output === 'object') ? obj : JSON.stringify(obj);
  52995. };
  52996. /**
  52997. * Modify a keyframe using a list of operations:
  52998. *
  52999. * @param {array of objects} operations
  53000. * Sequence of operations to be performed on the keyframes
  53001. */
  53002. plots.modifyFrames = function(gd, operations) {
  53003. var i, op, frame;
  53004. var _frames = gd._transitionData._frames;
  53005. var _frameHash = gd._transitionData._frameHash;
  53006. for(i = 0; i < operations.length; i++) {
  53007. op = operations[i];
  53008. switch(op.type) {
  53009. // No reason this couldn't exist, but is currently unused/untested:
  53010. /* case 'rename':
  53011. frame = _frames[op.index];
  53012. delete _frameHash[frame.name];
  53013. _frameHash[op.name] = frame;
  53014. frame.name = op.name;
  53015. break;*/
  53016. case 'replace':
  53017. frame = op.value;
  53018. var oldName = (_frames[op.index] || {}).name;
  53019. var newName = frame.name;
  53020. _frames[op.index] = _frameHash[newName] = frame;
  53021. if(newName !== oldName) {
  53022. // If name has changed in addition to replacement, then update
  53023. // the lookup table:
  53024. delete _frameHash[oldName];
  53025. _frameHash[newName] = frame;
  53026. }
  53027. break;
  53028. case 'insert':
  53029. frame = op.value;
  53030. _frameHash[frame.name] = frame;
  53031. _frames.splice(op.index, 0, frame);
  53032. break;
  53033. case 'delete':
  53034. frame = _frames[op.index];
  53035. delete _frameHash[frame.name];
  53036. _frames.splice(op.index, 1);
  53037. break;
  53038. }
  53039. }
  53040. return Promise.resolve();
  53041. };
  53042. /*
  53043. * Compute a keyframe. Merge a keyframe into its base frame(s) and
  53044. * expand properties.
  53045. *
  53046. * @param {object} frameLookup
  53047. * An object containing frames keyed by name (i.e. gd._transitionData._frameHash)
  53048. * @param {string} frame
  53049. * The name of the keyframe to be computed
  53050. *
  53051. * Returns: a new object with the merged content
  53052. */
  53053. plots.computeFrame = function(gd, frameName) {
  53054. var frameLookup = gd._transitionData._frameHash;
  53055. var i, traceIndices, traceIndex, destIndex;
  53056. // Null or undefined will fail on .toString(). We'll allow numbers since we
  53057. // make it clear frames must be given string names, but we'll allow numbers
  53058. // here since they're otherwise fine for looking up frames as long as they're
  53059. // properly cast to strings. We really just want to ensure here that this
  53060. // 1) doesn't fail, and
  53061. // 2) doens't give an incorrect answer (which String(frameName) would)
  53062. if(!frameName) {
  53063. throw new Error('computeFrame must be given a string frame name');
  53064. }
  53065. var framePtr = frameLookup[frameName.toString()];
  53066. // Return false if the name is invalid:
  53067. if(!framePtr) {
  53068. return false;
  53069. }
  53070. var frameStack = [framePtr];
  53071. var frameNameStack = [framePtr.name];
  53072. // Follow frame pointers:
  53073. while(framePtr.baseframe && (framePtr = frameLookup[framePtr.baseframe.toString()])) {
  53074. // Avoid infinite loops:
  53075. if(frameNameStack.indexOf(framePtr.name) !== -1) break;
  53076. frameStack.push(framePtr);
  53077. frameNameStack.push(framePtr.name);
  53078. }
  53079. // A new object for the merged result:
  53080. var result = {};
  53081. // Merge, starting with the last and ending with the desired frame:
  53082. while((framePtr = frameStack.pop())) {
  53083. if(framePtr.layout) {
  53084. result.layout = plots.extendLayout(result.layout, framePtr.layout);
  53085. }
  53086. if(framePtr.data) {
  53087. if(!result.data) {
  53088. result.data = [];
  53089. }
  53090. traceIndices = framePtr.traces;
  53091. if(!traceIndices) {
  53092. // If not defined, assume serial order starting at zero
  53093. traceIndices = [];
  53094. for(i = 0; i < framePtr.data.length; i++) {
  53095. traceIndices[i] = i;
  53096. }
  53097. }
  53098. if(!result.traces) {
  53099. result.traces = [];
  53100. }
  53101. for(i = 0; i < framePtr.data.length; i++) {
  53102. // Loop through this frames data, find out where it should go,
  53103. // and merge it!
  53104. traceIndex = traceIndices[i];
  53105. if(traceIndex === undefined || traceIndex === null) {
  53106. continue;
  53107. }
  53108. destIndex = result.traces.indexOf(traceIndex);
  53109. if(destIndex === -1) {
  53110. destIndex = result.data.length;
  53111. result.traces[destIndex] = traceIndex;
  53112. }
  53113. result.data[destIndex] = plots.extendTrace(result.data[destIndex], framePtr.data[i]);
  53114. }
  53115. }
  53116. }
  53117. return result;
  53118. };
  53119. /*
  53120. * Recompute the lookup table that maps frame name -> frame object. addFrames/
  53121. * deleteFrames already manages this data one at a time, so the only time this
  53122. * is necessary is if you poke around manually in `gd._transitionData._frames`
  53123. * and create and haven't updated the lookup table.
  53124. */
  53125. plots.recomputeFrameHash = function(gd) {
  53126. var hash = gd._transitionData._frameHash = {};
  53127. var frames = gd._transitionData._frames;
  53128. for(var i = 0; i < frames.length; i++) {
  53129. var frame = frames[i];
  53130. if(frame && frame.name) {
  53131. hash[frame.name] = frame;
  53132. }
  53133. }
  53134. };
  53135. /**
  53136. * Extend an object, treating container arrays very differently by extracting
  53137. * their contents and merging them separately.
  53138. *
  53139. * This exists so that we can extendDeepNoArrays and avoid stepping into data
  53140. * arrays without knowledge of the plot schema, but so that we may also manually
  53141. * recurse into known container arrays, such as transforms.
  53142. *
  53143. * See extendTrace and extendLayout below for usage.
  53144. */
  53145. plots.extendObjectWithContainers = function(dest, src, containerPaths) {
  53146. var containerProp, containerVal, i, j, srcProp, destProp, srcContainer, destContainer;
  53147. var copy = Lib.extendDeepNoArrays({}, src || {});
  53148. var expandedObj = Lib.expandObjectPaths(copy);
  53149. var containerObj = {};
  53150. // Step through and extract any container properties. Otherwise extendDeepNoArrays
  53151. // will clobber any existing properties with an empty array and then supplyDefaults
  53152. // will reset everything to defaults.
  53153. if(containerPaths && containerPaths.length) {
  53154. for(i = 0; i < containerPaths.length; i++) {
  53155. containerProp = Lib.nestedProperty(expandedObj, containerPaths[i]);
  53156. containerVal = containerProp.get();
  53157. if(containerVal === undefined) {
  53158. Lib.nestedProperty(containerObj, containerPaths[i]).set(null);
  53159. }
  53160. else {
  53161. containerProp.set(null);
  53162. Lib.nestedProperty(containerObj, containerPaths[i]).set(containerVal);
  53163. }
  53164. }
  53165. }
  53166. dest = Lib.extendDeepNoArrays(dest || {}, expandedObj);
  53167. if(containerPaths && containerPaths.length) {
  53168. for(i = 0; i < containerPaths.length; i++) {
  53169. srcProp = Lib.nestedProperty(containerObj, containerPaths[i]);
  53170. srcContainer = srcProp.get();
  53171. if(!srcContainer) continue;
  53172. destProp = Lib.nestedProperty(dest, containerPaths[i]);
  53173. destContainer = destProp.get();
  53174. if(!Array.isArray(destContainer)) {
  53175. destContainer = [];
  53176. destProp.set(destContainer);
  53177. }
  53178. for(j = 0; j < srcContainer.length; j++) {
  53179. var srcObj = srcContainer[j];
  53180. if(srcObj === null) destContainer[j] = null;
  53181. else {
  53182. destContainer[j] = plots.extendObjectWithContainers(destContainer[j], srcObj);
  53183. }
  53184. }
  53185. destProp.set(destContainer);
  53186. }
  53187. }
  53188. return dest;
  53189. };
  53190. plots.dataArrayContainers = ['transforms', 'dimensions'];
  53191. plots.layoutArrayContainers = Registry.layoutArrayContainers;
  53192. /*
  53193. * Extend a trace definition. This method:
  53194. *
  53195. * 1. directly transfers any array references
  53196. * 2. manually recurses into container arrays like transforms
  53197. *
  53198. * The result is the original object reference with the new contents merged in.
  53199. */
  53200. plots.extendTrace = function(destTrace, srcTrace) {
  53201. return plots.extendObjectWithContainers(destTrace, srcTrace, plots.dataArrayContainers);
  53202. };
  53203. /*
  53204. * Extend a layout definition. This method:
  53205. *
  53206. * 1. directly transfers any array references (not critically important for
  53207. * layout since there aren't really data arrays)
  53208. * 2. manually recurses into container arrays like annotations
  53209. *
  53210. * The result is the original object reference with the new contents merged in.
  53211. */
  53212. plots.extendLayout = function(destLayout, srcLayout) {
  53213. return plots.extendObjectWithContainers(destLayout, srcLayout, plots.layoutArrayContainers);
  53214. };
  53215. /**
  53216. * Transition to a set of new data and layout properties from Plotly.animate
  53217. *
  53218. * @param {DOM element} gd
  53219. * @param {Object[]} data
  53220. * an array of data objects following the normal Plotly data definition format
  53221. * @param {Object} layout
  53222. * a layout object, following normal Plotly layout format
  53223. * @param {Number[]} traces
  53224. * indices of the corresponding traces specified in `data`
  53225. * @param {Object} frameOpts
  53226. * options for the frame (i.e. whether to redraw post-transition)
  53227. * @param {Object} transitionOpts
  53228. * options for the transition
  53229. */
  53230. plots.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) {
  53231. var opts = {redraw: frameOpts.redraw};
  53232. var transitionedTraces = [];
  53233. var axEdits = [];
  53234. opts.prepareFn = function() {
  53235. var dataLength = Array.isArray(data) ? data.length : 0;
  53236. var traceIndices = traces.slice(0, dataLength);
  53237. for(var i = 0; i < traceIndices.length; i++) {
  53238. var traceIdx = traceIndices[i];
  53239. var trace = gd._fullData[traceIdx];
  53240. var module = trace._module;
  53241. // There's nothing to do if this module is not defined:
  53242. if(!module) continue;
  53243. // Don't register the trace as transitioned if it doesn't know what to do.
  53244. // If it *is* registered, it will receive a callback that it's responsible
  53245. // for calling in order to register the transition as having completed.
  53246. if(module.animatable) {
  53247. transitionedTraces.push(traceIdx);
  53248. }
  53249. gd.data[traceIndices[i]] = plots.extendTrace(gd.data[traceIndices[i]], data[i]);
  53250. }
  53251. // Follow the same procedure. Clone it so we don't mangle the input, then
  53252. // expand any object paths so we can merge deep into gd.layout:
  53253. var layoutUpdate = Lib.expandObjectPaths(Lib.extendDeepNoArrays({}, layout));
  53254. // Before merging though, we need to modify the incoming layout. We only
  53255. // know how to *transition* layout ranges, so it's imperative that a new
  53256. // range not be sent to the layout before the transition has started. So
  53257. // we must remove the things we can transition:
  53258. var axisAttrRe = /^[xy]axis[0-9]*$/;
  53259. for(var attr in layoutUpdate) {
  53260. if(!axisAttrRe.test(attr)) continue;
  53261. delete layoutUpdate[attr].range;
  53262. }
  53263. plots.extendLayout(gd.layout, layoutUpdate);
  53264. // Supply defaults after applying the incoming properties. Note that any attempt
  53265. // to simplify this step and reduce the amount of work resulted in the reconstruction
  53266. // of essentially the whole supplyDefaults step, so that it seems sensible to just use
  53267. // supplyDefaults even though it's heavier than would otherwise be desired for
  53268. // transitions:
  53269. // first delete calcdata so supplyDefaults knows a calc step is coming
  53270. delete gd.calcdata;
  53271. plots.supplyDefaults(gd);
  53272. plots.doCalcdata(gd);
  53273. var newLayout = Lib.expandObjectPaths(layout);
  53274. if(newLayout) {
  53275. var subplots = gd._fullLayout._plots;
  53276. for(var k in subplots) {
  53277. var plotinfo = subplots[k];
  53278. var xa = plotinfo.xaxis;
  53279. var ya = plotinfo.yaxis;
  53280. var xr0 = xa.range.slice();
  53281. var yr0 = ya.range.slice();
  53282. var xr1;
  53283. if(Array.isArray(newLayout[xa._name + '.range'])) {
  53284. xr1 = newLayout[xa._name + '.range'].slice();
  53285. } else if(Array.isArray((newLayout[xa._name] || {}).range)) {
  53286. xr1 = newLayout[xa._name].range.slice();
  53287. }
  53288. var yr1;
  53289. if(Array.isArray(newLayout[ya._name + '.range'])) {
  53290. yr1 = newLayout[ya._name + '.range'].slice();
  53291. } else if(Array.isArray((newLayout[ya._name] || {}).range)) {
  53292. yr1 = newLayout[ya._name].range.slice();
  53293. }
  53294. var editX;
  53295. if(xr0 && xr1 && (xr0[0] !== xr1[0] || xr0[1] !== xr1[1])) {
  53296. editX = {xr0: xr0, xr1: xr1};
  53297. }
  53298. var editY;
  53299. if(yr0 && yr1 && (yr0[0] !== yr1[0] || yr0[1] !== yr1[1])) {
  53300. editY = {yr0: yr0, yr1: yr1};
  53301. }
  53302. if(editX || editY) {
  53303. axEdits.push(Lib.extendFlat({plotinfo: plotinfo}, editX, editY));
  53304. }
  53305. }
  53306. }
  53307. return Promise.resolve();
  53308. };
  53309. opts.runFn = function(makeCallback) {
  53310. var traceTransitionOpts;
  53311. var basePlotModules = gd._fullLayout._basePlotModules;
  53312. var hasAxisTransition = axEdits.length;
  53313. var i;
  53314. if(layout) {
  53315. for(i = 0; i < basePlotModules.length; i++) {
  53316. if(basePlotModules[i].transitionAxes) {
  53317. basePlotModules[i].transitionAxes(gd, axEdits, transitionOpts, makeCallback);
  53318. }
  53319. }
  53320. }
  53321. // Here handle the exception that we refuse to animate scales and axes at the same
  53322. // time. In other words, if there's an axis transition, then set the data transition
  53323. // to instantaneous.
  53324. if(hasAxisTransition) {
  53325. traceTransitionOpts = Lib.extendFlat({}, transitionOpts);
  53326. traceTransitionOpts.duration = 0;
  53327. // This means do not transition traces,
  53328. // this happens on layout-only (e.g. axis range) animations
  53329. transitionedTraces = null;
  53330. } else {
  53331. traceTransitionOpts = transitionOpts;
  53332. }
  53333. for(i = 0; i < basePlotModules.length; i++) {
  53334. // Note that we pass a callback to *create* the callback that must be invoked on completion.
  53335. // This is since not all traces know about transitions, so it greatly simplifies matters if
  53336. // the trace is responsible for creating a callback, if needed, and then executing it when
  53337. // the time is right.
  53338. basePlotModules[i].plot(gd, transitionedTraces, traceTransitionOpts, makeCallback);
  53339. }
  53340. };
  53341. return _transition(gd, transitionOpts, opts);
  53342. };
  53343. /**
  53344. * Transition to a set of new data and layout properties from Plotly.react
  53345. *
  53346. * @param {DOM element} gd
  53347. * @param {object} restyleFlags
  53348. * - anim {'all'|'some'}
  53349. * @param {object} relayoutFlags
  53350. * - anim {'all'|'some'}
  53351. * @param {object} oldFullLayout : old (pre Plotly.react) fullLayout
  53352. */
  53353. plots.transitionFromReact = function(gd, restyleFlags, relayoutFlags, oldFullLayout) {
  53354. var fullLayout = gd._fullLayout;
  53355. var transitionOpts = fullLayout.transition;
  53356. var opts = {};
  53357. var axEdits = [];
  53358. opts.prepareFn = function() {
  53359. var subplots = fullLayout._plots;
  53360. // no need to redraw at end of transition,
  53361. // if all changes are animatable
  53362. opts.redraw = false;
  53363. if(restyleFlags.anim === 'some') opts.redraw = true;
  53364. if(relayoutFlags.anim === 'some') opts.redraw = true;
  53365. for(var k in subplots) {
  53366. var plotinfo = subplots[k];
  53367. var xa = plotinfo.xaxis;
  53368. var ya = plotinfo.yaxis;
  53369. var xr0 = oldFullLayout[xa._name].range.slice();
  53370. var yr0 = oldFullLayout[ya._name].range.slice();
  53371. var xr1 = xa.range.slice();
  53372. var yr1 = ya.range.slice();
  53373. xa.setScale();
  53374. ya.setScale();
  53375. var editX;
  53376. if(xr0[0] !== xr1[0] || xr0[1] !== xr1[1]) {
  53377. editX = {xr0: xr0, xr1: xr1};
  53378. }
  53379. var editY;
  53380. if(yr0[0] !== yr1[0] || yr0[1] !== yr1[1]) {
  53381. editY = {yr0: yr0, yr1: yr1};
  53382. }
  53383. if(editX || editY) {
  53384. axEdits.push(Lib.extendFlat({plotinfo: plotinfo}, editX, editY));
  53385. }
  53386. }
  53387. return Promise.resolve();
  53388. };
  53389. opts.runFn = function(makeCallback) {
  53390. var fullData = gd._fullData;
  53391. var fullLayout = gd._fullLayout;
  53392. var basePlotModules = fullLayout._basePlotModules;
  53393. var axisTransitionOpts;
  53394. var traceTransitionOpts;
  53395. var transitionedTraces;
  53396. var allTraceIndices = [];
  53397. for(var i = 0; i < fullData.length; i++) {
  53398. allTraceIndices.push(i);
  53399. }
  53400. function transitionAxes() {
  53401. for(var j = 0; j < basePlotModules.length; j++) {
  53402. if(basePlotModules[j].transitionAxes) {
  53403. basePlotModules[j].transitionAxes(gd, axEdits, axisTransitionOpts, makeCallback);
  53404. }
  53405. }
  53406. }
  53407. function transitionTraces() {
  53408. for(var j = 0; j < basePlotModules.length; j++) {
  53409. basePlotModules[j].plot(gd, transitionedTraces, traceTransitionOpts, makeCallback);
  53410. }
  53411. }
  53412. if(axEdits.length && restyleFlags.anim) {
  53413. if(transitionOpts.ordering === 'traces first') {
  53414. axisTransitionOpts = Lib.extendFlat({}, transitionOpts, {duration: 0});
  53415. transitionedTraces = allTraceIndices;
  53416. traceTransitionOpts = transitionOpts;
  53417. transitionTraces();
  53418. setTimeout(transitionAxes, transitionOpts.duration);
  53419. } else {
  53420. axisTransitionOpts = transitionOpts;
  53421. transitionedTraces = null;
  53422. traceTransitionOpts = Lib.extendFlat({}, transitionOpts, {duration: 0});
  53423. transitionAxes();
  53424. transitionTraces();
  53425. }
  53426. } else if(axEdits.length) {
  53427. axisTransitionOpts = transitionOpts;
  53428. transitionAxes();
  53429. } else if(restyleFlags.anim) {
  53430. transitionedTraces = allTraceIndices;
  53431. traceTransitionOpts = transitionOpts;
  53432. transitionTraces();
  53433. }
  53434. };
  53435. return _transition(gd, transitionOpts, opts);
  53436. };
  53437. /**
  53438. * trace/layout transition wrapper that works
  53439. * for transitions initiated by Plotly.animate and Plotly.react.
  53440. *
  53441. * @param {DOM element} gd
  53442. * @param {object} transitionOpts
  53443. * @param {object} opts
  53444. * - redraw {boolean}
  53445. * - prepareFn {function} *should return a Promise*
  53446. * - runFn {function} ran inside executeTransitions
  53447. */
  53448. function _transition(gd, transitionOpts, opts) {
  53449. var aborted = false;
  53450. function executeCallbacks(list) {
  53451. var p = Promise.resolve();
  53452. if(!list) return p;
  53453. while(list.length) {
  53454. p = p.then((list.shift()));
  53455. }
  53456. return p;
  53457. }
  53458. function flushCallbacks(list) {
  53459. if(!list) return;
  53460. while(list.length) {
  53461. list.shift();
  53462. }
  53463. }
  53464. function executeTransitions() {
  53465. gd.emit('plotly_transitioning', []);
  53466. return new Promise(function(resolve) {
  53467. // This flag is used to disabled things like autorange:
  53468. gd._transitioning = true;
  53469. // When instantaneous updates are coming through quickly, it's too much to simply disable
  53470. // all interaction, so store this flag so we can disambiguate whether mouse interactions
  53471. // should be fully disabled or not:
  53472. if(transitionOpts.duration > 0) {
  53473. gd._transitioningWithDuration = true;
  53474. }
  53475. // If another transition is triggered, this callback will be executed simply because it's
  53476. // in the interruptCallbacks queue. If this transition completes, it will instead flush
  53477. // that queue and forget about this callback.
  53478. gd._transitionData._interruptCallbacks.push(function() {
  53479. aborted = true;
  53480. });
  53481. if(opts.redraw) {
  53482. gd._transitionData._interruptCallbacks.push(function() {
  53483. return Registry.call('redraw', gd);
  53484. });
  53485. }
  53486. // Emit this and make sure it happens last:
  53487. gd._transitionData._interruptCallbacks.push(function() {
  53488. gd.emit('plotly_transitioninterrupted', []);
  53489. });
  53490. // Construct callbacks that are executed on transition end. This ensures the d3 transitions
  53491. // are *complete* before anything else is done.
  53492. var numCallbacks = 0;
  53493. var numCompleted = 0;
  53494. function makeCallback() {
  53495. numCallbacks++;
  53496. return function() {
  53497. numCompleted++;
  53498. // When all are complete, perform a redraw:
  53499. if(!aborted && numCompleted === numCallbacks) {
  53500. completeTransition(resolve);
  53501. }
  53502. };
  53503. }
  53504. opts.runFn(makeCallback);
  53505. // If nothing else creates a callback, then this will trigger the completion in the next tick:
  53506. setTimeout(makeCallback());
  53507. });
  53508. }
  53509. function completeTransition(callback) {
  53510. // This a simple workaround for tests which purge the graph before animations
  53511. // have completed. That's not a very common case, so this is the simplest
  53512. // fix.
  53513. if(!gd._transitionData) return;
  53514. flushCallbacks(gd._transitionData._interruptCallbacks);
  53515. return Promise.resolve().then(function() {
  53516. if(opts.redraw) {
  53517. return Registry.call('redraw', gd);
  53518. }
  53519. }).then(function() {
  53520. // Set transitioning false again once the redraw has occurred. This is used, for example,
  53521. // to prevent the trailing redraw from autoranging:
  53522. gd._transitioning = false;
  53523. gd._transitioningWithDuration = false;
  53524. gd.emit('plotly_transitioned', []);
  53525. }).then(callback);
  53526. }
  53527. function interruptPreviousTransitions() {
  53528. // Fail-safe against purged plot:
  53529. if(!gd._transitionData) return;
  53530. // If a transition is interrupted, set this to false. At the moment, the only thing that would
  53531. // interrupt a transition is another transition, so that it will momentarily be set to true
  53532. // again, but this determines whether autorange or dragbox work, so it's for the sake of
  53533. // cleanliness:
  53534. gd._transitioning = false;
  53535. return executeCallbacks(gd._transitionData._interruptCallbacks);
  53536. }
  53537. var seq = [
  53538. plots.previousPromises,
  53539. interruptPreviousTransitions,
  53540. opts.prepareFn,
  53541. plots.rehover,
  53542. executeTransitions
  53543. ];
  53544. var transitionStarting = Lib.syncOrAsync(seq, gd);
  53545. if(!transitionStarting || !transitionStarting.then) {
  53546. transitionStarting = Promise.resolve();
  53547. }
  53548. return transitionStarting.then(function() { return gd; });
  53549. }
  53550. plots.doCalcdata = function(gd, traces) {
  53551. var axList = axisIDs.list(gd);
  53552. var fullData = gd._fullData;
  53553. var fullLayout = gd._fullLayout;
  53554. var trace, _module, i, j;
  53555. // XXX: Is this correct? Needs a closer look so that *some* traces can be recomputed without
  53556. // *all* needing doCalcdata:
  53557. var calcdata = new Array(fullData.length);
  53558. var oldCalcdata = (gd.calcdata || []).slice(0);
  53559. gd.calcdata = calcdata;
  53560. // extra helper variables
  53561. // how many box/violins plots do we have (in case they're grouped)
  53562. fullLayout._numBoxes = 0;
  53563. fullLayout._numViolins = 0;
  53564. // initialize violin per-scale-group stats container
  53565. fullLayout._violinScaleGroupStats = {};
  53566. // for calculating avg luminosity of heatmaps
  53567. gd._hmpixcount = 0;
  53568. gd._hmlumcount = 0;
  53569. // for sharing colors across pies (and for legend)
  53570. fullLayout._piecolormap = {};
  53571. // If traces were specified and this trace was not included,
  53572. // then transfer it over from the old calcdata:
  53573. for(i = 0; i < fullData.length; i++) {
  53574. if(Array.isArray(traces) && traces.indexOf(i) === -1) {
  53575. calcdata[i] = oldCalcdata[i];
  53576. continue;
  53577. }
  53578. }
  53579. for(i = 0; i < fullData.length; i++) {
  53580. trace = fullData[i];
  53581. trace._arrayAttrs = PlotSchema.findArrayAttributes(trace);
  53582. // keep track of trace extremes (for autorange) in here
  53583. trace._extremes = {};
  53584. }
  53585. // add polar axes to axis list
  53586. var polarIds = fullLayout._subplots.polar || [];
  53587. for(i = 0; i < polarIds.length; i++) {
  53588. axList.push(
  53589. fullLayout[polarIds[i]].radialaxis,
  53590. fullLayout[polarIds[i]].angularaxis
  53591. );
  53592. }
  53593. setupAxisCategories(axList, fullData);
  53594. var hasCalcTransform = false;
  53595. // transform loop
  53596. for(i = 0; i < fullData.length; i++) {
  53597. trace = fullData[i];
  53598. if(trace.visible === true && trace.transforms) {
  53599. _module = trace._module;
  53600. // we need one round of trace module calc before
  53601. // the calc transform to 'fill in' the categories list
  53602. // used for example in the data-to-coordinate method
  53603. if(_module && _module.calc) {
  53604. var cdi = _module.calc(gd, trace);
  53605. // must clear scene 'batches', so that 2nd
  53606. // _module.calc call starts from scratch
  53607. if(cdi[0] && cdi[0].t && cdi[0].t._scene) {
  53608. delete cdi[0].t._scene.dirty;
  53609. }
  53610. }
  53611. for(j = 0; j < trace.transforms.length; j++) {
  53612. var transform = trace.transforms[j];
  53613. _module = transformsRegistry[transform.type];
  53614. if(_module && _module.calcTransform) {
  53615. trace._hasCalcTransform = true;
  53616. hasCalcTransform = true;
  53617. _module.calcTransform(gd, trace, transform);
  53618. }
  53619. }
  53620. }
  53621. }
  53622. // clear stuff that should recomputed in 'regular' loop
  53623. if(hasCalcTransform) setupAxisCategories(axList, fullData);
  53624. function calci(i, isContainer) {
  53625. trace = fullData[i];
  53626. _module = trace._module;
  53627. if(!!_module.isContainer !== isContainer) return;
  53628. var cd = [];
  53629. if(trace.visible === true) {
  53630. // clear existing ref in case it got relinked
  53631. delete trace._indexToPoints;
  53632. // keep ref of index-to-points map object of the *last* enabled transform,
  53633. // this index-to-points map object is required to determine the calcdata indices
  53634. // that correspond to input indices (e.g. from 'selectedpoints')
  53635. var transforms = trace.transforms || [];
  53636. for(j = transforms.length - 1; j >= 0; j--) {
  53637. if(transforms[j].enabled) {
  53638. trace._indexToPoints = transforms[j]._indexToPoints;
  53639. break;
  53640. }
  53641. }
  53642. if(_module && _module.calc) {
  53643. cd = _module.calc(gd, trace);
  53644. }
  53645. }
  53646. // Make sure there is a first point.
  53647. //
  53648. // This ensures there is a calcdata item for every trace,
  53649. // even if cartesian logic doesn't handle it (for things like legends).
  53650. if(!Array.isArray(cd) || !cd[0]) {
  53651. cd = [{x: BADNUM, y: BADNUM}];
  53652. }
  53653. // add the trace-wide properties to the first point,
  53654. // per point properties to every point
  53655. // t is the holder for trace-wide properties
  53656. if(!cd[0].t) cd[0].t = {};
  53657. cd[0].trace = trace;
  53658. calcdata[i] = cd;
  53659. }
  53660. // 'regular' loop - make sure container traces (eg carpet) calc before
  53661. // contained traces (eg contourcarpet)
  53662. for(i = 0; i < fullData.length; i++) calci(i, true);
  53663. for(i = 0; i < fullData.length; i++) calci(i, false);
  53664. doCrossTraceCalc(gd);
  53665. Registry.getComponentMethod('fx', 'calc')(gd);
  53666. Registry.getComponentMethod('errorbars', 'calc')(gd);
  53667. };
  53668. function setupAxisCategories(axList, fullData) {
  53669. for(var i = 0; i < axList.length; i++) {
  53670. var ax = axList[i];
  53671. ax.clearCalc();
  53672. if(ax.type === 'multicategory') {
  53673. ax.setupMultiCategory(fullData);
  53674. }
  53675. }
  53676. }
  53677. function doCrossTraceCalc(gd) {
  53678. var fullLayout = gd._fullLayout;
  53679. var modules = fullLayout._visibleModules;
  53680. var hash = {};
  53681. var i, j, k;
  53682. // position and range calculations for traces that
  53683. // depend on each other ie bars (stacked or grouped)
  53684. // and boxes (grouped) push each other out of the way
  53685. for(j = 0; j < modules.length; j++) {
  53686. var _module = modules[j];
  53687. var fn = _module.crossTraceCalc;
  53688. if(fn) {
  53689. var spType = _module.basePlotModule.name;
  53690. if(hash[spType]) {
  53691. Lib.pushUnique(hash[spType], fn);
  53692. } else {
  53693. hash[spType] = [fn];
  53694. }
  53695. }
  53696. }
  53697. for(k in hash) {
  53698. var methods = hash[k];
  53699. var subplots = fullLayout._subplots[k];
  53700. if(Array.isArray(subplots)) {
  53701. for(i = 0; i < subplots.length; i++) {
  53702. var sp = subplots[i];
  53703. var spInfo = k === 'cartesian' ?
  53704. fullLayout._plots[sp] :
  53705. fullLayout[sp];
  53706. for(j = 0; j < methods.length; j++) {
  53707. methods[j](gd, spInfo, sp);
  53708. }
  53709. }
  53710. }
  53711. else {
  53712. for(j = 0; j < methods.length; j++) {
  53713. methods[j](gd);
  53714. }
  53715. }
  53716. }
  53717. }
  53718. plots.rehover = function(gd) {
  53719. if(gd._fullLayout._rehover) {
  53720. gd._fullLayout._rehover();
  53721. }
  53722. };
  53723. plots.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subplotLayout) {
  53724. var traceHashOld = subplot.traceHash;
  53725. var traceHash = {};
  53726. var i;
  53727. // build up moduleName -> calcData hash
  53728. for(i = 0; i < subplotCalcData.length; i++) {
  53729. var calcTraces = subplotCalcData[i];
  53730. var trace = calcTraces[0].trace;
  53731. // skip over visible === false traces
  53732. // as they don't have `_module` ref
  53733. if(trace.visible) {
  53734. traceHash[trace.type] = traceHash[trace.type] || [];
  53735. traceHash[trace.type].push(calcTraces);
  53736. }
  53737. }
  53738. // when a trace gets deleted, make sure that its module's
  53739. // plot method is called so that it is properly
  53740. // removed from the DOM.
  53741. for(var moduleNameOld in traceHashOld) {
  53742. if(!traceHash[moduleNameOld]) {
  53743. var fakeCalcTrace = traceHashOld[moduleNameOld][0];
  53744. var fakeTrace = fakeCalcTrace[0].trace;
  53745. fakeTrace.visible = false;
  53746. traceHash[moduleNameOld] = [fakeCalcTrace];
  53747. }
  53748. }
  53749. // call module plot method
  53750. for(var moduleName in traceHash) {
  53751. var moduleCalcData = traceHash[moduleName];
  53752. var _module = moduleCalcData[0][0].trace._module;
  53753. _module.plot(gd, subplot, Lib.filterVisible(moduleCalcData), subplotLayout);
  53754. }
  53755. // update moduleName -> calcData hash
  53756. subplot.traceHash = traceHash;
  53757. };
  53758. },{"../components/color":51,"../constants/numerical":149,"../lib":168,"../plot_api/plot_schema":201,"../plot_api/plot_template":202,"../plots/cartesian/axis_ids":215,"../registry":257,"./animation_attributes":207,"./attributes":209,"./command":237,"./font_attributes":239,"./frame_attributes":240,"./layout_attributes":243,"d3":16,"fast-isnumeric":18}],246:[function(_dereq_,module,exports){
  53759. /**
  53760. * Copyright 2012-2019, Plotly, Inc.
  53761. * All rights reserved.
  53762. *
  53763. * This source code is licensed under the MIT license found in the
  53764. * LICENSE file in the root directory of this source tree.
  53765. */
  53766. 'use strict';
  53767. var scatterAttrs = _dereq_('../../../traces/scatter/attributes');
  53768. var scatterMarkerAttrs = scatterAttrs.marker;
  53769. var extendFlat = _dereq_('../../../lib/extend').extendFlat;
  53770. var deprecationWarning = [
  53771. 'Area traces are deprecated!',
  53772. 'Please switch to the *barpolar* trace type.'
  53773. ].join(' ');
  53774. module.exports = {
  53775. r: extendFlat({}, scatterAttrs.r, {
  53776. }),
  53777. t: extendFlat({}, scatterAttrs.t, {
  53778. }),
  53779. marker: {
  53780. color: extendFlat({}, scatterMarkerAttrs.color, {
  53781. }),
  53782. size: extendFlat({}, scatterMarkerAttrs.size, {
  53783. }),
  53784. symbol: extendFlat({}, scatterMarkerAttrs.symbol, {
  53785. }),
  53786. opacity: extendFlat({}, scatterMarkerAttrs.opacity, {
  53787. }),
  53788. editType: 'calc'
  53789. }
  53790. };
  53791. },{"../../../lib/extend":162,"../../../traces/scatter/attributes":367}],247:[function(_dereq_,module,exports){
  53792. /**
  53793. * Copyright 2012-2019, Plotly, Inc.
  53794. * All rights reserved.
  53795. *
  53796. * This source code is licensed under the MIT license found in the
  53797. * LICENSE file in the root directory of this source tree.
  53798. */
  53799. 'use strict';
  53800. var axesAttrs = _dereq_('../../cartesian/layout_attributes');
  53801. var extendFlat = _dereq_('../../../lib/extend').extendFlat;
  53802. var overrideAll = _dereq_('../../../plot_api/edit_types').overrideAll;
  53803. var deprecationWarning = [
  53804. 'Legacy polar charts are deprecated!',
  53805. 'Please switch to *polar* subplots.'
  53806. ].join(' ');
  53807. var domainAttr = extendFlat({}, axesAttrs.domain, {
  53808. });
  53809. function mergeAttrs(axisName, nonCommonAttrs) {
  53810. var commonAttrs = {
  53811. showline: {
  53812. valType: 'boolean',
  53813. },
  53814. showticklabels: {
  53815. valType: 'boolean',
  53816. },
  53817. tickorientation: {
  53818. valType: 'enumerated',
  53819. values: ['horizontal', 'vertical'],
  53820. },
  53821. ticklen: {
  53822. valType: 'number',
  53823. min: 0,
  53824. },
  53825. tickcolor: {
  53826. valType: 'color',
  53827. },
  53828. ticksuffix: {
  53829. valType: 'string',
  53830. },
  53831. endpadding: {
  53832. valType: 'number',
  53833. description: deprecationWarning,
  53834. },
  53835. visible: {
  53836. valType: 'boolean',
  53837. }
  53838. };
  53839. return extendFlat({}, nonCommonAttrs, commonAttrs);
  53840. }
  53841. module.exports = overrideAll({
  53842. radialaxis: mergeAttrs('radial', {
  53843. range: {
  53844. valType: 'info_array',
  53845. items: [
  53846. { valType: 'number' },
  53847. { valType: 'number' }
  53848. ],
  53849. },
  53850. domain: domainAttr,
  53851. orientation: {
  53852. valType: 'number',
  53853. }
  53854. }),
  53855. angularaxis: mergeAttrs('angular', {
  53856. range: {
  53857. valType: 'info_array',
  53858. items: [
  53859. { valType: 'number', dflt: 0 },
  53860. { valType: 'number', dflt: 360 }
  53861. ],
  53862. },
  53863. domain: domainAttr
  53864. }),
  53865. // attributes that appear at layout root
  53866. layout: {
  53867. direction: {
  53868. valType: 'enumerated',
  53869. values: ['clockwise', 'counterclockwise'],
  53870. },
  53871. orientation: {
  53872. valType: 'angle',
  53873. }
  53874. }
  53875. }, 'plot', 'nested');
  53876. },{"../../../lib/extend":162,"../../../plot_api/edit_types":195,"../../cartesian/layout_attributes":225}],248:[function(_dereq_,module,exports){
  53877. /**
  53878. * Copyright 2012-2019, Plotly, Inc.
  53879. * All rights reserved.
  53880. *
  53881. * This source code is licensed under the MIT license found in the
  53882. * LICENSE file in the root directory of this source tree.
  53883. */
  53884. 'use strict';
  53885. var Polar = module.exports = _dereq_('./micropolar');
  53886. Polar.manager = _dereq_('./micropolar_manager');
  53887. },{"./micropolar":249,"./micropolar_manager":250}],249:[function(_dereq_,module,exports){
  53888. /**
  53889. * Copyright 2012-2019, Plotly, Inc.
  53890. * All rights reserved.
  53891. *
  53892. * This source code is licensed under the MIT license found in the
  53893. * LICENSE file in the root directory of this source tree.
  53894. */
  53895. var d3 = _dereq_('d3');
  53896. var Lib = _dereq_('../../../lib');
  53897. var extendDeepAll = Lib.extendDeepAll;
  53898. var MID_SHIFT = _dereq_('../../../constants/alignment').MID_SHIFT;
  53899. var µ = module.exports = { version: '0.2.2' };
  53900. µ.Axis = function module() {
  53901. var config = {
  53902. data: [],
  53903. layout: {}
  53904. }, inputConfig = {}, liveConfig = {};
  53905. var svg, container, dispatch = d3.dispatch('hover'), radialScale, angularScale;
  53906. var exports = {};
  53907. function render(_container) {
  53908. container = _container || container;
  53909. var data = config.data;
  53910. var axisConfig = config.layout;
  53911. if (typeof container == 'string' || container.nodeName) container = d3.select(container);
  53912. container.datum(data).each(function(_data, _index) {
  53913. var dataOriginal = _data.slice();
  53914. liveConfig = {
  53915. data: µ.util.cloneJson(dataOriginal),
  53916. layout: µ.util.cloneJson(axisConfig)
  53917. };
  53918. var colorIndex = 0;
  53919. dataOriginal.forEach(function(d, i) {
  53920. if (!d.color) {
  53921. d.color = axisConfig.defaultColorRange[colorIndex];
  53922. colorIndex = (colorIndex + 1) % axisConfig.defaultColorRange.length;
  53923. }
  53924. if (!d.strokeColor) {
  53925. d.strokeColor = d.geometry === 'LinePlot' ? d.color : d3.rgb(d.color).darker().toString();
  53926. }
  53927. liveConfig.data[i].color = d.color;
  53928. liveConfig.data[i].strokeColor = d.strokeColor;
  53929. liveConfig.data[i].strokeDash = d.strokeDash;
  53930. liveConfig.data[i].strokeSize = d.strokeSize;
  53931. });
  53932. var data = dataOriginal.filter(function(d, i) {
  53933. var visible = d.visible;
  53934. return typeof visible === 'undefined' || visible === true;
  53935. });
  53936. var isStacked = false;
  53937. var dataWithGroupId = data.map(function(d, i) {
  53938. isStacked = isStacked || typeof d.groupId !== 'undefined';
  53939. return d;
  53940. });
  53941. if (isStacked) {
  53942. var grouped = d3.nest().key(function(d, i) {
  53943. return typeof d.groupId != 'undefined' ? d.groupId : 'unstacked';
  53944. }).entries(dataWithGroupId);
  53945. var dataYStack = [];
  53946. var stacked = grouped.map(function(d, i) {
  53947. if (d.key === 'unstacked') return d.values; else {
  53948. var prevArray = d.values[0].r.map(function(d, i) {
  53949. return 0;
  53950. });
  53951. d.values.forEach(function(d, i, a) {
  53952. d.yStack = [ prevArray ];
  53953. dataYStack.push(prevArray);
  53954. prevArray = µ.util.sumArrays(d.r, prevArray);
  53955. });
  53956. return d.values;
  53957. }
  53958. });
  53959. data = d3.merge(stacked);
  53960. }
  53961. data.forEach(function(d, i) {
  53962. d.t = Array.isArray(d.t[0]) ? d.t : [ d.t ];
  53963. d.r = Array.isArray(d.r[0]) ? d.r : [ d.r ];
  53964. });
  53965. var radius = Math.min(axisConfig.width - axisConfig.margin.left - axisConfig.margin.right, axisConfig.height - axisConfig.margin.top - axisConfig.margin.bottom) / 2;
  53966. radius = Math.max(10, radius);
  53967. var chartCenter = [ axisConfig.margin.left + radius, axisConfig.margin.top + radius ];
  53968. var extent;
  53969. if (isStacked) {
  53970. var highestStackedValue = d3.max(µ.util.sumArrays(µ.util.arrayLast(data).r[0], µ.util.arrayLast(dataYStack)));
  53971. extent = [ 0, highestStackedValue ];
  53972. } else extent = d3.extent(µ.util.flattenArray(data.map(function(d, i) {
  53973. return d.r;
  53974. })));
  53975. if (axisConfig.radialAxis.domain != µ.DATAEXTENT) extent[0] = 0;
  53976. radialScale = d3.scale.linear().domain(axisConfig.radialAxis.domain != µ.DATAEXTENT && axisConfig.radialAxis.domain ? axisConfig.radialAxis.domain : extent).range([ 0, radius ]);
  53977. liveConfig.layout.radialAxis.domain = radialScale.domain();
  53978. var angularDataMerged = µ.util.flattenArray(data.map(function(d, i) {
  53979. return d.t;
  53980. }));
  53981. var isOrdinal = typeof angularDataMerged[0] === 'string';
  53982. var ticks;
  53983. if (isOrdinal) {
  53984. angularDataMerged = µ.util.deduplicate(angularDataMerged);
  53985. ticks = angularDataMerged.slice();
  53986. angularDataMerged = d3.range(angularDataMerged.length);
  53987. data = data.map(function(d, i) {
  53988. var result = d;
  53989. d.t = [ angularDataMerged ];
  53990. if (isStacked) result.yStack = d.yStack;
  53991. return result;
  53992. });
  53993. }
  53994. var hasOnlyLineOrDotPlot = data.filter(function(d, i) {
  53995. return d.geometry === 'LinePlot' || d.geometry === 'DotPlot';
  53996. }).length === data.length;
  53997. var needsEndSpacing = axisConfig.needsEndSpacing === null ? isOrdinal || !hasOnlyLineOrDotPlot : axisConfig.needsEndSpacing;
  53998. var useProvidedDomain = axisConfig.angularAxis.domain && axisConfig.angularAxis.domain != µ.DATAEXTENT && !isOrdinal && axisConfig.angularAxis.domain[0] >= 0;
  53999. var angularDomain = useProvidedDomain ? axisConfig.angularAxis.domain : d3.extent(angularDataMerged);
  54000. var angularDomainStep = Math.abs(angularDataMerged[1] - angularDataMerged[0]);
  54001. if (hasOnlyLineOrDotPlot && !isOrdinal) angularDomainStep = 0;
  54002. var angularDomainWithPadding = angularDomain.slice();
  54003. if (needsEndSpacing && isOrdinal) angularDomainWithPadding[1] += angularDomainStep;
  54004. var tickCount = axisConfig.angularAxis.ticksCount || 4;
  54005. if (tickCount > 8) tickCount = tickCount / (tickCount / 8) + tickCount % 8;
  54006. if (axisConfig.angularAxis.ticksStep) {
  54007. tickCount = (angularDomainWithPadding[1] - angularDomainWithPadding[0]) / tickCount;
  54008. }
  54009. var angularTicksStep = axisConfig.angularAxis.ticksStep || (angularDomainWithPadding[1] - angularDomainWithPadding[0]) / (tickCount * (axisConfig.minorTicks + 1));
  54010. if (ticks) angularTicksStep = Math.max(Math.round(angularTicksStep), 1);
  54011. if (!angularDomainWithPadding[2]) angularDomainWithPadding[2] = angularTicksStep;
  54012. var angularAxisRange = d3.range.apply(this, angularDomainWithPadding);
  54013. angularAxisRange = angularAxisRange.map(function(d, i) {
  54014. return parseFloat(d.toPrecision(12));
  54015. });
  54016. angularScale = d3.scale.linear().domain(angularDomainWithPadding.slice(0, 2)).range(axisConfig.direction === 'clockwise' ? [ 0, 360 ] : [ 360, 0 ]);
  54017. liveConfig.layout.angularAxis.domain = angularScale.domain();
  54018. liveConfig.layout.angularAxis.endPadding = needsEndSpacing ? angularDomainStep : 0;
  54019. svg = d3.select(this).select('svg.chart-root');
  54020. if (typeof svg === 'undefined' || svg.empty()) {
  54021. var skeleton = "<svg xmlns='http://www.w3.org/2000/svg' class='chart-root'>' + '<g class='outer-group'>' + '<g class='chart-group'>' + '<circle class='background-circle'></circle>' + '<g class='geometry-group'></g>' + '<g class='radial axis-group'>' + '<circle class='outside-circle'></circle>' + '</g>' + '<g class='angular axis-group'></g>' + '<g class='guides-group'><line></line><circle r='0'></circle></g>' + '</g>' + '<g class='legend-group'></g>' + '<g class='tooltips-group'></g>' + '<g class='title-group'><text></text></g>' + '</g>' + '</svg>";
  54022. var doc = new DOMParser().parseFromString(skeleton, 'application/xml');
  54023. var newSvg = this.appendChild(this.ownerDocument.importNode(doc.documentElement, true));
  54024. svg = d3.select(newSvg);
  54025. }
  54026. svg.select('.guides-group').style({
  54027. 'pointer-events': 'none'
  54028. });
  54029. svg.select('.angular.axis-group').style({
  54030. 'pointer-events': 'none'
  54031. });
  54032. svg.select('.radial.axis-group').style({
  54033. 'pointer-events': 'none'
  54034. });
  54035. var chartGroup = svg.select('.chart-group');
  54036. var lineStyle = {
  54037. fill: 'none',
  54038. stroke: axisConfig.tickColor
  54039. };
  54040. var fontStyle = {
  54041. 'font-size': axisConfig.font.size,
  54042. 'font-family': axisConfig.font.family,
  54043. fill: axisConfig.font.color,
  54044. 'text-shadow': [ '-1px 0px', '1px -1px', '-1px 1px', '1px 1px' ].map(function(d, i) {
  54045. return ' ' + d + ' 0 ' + axisConfig.font.outlineColor;
  54046. }).join(',')
  54047. };
  54048. var legendContainer;
  54049. if (axisConfig.showLegend) {
  54050. legendContainer = svg.select('.legend-group').attr({
  54051. transform: 'translate(' + [ radius, axisConfig.margin.top ] + ')'
  54052. }).style({
  54053. display: 'block'
  54054. });
  54055. var elements = data.map(function(d, i) {
  54056. var datumClone = µ.util.cloneJson(d);
  54057. datumClone.symbol = d.geometry === 'DotPlot' ? d.dotType || 'circle' : d.geometry != 'LinePlot' ? 'square' : 'line';
  54058. datumClone.visibleInLegend = typeof d.visibleInLegend === 'undefined' || d.visibleInLegend;
  54059. datumClone.color = d.geometry === 'LinePlot' ? d.strokeColor : d.color;
  54060. return datumClone;
  54061. });
  54062. µ.Legend().config({
  54063. data: data.map(function(d, i) {
  54064. return d.name || 'Element' + i;
  54065. }),
  54066. legendConfig: extendDeepAll({},
  54067. µ.Legend.defaultConfig().legendConfig,
  54068. {
  54069. container: legendContainer,
  54070. elements: elements,
  54071. reverseOrder: axisConfig.legend.reverseOrder
  54072. }
  54073. )
  54074. })();
  54075. var legendBBox = legendContainer.node().getBBox();
  54076. radius = Math.min(axisConfig.width - legendBBox.width - axisConfig.margin.left - axisConfig.margin.right, axisConfig.height - axisConfig.margin.top - axisConfig.margin.bottom) / 2;
  54077. radius = Math.max(10, radius);
  54078. chartCenter = [ axisConfig.margin.left + radius, axisConfig.margin.top + radius ];
  54079. radialScale.range([ 0, radius ]);
  54080. liveConfig.layout.radialAxis.domain = radialScale.domain();
  54081. legendContainer.attr('transform', 'translate(' + [ chartCenter[0] + radius, chartCenter[1] - radius ] + ')');
  54082. } else {
  54083. legendContainer = svg.select('.legend-group').style({
  54084. display: 'none'
  54085. });
  54086. }
  54087. svg.attr({
  54088. width: axisConfig.width,
  54089. height: axisConfig.height
  54090. }).style({
  54091. opacity: axisConfig.opacity
  54092. });
  54093. chartGroup.attr('transform', 'translate(' + chartCenter + ')').style({
  54094. cursor: 'crosshair'
  54095. });
  54096. var centeringOffset = [ (axisConfig.width - (axisConfig.margin.left + axisConfig.margin.right + radius * 2 + (legendBBox ? legendBBox.width : 0))) / 2, (axisConfig.height - (axisConfig.margin.top + axisConfig.margin.bottom + radius * 2)) / 2 ];
  54097. centeringOffset[0] = Math.max(0, centeringOffset[0]);
  54098. centeringOffset[1] = Math.max(0, centeringOffset[1]);
  54099. svg.select('.outer-group').attr('transform', 'translate(' + centeringOffset + ')');
  54100. if (axisConfig.title && axisConfig.title.text) {
  54101. var title = svg.select('g.title-group text').style(fontStyle).text(axisConfig.title.text);
  54102. var titleBBox = title.node().getBBox();
  54103. title.attr({
  54104. x: chartCenter[0] - titleBBox.width / 2,
  54105. y: chartCenter[1] - radius - 20
  54106. });
  54107. }
  54108. var radialAxis = svg.select('.radial.axis-group');
  54109. if (axisConfig.radialAxis.gridLinesVisible) {
  54110. var gridCircles = radialAxis.selectAll('circle.grid-circle').data(radialScale.ticks(5));
  54111. gridCircles.enter().append('circle').attr({
  54112. 'class': 'grid-circle'
  54113. }).style(lineStyle);
  54114. gridCircles.attr('r', radialScale);
  54115. gridCircles.exit().remove();
  54116. }
  54117. radialAxis.select('circle.outside-circle').attr({
  54118. r: radius
  54119. }).style(lineStyle);
  54120. var backgroundCircle = svg.select('circle.background-circle').attr({
  54121. r: radius
  54122. }).style({
  54123. fill: axisConfig.backgroundColor,
  54124. stroke: axisConfig.stroke
  54125. });
  54126. function currentAngle(d, i) {
  54127. return angularScale(d) % 360 + axisConfig.orientation;
  54128. }
  54129. if (axisConfig.radialAxis.visible) {
  54130. var axis = d3.svg.axis().scale(radialScale).ticks(5).tickSize(5);
  54131. radialAxis.call(axis).attr({
  54132. transform: 'rotate(' + axisConfig.radialAxis.orientation + ')'
  54133. });
  54134. radialAxis.selectAll('.domain').style(lineStyle);
  54135. radialAxis.selectAll('g>text').text(function(d, i) {
  54136. return this.textContent + axisConfig.radialAxis.ticksSuffix;
  54137. }).style(fontStyle).style({
  54138. 'text-anchor': 'start'
  54139. }).attr({
  54140. x: 0,
  54141. y: 0,
  54142. dx: 0,
  54143. dy: 0,
  54144. transform: function(d, i) {
  54145. if (axisConfig.radialAxis.tickOrientation === 'horizontal') {
  54146. return 'rotate(' + -axisConfig.radialAxis.orientation + ') translate(' + [ 0, fontStyle['font-size'] ] + ')';
  54147. } else return 'translate(' + [ 0, fontStyle['font-size'] ] + ')';
  54148. }
  54149. });
  54150. radialAxis.selectAll('g>line').style({
  54151. stroke: 'black'
  54152. });
  54153. }
  54154. var angularAxis = svg.select('.angular.axis-group').selectAll('g.angular-tick').data(angularAxisRange);
  54155. var angularAxisEnter = angularAxis.enter().append('g').classed('angular-tick', true);
  54156. angularAxis.attr({
  54157. transform: function(d, i) {
  54158. return 'rotate(' + currentAngle(d, i) + ')';
  54159. }
  54160. }).style({
  54161. display: axisConfig.angularAxis.visible ? 'block' : 'none'
  54162. });
  54163. angularAxis.exit().remove();
  54164. angularAxisEnter.append('line').classed('grid-line', true).classed('major', function(d, i) {
  54165. return i % (axisConfig.minorTicks + 1) == 0;
  54166. }).classed('minor', function(d, i) {
  54167. return !(i % (axisConfig.minorTicks + 1) == 0);
  54168. }).style(lineStyle);
  54169. angularAxisEnter.selectAll('.minor').style({
  54170. stroke: axisConfig.minorTickColor
  54171. });
  54172. angularAxis.select('line.grid-line').attr({
  54173. x1: axisConfig.tickLength ? radius - axisConfig.tickLength : 0,
  54174. x2: radius
  54175. }).style({
  54176. display: axisConfig.angularAxis.gridLinesVisible ? 'block' : 'none'
  54177. });
  54178. angularAxisEnter.append('text').classed('axis-text', true).style(fontStyle);
  54179. var ticksText = angularAxis.select('text.axis-text').attr({
  54180. x: radius + axisConfig.labelOffset,
  54181. dy: MID_SHIFT + 'em',
  54182. transform: function(d, i) {
  54183. var angle = currentAngle(d, i);
  54184. var rad = radius + axisConfig.labelOffset;
  54185. var orient = axisConfig.angularAxis.tickOrientation;
  54186. if (orient == 'horizontal') return 'rotate(' + -angle + ' ' + rad + ' 0)'; else if (orient == 'radial') return angle < 270 && angle > 90 ? 'rotate(180 ' + rad + ' 0)' : null; else return 'rotate(' + (angle <= 180 && angle > 0 ? -90 : 90) + ' ' + rad + ' 0)';
  54187. }
  54188. }).style({
  54189. 'text-anchor': 'middle',
  54190. display: axisConfig.angularAxis.labelsVisible ? 'block' : 'none'
  54191. }).text(function(d, i) {
  54192. if (i % (axisConfig.minorTicks + 1) != 0) return '';
  54193. if (ticks) {
  54194. return ticks[d] + axisConfig.angularAxis.ticksSuffix;
  54195. } else return d + axisConfig.angularAxis.ticksSuffix;
  54196. }).style(fontStyle);
  54197. if (axisConfig.angularAxis.rewriteTicks) ticksText.text(function(d, i) {
  54198. if (i % (axisConfig.minorTicks + 1) != 0) return '';
  54199. return axisConfig.angularAxis.rewriteTicks(this.textContent, i);
  54200. });
  54201. var rightmostTickEndX = d3.max(chartGroup.selectAll('.angular-tick text')[0].map(function(d, i) {
  54202. return d.getCTM().e + d.getBBox().width;
  54203. }));
  54204. legendContainer.attr({
  54205. transform: 'translate(' + [ radius + rightmostTickEndX, axisConfig.margin.top ] + ')'
  54206. });
  54207. var hasGeometry = svg.select('g.geometry-group').selectAll('g').size() > 0;
  54208. var geometryContainer = svg.select('g.geometry-group').selectAll('g.geometry').data(data);
  54209. geometryContainer.enter().append('g').attr({
  54210. 'class': function(d, i) {
  54211. return 'geometry geometry' + i;
  54212. }
  54213. });
  54214. geometryContainer.exit().remove();
  54215. if (data[0] || hasGeometry) {
  54216. var geometryConfigs = [];
  54217. data.forEach(function(d, i) {
  54218. var geometryConfig = {};
  54219. geometryConfig.radialScale = radialScale;
  54220. geometryConfig.angularScale = angularScale;
  54221. geometryConfig.container = geometryContainer.filter(function(dB, iB) {
  54222. return iB == i;
  54223. });
  54224. geometryConfig.geometry = d.geometry;
  54225. geometryConfig.orientation = axisConfig.orientation;
  54226. geometryConfig.direction = axisConfig.direction;
  54227. geometryConfig.index = i;
  54228. geometryConfigs.push({
  54229. data: d,
  54230. geometryConfig: geometryConfig
  54231. });
  54232. });
  54233. var geometryConfigsGrouped = d3.nest().key(function(d, i) {
  54234. return typeof d.data.groupId != 'undefined' || 'unstacked';
  54235. }).entries(geometryConfigs);
  54236. var geometryConfigsGrouped2 = [];
  54237. geometryConfigsGrouped.forEach(function(d, i) {
  54238. if (d.key === 'unstacked') geometryConfigsGrouped2 = geometryConfigsGrouped2.concat(d.values.map(function(d, i) {
  54239. return [ d ];
  54240. })); else geometryConfigsGrouped2.push(d.values);
  54241. });
  54242. geometryConfigsGrouped2.forEach(function(d, i) {
  54243. var geometry;
  54244. if (Array.isArray(d)) geometry = d[0].geometryConfig.geometry; else geometry = d.geometryConfig.geometry;
  54245. var finalGeometryConfig = d.map(function(dB, iB) {
  54246. return extendDeepAll(µ[geometry].defaultConfig(), dB);
  54247. });
  54248. µ[geometry]().config(finalGeometryConfig)();
  54249. });
  54250. }
  54251. var guides = svg.select('.guides-group');
  54252. var tooltipContainer = svg.select('.tooltips-group');
  54253. var angularTooltip = µ.tooltipPanel().config({
  54254. container: tooltipContainer,
  54255. fontSize: 8
  54256. })();
  54257. var radialTooltip = µ.tooltipPanel().config({
  54258. container: tooltipContainer,
  54259. fontSize: 8
  54260. })();
  54261. var geometryTooltip = µ.tooltipPanel().config({
  54262. container: tooltipContainer,
  54263. hasTick: true
  54264. })();
  54265. var angularValue, radialValue;
  54266. if (!isOrdinal) {
  54267. var angularGuideLine = guides.select('line').attr({
  54268. x1: 0,
  54269. y1: 0,
  54270. y2: 0
  54271. }).style({
  54272. stroke: 'grey',
  54273. 'pointer-events': 'none'
  54274. });
  54275. chartGroup.on('mousemove.angular-guide', function(d, i) {
  54276. var mouseAngle = µ.util.getMousePos(backgroundCircle).angle;
  54277. angularGuideLine.attr({
  54278. x2: -radius,
  54279. transform: 'rotate(' + mouseAngle + ')'
  54280. }).style({
  54281. opacity: .5
  54282. });
  54283. var angleWithOriginOffset = (mouseAngle + 180 + 360 - axisConfig.orientation) % 360;
  54284. angularValue = angularScale.invert(angleWithOriginOffset);
  54285. var pos = µ.util.convertToCartesian(radius + 12, mouseAngle + 180);
  54286. angularTooltip.text(µ.util.round(angularValue)).move([ pos[0] + chartCenter[0], pos[1] + chartCenter[1] ]);
  54287. }).on('mouseout.angular-guide', function(d, i) {
  54288. guides.select('line').style({
  54289. opacity: 0
  54290. });
  54291. });
  54292. }
  54293. var angularGuideCircle = guides.select('circle').style({
  54294. stroke: 'grey',
  54295. fill: 'none'
  54296. });
  54297. chartGroup.on('mousemove.radial-guide', function(d, i) {
  54298. var r = µ.util.getMousePos(backgroundCircle).radius;
  54299. angularGuideCircle.attr({
  54300. r: r
  54301. }).style({
  54302. opacity: .5
  54303. });
  54304. radialValue = radialScale.invert(µ.util.getMousePos(backgroundCircle).radius);
  54305. var pos = µ.util.convertToCartesian(r, axisConfig.radialAxis.orientation);
  54306. radialTooltip.text(µ.util.round(radialValue)).move([ pos[0] + chartCenter[0], pos[1] + chartCenter[1] ]);
  54307. }).on('mouseout.radial-guide', function(d, i) {
  54308. angularGuideCircle.style({
  54309. opacity: 0
  54310. });
  54311. geometryTooltip.hide();
  54312. angularTooltip.hide();
  54313. radialTooltip.hide();
  54314. });
  54315. svg.selectAll('.geometry-group .mark').on('mouseover.tooltip', function(d, i) {
  54316. var el = d3.select(this);
  54317. var color = this.style.fill;
  54318. var newColor = 'black';
  54319. var opacity = this.style.opacity || 1;
  54320. el.attr({
  54321. 'data-opacity': opacity
  54322. });
  54323. if (color && color !== 'none') {
  54324. el.attr({
  54325. 'data-fill': color
  54326. });
  54327. newColor = d3.hsl(color).darker().toString();
  54328. el.style({
  54329. fill: newColor,
  54330. opacity: 1
  54331. });
  54332. var textData = {
  54333. t: µ.util.round(d[0]),
  54334. r: µ.util.round(d[1])
  54335. };
  54336. if (isOrdinal) textData.t = ticks[d[0]];
  54337. var text = 't: ' + textData.t + ', r: ' + textData.r;
  54338. var bbox = this.getBoundingClientRect();
  54339. var svgBBox = svg.node().getBoundingClientRect();
  54340. var pos = [ bbox.left + bbox.width / 2 - centeringOffset[0] - svgBBox.left, bbox.top + bbox.height / 2 - centeringOffset[1] - svgBBox.top ];
  54341. geometryTooltip.config({
  54342. color: newColor
  54343. }).text(text);
  54344. geometryTooltip.move(pos);
  54345. } else {
  54346. color = this.style.stroke || 'black';
  54347. el.attr({
  54348. 'data-stroke': color
  54349. });
  54350. newColor = d3.hsl(color).darker().toString();
  54351. el.style({
  54352. stroke: newColor,
  54353. opacity: 1
  54354. });
  54355. }
  54356. }).on('mousemove.tooltip', function(d, i) {
  54357. if (d3.event.which != 0) return false;
  54358. if (d3.select(this).attr('data-fill')) geometryTooltip.show();
  54359. }).on('mouseout.tooltip', function(d, i) {
  54360. geometryTooltip.hide();
  54361. var el = d3.select(this);
  54362. var fillColor = el.attr('data-fill');
  54363. if (fillColor) el.style({
  54364. fill: fillColor,
  54365. opacity: el.attr('data-opacity')
  54366. }); else el.style({
  54367. stroke: el.attr('data-stroke'),
  54368. opacity: el.attr('data-opacity')
  54369. });
  54370. });
  54371. });
  54372. return exports;
  54373. }
  54374. exports.render = function(_container) {
  54375. render(_container);
  54376. return this;
  54377. };
  54378. exports.config = function(_x) {
  54379. if (!arguments.length) return config;
  54380. var xClone = µ.util.cloneJson(_x);
  54381. xClone.data.forEach(function(d, i) {
  54382. if (!config.data[i]) config.data[i] = {};
  54383. extendDeepAll(config.data[i], µ.Axis.defaultConfig().data[0]);
  54384. extendDeepAll(config.data[i], d);
  54385. });
  54386. extendDeepAll(config.layout, µ.Axis.defaultConfig().layout);
  54387. extendDeepAll(config.layout, xClone.layout);
  54388. return this;
  54389. };
  54390. exports.getLiveConfig = function() {
  54391. return liveConfig;
  54392. };
  54393. exports.getinputConfig = function() {
  54394. return inputConfig;
  54395. };
  54396. exports.radialScale = function(_x) {
  54397. return radialScale;
  54398. };
  54399. exports.angularScale = function(_x) {
  54400. return angularScale;
  54401. };
  54402. exports.svg = function() {
  54403. return svg;
  54404. };
  54405. d3.rebind(exports, dispatch, 'on');
  54406. return exports;
  54407. };
  54408. µ.Axis.defaultConfig = function(d, i) {
  54409. var config = {
  54410. data: [ {
  54411. t: [ 1, 2, 3, 4 ],
  54412. r: [ 10, 11, 12, 13 ],
  54413. name: 'Line1',
  54414. geometry: 'LinePlot',
  54415. color: null,
  54416. strokeDash: 'solid',
  54417. strokeColor: null,
  54418. strokeSize: '1',
  54419. visibleInLegend: true,
  54420. opacity: 1
  54421. } ],
  54422. layout: {
  54423. defaultColorRange: d3.scale.category10().range(),
  54424. title: null,
  54425. height: 450,
  54426. width: 500,
  54427. margin: {
  54428. top: 40,
  54429. right: 40,
  54430. bottom: 40,
  54431. left: 40
  54432. },
  54433. font: {
  54434. size: 12,
  54435. color: 'gray',
  54436. outlineColor: 'white',
  54437. family: 'Tahoma, sans-serif'
  54438. },
  54439. direction: 'clockwise',
  54440. orientation: 0,
  54441. labelOffset: 10,
  54442. radialAxis: {
  54443. domain: null,
  54444. orientation: -45,
  54445. ticksSuffix: '',
  54446. visible: true,
  54447. gridLinesVisible: true,
  54448. tickOrientation: 'horizontal',
  54449. rewriteTicks: null
  54450. },
  54451. angularAxis: {
  54452. domain: [ 0, 360 ],
  54453. ticksSuffix: '',
  54454. visible: true,
  54455. gridLinesVisible: true,
  54456. labelsVisible: true,
  54457. tickOrientation: 'horizontal',
  54458. rewriteTicks: null,
  54459. ticksCount: null,
  54460. ticksStep: null
  54461. },
  54462. minorTicks: 0,
  54463. tickLength: null,
  54464. tickColor: 'silver',
  54465. minorTickColor: '#eee',
  54466. backgroundColor: 'none',
  54467. needsEndSpacing: null,
  54468. showLegend: true,
  54469. legend: {
  54470. reverseOrder: false
  54471. },
  54472. opacity: 1
  54473. }
  54474. };
  54475. return config;
  54476. };
  54477. µ.util = {};
  54478. µ.DATAEXTENT = 'dataExtent';
  54479. µ.AREA = 'AreaChart';
  54480. µ.LINE = 'LinePlot';
  54481. µ.DOT = 'DotPlot';
  54482. µ.BAR = 'BarChart';
  54483. µ.util._override = function(_objA, _objB) {
  54484. for (var x in _objA) if (x in _objB) _objB[x] = _objA[x];
  54485. };
  54486. µ.util._extend = function(_objA, _objB) {
  54487. for (var x in _objA) _objB[x] = _objA[x];
  54488. };
  54489. µ.util._rndSnd = function() {
  54490. return Math.random() * 2 - 1 + (Math.random() * 2 - 1) + (Math.random() * 2 - 1);
  54491. };
  54492. µ.util.dataFromEquation2 = function(_equation, _step) {
  54493. var step = _step || 6;
  54494. var data = d3.range(0, 360 + step, step).map(function(deg, index) {
  54495. var theta = deg * Math.PI / 180;
  54496. var radius = _equation(theta);
  54497. return [ deg, radius ];
  54498. });
  54499. return data;
  54500. };
  54501. µ.util.dataFromEquation = function(_equation, _step, _name) {
  54502. var step = _step || 6;
  54503. var t = [], r = [];
  54504. d3.range(0, 360 + step, step).forEach(function(deg, index) {
  54505. var theta = deg * Math.PI / 180;
  54506. var radius = _equation(theta);
  54507. t.push(deg);
  54508. r.push(radius);
  54509. });
  54510. var result = {
  54511. t: t,
  54512. r: r
  54513. };
  54514. if (_name) result.name = _name;
  54515. return result;
  54516. };
  54517. µ.util.ensureArray = function(_val, _count) {
  54518. if (typeof _val === 'undefined') return null;
  54519. var arr = [].concat(_val);
  54520. return d3.range(_count).map(function(d, i) {
  54521. return arr[i] || arr[0];
  54522. });
  54523. };
  54524. µ.util.fillArrays = function(_obj, _valueNames, _count) {
  54525. _valueNames.forEach(function(d, i) {
  54526. _obj[d] = µ.util.ensureArray(_obj[d], _count);
  54527. });
  54528. return _obj;
  54529. };
  54530. µ.util.cloneJson = function(json) {
  54531. return JSON.parse(JSON.stringify(json));
  54532. };
  54533. µ.util.validateKeys = function(obj, keys) {
  54534. if (typeof keys === 'string') keys = keys.split('.');
  54535. var next = keys.shift();
  54536. return obj[next] && (!keys.length || objHasKeys(obj[next], keys));
  54537. };
  54538. µ.util.sumArrays = function(a, b) {
  54539. return d3.zip(a, b).map(function(d, i) {
  54540. return d3.sum(d);
  54541. });
  54542. };
  54543. µ.util.arrayLast = function(a) {
  54544. return a[a.length - 1];
  54545. };
  54546. µ.util.arrayEqual = function(a, b) {
  54547. var i = Math.max(a.length, b.length, 1);
  54548. while (i-- >= 0 && a[i] === b[i]) ;
  54549. return i === -2;
  54550. };
  54551. µ.util.flattenArray = function(arr) {
  54552. var r = [];
  54553. while (!µ.util.arrayEqual(r, arr)) {
  54554. r = arr;
  54555. arr = [].concat.apply([], arr);
  54556. }
  54557. return arr;
  54558. };
  54559. µ.util.deduplicate = function(arr) {
  54560. return arr.filter(function(v, i, a) {
  54561. return a.indexOf(v) == i;
  54562. });
  54563. };
  54564. µ.util.convertToCartesian = function(radius, theta) {
  54565. var thetaRadians = theta * Math.PI / 180;
  54566. var x = radius * Math.cos(thetaRadians);
  54567. var y = radius * Math.sin(thetaRadians);
  54568. return [ x, y ];
  54569. };
  54570. µ.util.round = function(_value, _digits) {
  54571. var digits = _digits || 2;
  54572. var mult = Math.pow(10, digits);
  54573. return Math.round(_value * mult) / mult;
  54574. };
  54575. µ.util.getMousePos = function(_referenceElement) {
  54576. var mousePos = d3.mouse(_referenceElement.node());
  54577. var mouseX = mousePos[0];
  54578. var mouseY = mousePos[1];
  54579. var mouse = {};
  54580. mouse.x = mouseX;
  54581. mouse.y = mouseY;
  54582. mouse.pos = mousePos;
  54583. mouse.angle = (Math.atan2(mouseY, mouseX) + Math.PI) * 180 / Math.PI;
  54584. mouse.radius = Math.sqrt(mouseX * mouseX + mouseY * mouseY);
  54585. return mouse;
  54586. };
  54587. µ.util.duplicatesCount = function(arr) {
  54588. var uniques = {}, val;
  54589. var dups = {};
  54590. for (var i = 0, len = arr.length; i < len; i++) {
  54591. val = arr[i];
  54592. if (val in uniques) {
  54593. uniques[val]++;
  54594. dups[val] = uniques[val];
  54595. } else {
  54596. uniques[val] = 1;
  54597. }
  54598. }
  54599. return dups;
  54600. };
  54601. µ.util.duplicates = function(arr) {
  54602. return Object.keys(µ.util.duplicatesCount(arr));
  54603. };
  54604. µ.util.translator = function(obj, sourceBranch, targetBranch, reverse) {
  54605. if (reverse) {
  54606. var targetBranchCopy = targetBranch.slice();
  54607. targetBranch = sourceBranch;
  54608. sourceBranch = targetBranchCopy;
  54609. }
  54610. var value = sourceBranch.reduce(function(previousValue, currentValue) {
  54611. if (typeof previousValue != 'undefined') return previousValue[currentValue];
  54612. }, obj);
  54613. if (typeof value === 'undefined') return;
  54614. sourceBranch.reduce(function(previousValue, currentValue, index) {
  54615. if (typeof previousValue == 'undefined') return;
  54616. if (index === sourceBranch.length - 1) delete previousValue[currentValue];
  54617. return previousValue[currentValue];
  54618. }, obj);
  54619. targetBranch.reduce(function(previousValue, currentValue, index) {
  54620. if (typeof previousValue[currentValue] === 'undefined') previousValue[currentValue] = {};
  54621. if (index === targetBranch.length - 1) previousValue[currentValue] = value;
  54622. return previousValue[currentValue];
  54623. }, obj);
  54624. };
  54625. µ.PolyChart = function module() {
  54626. var config = [ µ.PolyChart.defaultConfig() ];
  54627. var dispatch = d3.dispatch('hover');
  54628. var dashArray = {
  54629. solid: 'none',
  54630. dash: [ 5, 2 ],
  54631. dot: [ 2, 5 ]
  54632. };
  54633. var colorScale;
  54634. function exports() {
  54635. var geometryConfig = config[0].geometryConfig;
  54636. var container = geometryConfig.container;
  54637. if (typeof container == 'string') container = d3.select(container);
  54638. container.datum(config).each(function(_config, _index) {
  54639. var isStack = !!_config[0].data.yStack;
  54640. var data = _config.map(function(d, i) {
  54641. if (isStack) return d3.zip(d.data.t[0], d.data.r[0], d.data.yStack[0]); else return d3.zip(d.data.t[0], d.data.r[0]);
  54642. });
  54643. var angularScale = geometryConfig.angularScale;
  54644. var domainMin = geometryConfig.radialScale.domain()[0];
  54645. var generator = {};
  54646. generator.bar = function(d, i, pI) {
  54647. var dataConfig = _config[pI].data;
  54648. var h = geometryConfig.radialScale(d[1]) - geometryConfig.radialScale(0);
  54649. var stackTop = geometryConfig.radialScale(d[2] || 0);
  54650. var w = dataConfig.barWidth;
  54651. d3.select(this).attr({
  54652. 'class': 'mark bar',
  54653. d: 'M' + [ [ h + stackTop, -w / 2 ], [ h + stackTop, w / 2 ], [ stackTop, w / 2 ], [ stackTop, -w / 2 ] ].join('L') + 'Z',
  54654. transform: function(d, i) {
  54655. return 'rotate(' + (geometryConfig.orientation + angularScale(d[0])) + ')';
  54656. }
  54657. });
  54658. };
  54659. generator.dot = function(d, i, pI) {
  54660. var stackedData = d[2] ? [ d[0], d[1] + d[2] ] : d;
  54661. var symbol = d3.svg.symbol().size(_config[pI].data.dotSize).type(_config[pI].data.dotType)(d, i);
  54662. d3.select(this).attr({
  54663. 'class': 'mark dot',
  54664. d: symbol,
  54665. transform: function(d, i) {
  54666. var coord = convertToCartesian(getPolarCoordinates(stackedData));
  54667. return 'translate(' + [ coord.x, coord.y ] + ')';
  54668. }
  54669. });
  54670. };
  54671. var line = d3.svg.line.radial().interpolate(_config[0].data.lineInterpolation).radius(function(d) {
  54672. return geometryConfig.radialScale(d[1]);
  54673. }).angle(function(d) {
  54674. return geometryConfig.angularScale(d[0]) * Math.PI / 180;
  54675. });
  54676. generator.line = function(d, i, pI) {
  54677. var lineData = d[2] ? data[pI].map(function(d, i) {
  54678. return [ d[0], d[1] + d[2] ];
  54679. }) : data[pI];
  54680. d3.select(this).each(generator['dot']).style({
  54681. opacity: function(dB, iB) {
  54682. return +_config[pI].data.dotVisible;
  54683. },
  54684. fill: markStyle.stroke(d, i, pI)
  54685. }).attr({
  54686. 'class': 'mark dot'
  54687. });
  54688. if (i > 0) return;
  54689. var lineSelection = d3.select(this.parentNode).selectAll('path.line').data([ 0 ]);
  54690. lineSelection.enter().insert('path');
  54691. lineSelection.attr({
  54692. 'class': 'line',
  54693. d: line(lineData),
  54694. transform: function(dB, iB) {
  54695. return 'rotate(' + (geometryConfig.orientation + 90) + ')';
  54696. },
  54697. 'pointer-events': 'none'
  54698. }).style({
  54699. fill: function(dB, iB) {
  54700. return markStyle.fill(d, i, pI);
  54701. },
  54702. 'fill-opacity': 0,
  54703. stroke: function(dB, iB) {
  54704. return markStyle.stroke(d, i, pI);
  54705. },
  54706. 'stroke-width': function(dB, iB) {
  54707. return markStyle['stroke-width'](d, i, pI);
  54708. },
  54709. 'stroke-dasharray': function(dB, iB) {
  54710. return markStyle['stroke-dasharray'](d, i, pI);
  54711. },
  54712. opacity: function(dB, iB) {
  54713. return markStyle.opacity(d, i, pI);
  54714. },
  54715. display: function(dB, iB) {
  54716. return markStyle.display(d, i, pI);
  54717. }
  54718. });
  54719. };
  54720. var angularRange = geometryConfig.angularScale.range();
  54721. var triangleAngle = Math.abs(angularRange[1] - angularRange[0]) / data[0].length * Math.PI / 180;
  54722. var arc = d3.svg.arc().startAngle(function(d) {
  54723. return -triangleAngle / 2;
  54724. }).endAngle(function(d) {
  54725. return triangleAngle / 2;
  54726. }).innerRadius(function(d) {
  54727. return geometryConfig.radialScale(domainMin + (d[2] || 0));
  54728. }).outerRadius(function(d) {
  54729. return geometryConfig.radialScale(domainMin + (d[2] || 0)) + geometryConfig.radialScale(d[1]);
  54730. });
  54731. generator.arc = function(d, i, pI) {
  54732. d3.select(this).attr({
  54733. 'class': 'mark arc',
  54734. d: arc,
  54735. transform: function(d, i) {
  54736. return 'rotate(' + (geometryConfig.orientation + angularScale(d[0]) + 90) + ')';
  54737. }
  54738. });
  54739. };
  54740. var markStyle = {
  54741. fill: function(d, i, pI) {
  54742. return _config[pI].data.color;
  54743. },
  54744. stroke: function(d, i, pI) {
  54745. return _config[pI].data.strokeColor;
  54746. },
  54747. 'stroke-width': function(d, i, pI) {
  54748. return _config[pI].data.strokeSize + 'px';
  54749. },
  54750. 'stroke-dasharray': function(d, i, pI) {
  54751. return dashArray[_config[pI].data.strokeDash];
  54752. },
  54753. opacity: function(d, i, pI) {
  54754. return _config[pI].data.opacity;
  54755. },
  54756. display: function(d, i, pI) {
  54757. return typeof _config[pI].data.visible === 'undefined' || _config[pI].data.visible ? 'block' : 'none';
  54758. }
  54759. };
  54760. var geometryLayer = d3.select(this).selectAll('g.layer').data(data);
  54761. geometryLayer.enter().append('g').attr({
  54762. 'class': 'layer'
  54763. });
  54764. var geometry = geometryLayer.selectAll('path.mark').data(function(d, i) {
  54765. return d;
  54766. });
  54767. geometry.enter().append('path').attr({
  54768. 'class': 'mark'
  54769. });
  54770. geometry.style(markStyle).each(generator[geometryConfig.geometryType]);
  54771. geometry.exit().remove();
  54772. geometryLayer.exit().remove();
  54773. function getPolarCoordinates(d, i) {
  54774. var r = geometryConfig.radialScale(d[1]);
  54775. var t = (geometryConfig.angularScale(d[0]) + geometryConfig.orientation) * Math.PI / 180;
  54776. return {
  54777. r: r,
  54778. t: t
  54779. };
  54780. }
  54781. function convertToCartesian(polarCoordinates) {
  54782. var x = polarCoordinates.r * Math.cos(polarCoordinates.t);
  54783. var y = polarCoordinates.r * Math.sin(polarCoordinates.t);
  54784. return {
  54785. x: x,
  54786. y: y
  54787. };
  54788. }
  54789. });
  54790. }
  54791. exports.config = function(_x) {
  54792. if (!arguments.length) return config;
  54793. _x.forEach(function(d, i) {
  54794. if (!config[i]) config[i] = {};
  54795. extendDeepAll(config[i], µ.PolyChart.defaultConfig());
  54796. extendDeepAll(config[i], d);
  54797. });
  54798. return this;
  54799. };
  54800. exports.getColorScale = function() {
  54801. return colorScale;
  54802. };
  54803. d3.rebind(exports, dispatch, 'on');
  54804. return exports;
  54805. };
  54806. µ.PolyChart.defaultConfig = function() {
  54807. var config = {
  54808. data: {
  54809. name: 'geom1',
  54810. t: [ [ 1, 2, 3, 4 ] ],
  54811. r: [ [ 1, 2, 3, 4 ] ],
  54812. dotType: 'circle',
  54813. dotSize: 64,
  54814. dotVisible: false,
  54815. barWidth: 20,
  54816. color: '#ffa500',
  54817. strokeSize: 1,
  54818. strokeColor: 'silver',
  54819. strokeDash: 'solid',
  54820. opacity: 1,
  54821. index: 0,
  54822. visible: true,
  54823. visibleInLegend: true
  54824. },
  54825. geometryConfig: {
  54826. geometry: 'LinePlot',
  54827. geometryType: 'arc',
  54828. direction: 'clockwise',
  54829. orientation: 0,
  54830. container: 'body',
  54831. radialScale: null,
  54832. angularScale: null,
  54833. colorScale: d3.scale.category20()
  54834. }
  54835. };
  54836. return config;
  54837. };
  54838. µ.BarChart = function module() {
  54839. return µ.PolyChart();
  54840. };
  54841. µ.BarChart.defaultConfig = function() {
  54842. var config = {
  54843. geometryConfig: {
  54844. geometryType: 'bar'
  54845. }
  54846. };
  54847. return config;
  54848. };
  54849. µ.AreaChart = function module() {
  54850. return µ.PolyChart();
  54851. };
  54852. µ.AreaChart.defaultConfig = function() {
  54853. var config = {
  54854. geometryConfig: {
  54855. geometryType: 'arc'
  54856. }
  54857. };
  54858. return config;
  54859. };
  54860. µ.DotPlot = function module() {
  54861. return µ.PolyChart();
  54862. };
  54863. µ.DotPlot.defaultConfig = function() {
  54864. var config = {
  54865. geometryConfig: {
  54866. geometryType: 'dot',
  54867. dotType: 'circle'
  54868. }
  54869. };
  54870. return config;
  54871. };
  54872. µ.LinePlot = function module() {
  54873. return µ.PolyChart();
  54874. };
  54875. µ.LinePlot.defaultConfig = function() {
  54876. var config = {
  54877. geometryConfig: {
  54878. geometryType: 'line'
  54879. }
  54880. };
  54881. return config;
  54882. };
  54883. µ.Legend = function module() {
  54884. var config = µ.Legend.defaultConfig();
  54885. var dispatch = d3.dispatch('hover');
  54886. function exports() {
  54887. var legendConfig = config.legendConfig;
  54888. var flattenData = config.data.map(function(d, i) {
  54889. return [].concat(d).map(function(dB, iB) {
  54890. var element = extendDeepAll({}, legendConfig.elements[i]);
  54891. element.name = dB;
  54892. element.color = [].concat(legendConfig.elements[i].color)[iB];
  54893. return element;
  54894. });
  54895. });
  54896. var data = d3.merge(flattenData);
  54897. data = data.filter(function(d, i) {
  54898. return legendConfig.elements[i] && (legendConfig.elements[i].visibleInLegend || typeof legendConfig.elements[i].visibleInLegend === 'undefined');
  54899. });
  54900. if (legendConfig.reverseOrder) data = data.reverse();
  54901. var container = legendConfig.container;
  54902. if (typeof container == 'string' || container.nodeName) container = d3.select(container);
  54903. var colors = data.map(function(d, i) {
  54904. return d.color;
  54905. });
  54906. var lineHeight = legendConfig.fontSize;
  54907. var isContinuous = legendConfig.isContinuous == null ? typeof data[0] === 'number' : legendConfig.isContinuous;
  54908. var height = isContinuous ? legendConfig.height : lineHeight * data.length;
  54909. var legendContainerGroup = container.classed('legend-group', true);
  54910. var svg = legendContainerGroup.selectAll('svg').data([ 0 ]);
  54911. var svgEnter = svg.enter().append('svg').attr({
  54912. width: 300,
  54913. height: height + lineHeight,
  54914. xmlns: 'http://www.w3.org/2000/svg',
  54915. 'xmlns:xlink': 'http://www.w3.org/1999/xlink',
  54916. version: '1.1'
  54917. });
  54918. svgEnter.append('g').classed('legend-axis', true);
  54919. svgEnter.append('g').classed('legend-marks', true);
  54920. var dataNumbered = d3.range(data.length);
  54921. var colorScale = d3.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered).range(colors);
  54922. var dataScale = d3.scale[isContinuous ? 'linear' : 'ordinal']().domain(dataNumbered)[isContinuous ? 'range' : 'rangePoints']([ 0, height ]);
  54923. var shapeGenerator = function(_type, _size) {
  54924. var squareSize = _size * 3;
  54925. if (_type === 'line') {
  54926. return 'M' + [ [ -_size / 2, -_size / 12 ], [ _size / 2, -_size / 12 ], [ _size / 2, _size / 12 ], [ -_size / 2, _size / 12 ] ] + 'Z';
  54927. } else if (d3.svg.symbolTypes.indexOf(_type) != -1) return d3.svg.symbol().type(_type).size(squareSize)(); else return d3.svg.symbol().type('square').size(squareSize)();
  54928. };
  54929. if (isContinuous) {
  54930. var gradient = svg.select('.legend-marks').append('defs').append('linearGradient').attr({
  54931. id: 'grad1',
  54932. x1: '0%',
  54933. y1: '0%',
  54934. x2: '0%',
  54935. y2: '100%'
  54936. }).selectAll('stop').data(colors);
  54937. gradient.enter().append('stop');
  54938. gradient.attr({
  54939. offset: function(d, i) {
  54940. return i / (colors.length - 1) * 100 + '%';
  54941. }
  54942. }).style({
  54943. 'stop-color': function(d, i) {
  54944. return d;
  54945. }
  54946. });
  54947. svg.append('rect').classed('legend-mark', true).attr({
  54948. height: legendConfig.height,
  54949. width: legendConfig.colorBandWidth,
  54950. fill: 'url(#grad1)'
  54951. });
  54952. } else {
  54953. var legendElement = svg.select('.legend-marks').selectAll('path.legend-mark').data(data);
  54954. legendElement.enter().append('path').classed('legend-mark', true);
  54955. legendElement.attr({
  54956. transform: function(d, i) {
  54957. return 'translate(' + [ lineHeight / 2, dataScale(i) + lineHeight / 2 ] + ')';
  54958. },
  54959. d: function(d, i) {
  54960. var symbolType = d.symbol;
  54961. return shapeGenerator(symbolType, lineHeight);
  54962. },
  54963. fill: function(d, i) {
  54964. return colorScale(i);
  54965. }
  54966. });
  54967. legendElement.exit().remove();
  54968. }
  54969. var legendAxis = d3.svg.axis().scale(dataScale).orient('right');
  54970. var axis = svg.select('g.legend-axis').attr({
  54971. transform: 'translate(' + [ isContinuous ? legendConfig.colorBandWidth : lineHeight, lineHeight / 2 ] + ')'
  54972. }).call(legendAxis);
  54973. axis.selectAll('.domain').style({
  54974. fill: 'none',
  54975. stroke: 'none'
  54976. });
  54977. axis.selectAll('line').style({
  54978. fill: 'none',
  54979. stroke: isContinuous ? legendConfig.textColor : 'none'
  54980. });
  54981. axis.selectAll('text').style({
  54982. fill: legendConfig.textColor,
  54983. 'font-size': legendConfig.fontSize
  54984. }).text(function(d, i) {
  54985. return data[i].name;
  54986. });
  54987. return exports;
  54988. }
  54989. exports.config = function(_x) {
  54990. if (!arguments.length) return config;
  54991. extendDeepAll(config, _x);
  54992. return this;
  54993. };
  54994. d3.rebind(exports, dispatch, 'on');
  54995. return exports;
  54996. };
  54997. µ.Legend.defaultConfig = function(d, i) {
  54998. var config = {
  54999. data: [ 'a', 'b', 'c' ],
  55000. legendConfig: {
  55001. elements: [ {
  55002. symbol: 'line',
  55003. color: 'red'
  55004. }, {
  55005. symbol: 'square',
  55006. color: 'yellow'
  55007. }, {
  55008. symbol: 'diamond',
  55009. color: 'limegreen'
  55010. } ],
  55011. height: 150,
  55012. colorBandWidth: 30,
  55013. fontSize: 12,
  55014. container: 'body',
  55015. isContinuous: null,
  55016. textColor: 'grey',
  55017. reverseOrder: false
  55018. }
  55019. };
  55020. return config;
  55021. };
  55022. µ.tooltipPanel = function() {
  55023. var tooltipEl, tooltipTextEl, backgroundEl;
  55024. var config = {
  55025. container: null,
  55026. hasTick: false,
  55027. fontSize: 12,
  55028. color: 'white',
  55029. padding: 5
  55030. };
  55031. var id = 'tooltip-' + µ.tooltipPanel.uid++;
  55032. var tickSize = 10;
  55033. var exports = function() {
  55034. tooltipEl = config.container.selectAll('g.' + id).data([ 0 ]);
  55035. var tooltipEnter = tooltipEl.enter().append('g').classed(id, true).style({
  55036. 'pointer-events': 'none',
  55037. display: 'none'
  55038. });
  55039. backgroundEl = tooltipEnter.append('path').style({
  55040. fill: 'white',
  55041. 'fill-opacity': .9
  55042. }).attr({
  55043. d: 'M0 0'
  55044. });
  55045. tooltipTextEl = tooltipEnter.append('text').attr({
  55046. dx: config.padding + tickSize,
  55047. dy: +config.fontSize * .3
  55048. });
  55049. return exports;
  55050. };
  55051. exports.text = function(_text) {
  55052. var l = d3.hsl(config.color).l;
  55053. var strokeColor = l >= .5 ? '#aaa' : 'white';
  55054. var fillColor = l >= .5 ? 'black' : 'white';
  55055. var text = _text || '';
  55056. tooltipTextEl.style({
  55057. fill: fillColor,
  55058. 'font-size': config.fontSize + 'px'
  55059. }).text(text);
  55060. var padding = config.padding;
  55061. var bbox = tooltipTextEl.node().getBBox();
  55062. var boxStyle = {
  55063. fill: config.color,
  55064. stroke: strokeColor,
  55065. 'stroke-width': '2px'
  55066. };
  55067. var backGroundW = bbox.width + padding * 2 + tickSize;
  55068. var backGroundH = bbox.height + padding * 2;
  55069. backgroundEl.attr({
  55070. d: 'M' + [ [ tickSize, -backGroundH / 2 ], [ tickSize, -backGroundH / 4 ], [ config.hasTick ? 0 : tickSize, 0 ], [ tickSize, backGroundH / 4 ], [ tickSize, backGroundH / 2 ], [ backGroundW, backGroundH / 2 ], [ backGroundW, -backGroundH / 2 ] ].join('L') + 'Z'
  55071. }).style(boxStyle);
  55072. tooltipEl.attr({
  55073. transform: 'translate(' + [ tickSize, -backGroundH / 2 + padding * 2 ] + ')'
  55074. });
  55075. tooltipEl.style({
  55076. display: 'block'
  55077. });
  55078. return exports;
  55079. };
  55080. exports.move = function(_pos) {
  55081. if (!tooltipEl) return;
  55082. tooltipEl.attr({
  55083. transform: 'translate(' + [ _pos[0], _pos[1] ] + ')'
  55084. }).style({
  55085. display: 'block'
  55086. });
  55087. return exports;
  55088. };
  55089. exports.hide = function() {
  55090. if (!tooltipEl) return;
  55091. tooltipEl.style({
  55092. display: 'none'
  55093. });
  55094. return exports;
  55095. };
  55096. exports.show = function() {
  55097. if (!tooltipEl) return;
  55098. tooltipEl.style({
  55099. display: 'block'
  55100. });
  55101. return exports;
  55102. };
  55103. exports.config = function(_x) {
  55104. extendDeepAll(config, _x);
  55105. return exports;
  55106. };
  55107. return exports;
  55108. };
  55109. µ.tooltipPanel.uid = 1;
  55110. µ.adapter = {};
  55111. µ.adapter.plotly = function module() {
  55112. var exports = {};
  55113. exports.convert = function(_inputConfig, reverse) {
  55114. var outputConfig = {};
  55115. if (_inputConfig.data) {
  55116. outputConfig.data = _inputConfig.data.map(function(d, i) {
  55117. var r = extendDeepAll({}, d);
  55118. var toTranslate = [
  55119. [ r, [ 'marker', 'color' ], [ 'color' ] ],
  55120. [ r, [ 'marker', 'opacity' ], [ 'opacity' ] ],
  55121. [ r, [ 'marker', 'line', 'color' ], [ 'strokeColor' ] ],
  55122. [ r, [ 'marker', 'line', 'dash' ], [ 'strokeDash' ] ],
  55123. [ r, [ 'marker', 'line', 'width' ], [ 'strokeSize' ] ],
  55124. [ r, [ 'marker', 'symbol' ], [ 'dotType' ] ],
  55125. [ r, [ 'marker', 'size' ], [ 'dotSize' ] ],
  55126. [ r, [ 'marker', 'barWidth' ], [ 'barWidth' ] ],
  55127. [ r, [ 'line', 'interpolation' ], [ 'lineInterpolation' ] ],
  55128. [ r, [ 'showlegend' ], [ 'visibleInLegend' ] ]
  55129. ];
  55130. toTranslate.forEach(function(d, i) {
  55131. µ.util.translator.apply(null, d.concat(reverse));
  55132. });
  55133. if (!reverse) delete r.marker;
  55134. if (reverse) delete r.groupId;
  55135. if (!reverse) {
  55136. if (r.type === 'scatter') {
  55137. if (r.mode === 'lines') r.geometry = 'LinePlot'; else if (r.mode === 'markers') r.geometry = 'DotPlot'; else if (r.mode === 'lines+markers') {
  55138. r.geometry = 'LinePlot';
  55139. r.dotVisible = true;
  55140. }
  55141. } else if (r.type === 'area') r.geometry = 'AreaChart'; else if (r.type === 'bar') r.geometry = 'BarChart';
  55142. delete r.mode;
  55143. delete r.type;
  55144. } else {
  55145. if (r.geometry === 'LinePlot') {
  55146. r.type = 'scatter';
  55147. if (r.dotVisible === true) {
  55148. delete r.dotVisible;
  55149. r.mode = 'lines+markers';
  55150. } else r.mode = 'lines';
  55151. } else if (r.geometry === 'DotPlot') {
  55152. r.type = 'scatter';
  55153. r.mode = 'markers';
  55154. } else if (r.geometry === 'AreaChart') r.type = 'area'; else if (r.geometry === 'BarChart') r.type = 'bar';
  55155. delete r.geometry;
  55156. }
  55157. return r;
  55158. });
  55159. if (!reverse && _inputConfig.layout && _inputConfig.layout.barmode === 'stack') {
  55160. var duplicates = µ.util.duplicates(outputConfig.data.map(function(d, i) {
  55161. return d.geometry;
  55162. }));
  55163. outputConfig.data.forEach(function(d, i) {
  55164. var idx = duplicates.indexOf(d.geometry);
  55165. if (idx != -1) outputConfig.data[i].groupId = idx;
  55166. });
  55167. }
  55168. }
  55169. if (_inputConfig.layout) {
  55170. var r = extendDeepAll({}, _inputConfig.layout);
  55171. var toTranslate = [
  55172. [ r, [ 'plot_bgcolor' ], [ 'backgroundColor' ] ],
  55173. [ r, [ 'showlegend' ], [ 'showLegend' ] ],
  55174. [ r, [ 'radialaxis' ], [ 'radialAxis' ] ],
  55175. [ r, [ 'angularaxis' ], [ 'angularAxis' ] ],
  55176. [ r.angularaxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
  55177. [ r.angularaxis, [ 'showticklabels' ], [ 'labelsVisible' ] ],
  55178. [ r.angularaxis, [ 'nticks' ], [ 'ticksCount' ] ],
  55179. [ r.angularaxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
  55180. [ r.angularaxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
  55181. [ r.angularaxis, [ 'range' ], [ 'domain' ] ],
  55182. [ r.angularaxis, [ 'endpadding' ], [ 'endPadding' ] ],
  55183. [ r.radialaxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
  55184. [ r.radialaxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
  55185. [ r.radialaxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
  55186. [ r.radialaxis, [ 'range' ], [ 'domain' ] ],
  55187. [ r.angularAxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
  55188. [ r.angularAxis, [ 'showticklabels' ], [ 'labelsVisible' ] ],
  55189. [ r.angularAxis, [ 'nticks' ], [ 'ticksCount' ] ],
  55190. [ r.angularAxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
  55191. [ r.angularAxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
  55192. [ r.angularAxis, [ 'range' ], [ 'domain' ] ],
  55193. [ r.angularAxis, [ 'endpadding' ], [ 'endPadding' ] ],
  55194. [ r.radialAxis, [ 'showline' ], [ 'gridLinesVisible' ] ],
  55195. [ r.radialAxis, [ 'tickorientation' ], [ 'tickOrientation' ] ],
  55196. [ r.radialAxis, [ 'ticksuffix' ], [ 'ticksSuffix' ] ],
  55197. [ r.radialAxis, [ 'range' ], [ 'domain' ] ],
  55198. [ r.font, [ 'outlinecolor' ], [ 'outlineColor' ] ],
  55199. [ r.legend, [ 'traceorder' ], [ 'reverseOrder' ] ],
  55200. [ r, [ 'labeloffset' ], [ 'labelOffset' ] ],
  55201. [ r, [ 'defaultcolorrange' ], [ 'defaultColorRange' ] ]
  55202. ];
  55203. toTranslate.forEach(function(d, i) {
  55204. µ.util.translator.apply(null, d.concat(reverse));
  55205. });
  55206. if (!reverse) {
  55207. if (r.angularAxis && typeof r.angularAxis.ticklen !== 'undefined') r.tickLength = r.angularAxis.ticklen;
  55208. if (r.angularAxis && typeof r.angularAxis.tickcolor !== 'undefined') r.tickColor = r.angularAxis.tickcolor;
  55209. } else {
  55210. if (typeof r.tickLength !== 'undefined') {
  55211. r.angularaxis.ticklen = r.tickLength;
  55212. delete r.tickLength;
  55213. }
  55214. if (r.tickColor) {
  55215. r.angularaxis.tickcolor = r.tickColor;
  55216. delete r.tickColor;
  55217. }
  55218. }
  55219. if (r.legend && typeof r.legend.reverseOrder != 'boolean') {
  55220. r.legend.reverseOrder = r.legend.reverseOrder != 'normal';
  55221. }
  55222. if (r.legend && typeof r.legend.traceorder == 'boolean') {
  55223. r.legend.traceorder = r.legend.traceorder ? 'reversed' : 'normal';
  55224. delete r.legend.reverseOrder;
  55225. }
  55226. if (r.margin && typeof r.margin.t != 'undefined') {
  55227. var source = [ 't', 'r', 'b', 'l', 'pad' ];
  55228. var target = [ 'top', 'right', 'bottom', 'left', 'pad' ];
  55229. var margin = {};
  55230. d3.entries(r.margin).forEach(function(dB, iB) {
  55231. margin[target[source.indexOf(dB.key)]] = dB.value;
  55232. });
  55233. r.margin = margin;
  55234. }
  55235. if (reverse) {
  55236. delete r.needsEndSpacing;
  55237. delete r.minorTickColor;
  55238. delete r.minorTicks;
  55239. delete r.angularaxis.ticksCount;
  55240. delete r.angularaxis.ticksCount;
  55241. delete r.angularaxis.ticksStep;
  55242. delete r.angularaxis.rewriteTicks;
  55243. delete r.angularaxis.nticks;
  55244. delete r.radialaxis.ticksCount;
  55245. delete r.radialaxis.ticksCount;
  55246. delete r.radialaxis.ticksStep;
  55247. delete r.radialaxis.rewriteTicks;
  55248. delete r.radialaxis.nticks;
  55249. }
  55250. outputConfig.layout = r;
  55251. }
  55252. return outputConfig;
  55253. };
  55254. return exports;
  55255. };
  55256. },{"../../../constants/alignment":146,"../../../lib":168,"d3":16}],250:[function(_dereq_,module,exports){
  55257. /**
  55258. * Copyright 2012-2019, Plotly, Inc.
  55259. * All rights reserved.
  55260. *
  55261. * This source code is licensed under the MIT license found in the
  55262. * LICENSE file in the root directory of this source tree.
  55263. */
  55264. /* eslint-disable new-cap */
  55265. 'use strict';
  55266. var d3 = _dereq_('d3');
  55267. var Lib = _dereq_('../../../lib');
  55268. var Color = _dereq_('../../../components/color');
  55269. var micropolar = _dereq_('./micropolar');
  55270. var UndoManager = _dereq_('./undo_manager');
  55271. var extendDeepAll = Lib.extendDeepAll;
  55272. var manager = module.exports = {};
  55273. manager.framework = function(_gd) {
  55274. var config, previousConfigClone, plot, convertedInput, container;
  55275. var undoManager = new UndoManager();
  55276. function exports(_inputConfig, _container) {
  55277. if(_container) container = _container;
  55278. d3.select(d3.select(container).node().parentNode).selectAll('.svg-container>*:not(.chart-root)').remove();
  55279. config = (!config) ?
  55280. _inputConfig :
  55281. extendDeepAll(config, _inputConfig);
  55282. if(!plot) plot = micropolar.Axis();
  55283. convertedInput = micropolar.adapter.plotly().convert(config);
  55284. plot.config(convertedInput).render(container);
  55285. _gd.data = config.data;
  55286. _gd.layout = config.layout;
  55287. manager.fillLayout(_gd);
  55288. return config;
  55289. }
  55290. exports.isPolar = true;
  55291. exports.svg = function() { return plot.svg(); };
  55292. exports.getConfig = function() { return config; };
  55293. exports.getLiveConfig = function() {
  55294. return micropolar.adapter.plotly().convert(plot.getLiveConfig(), true);
  55295. };
  55296. exports.getLiveScales = function() { return {t: plot.angularScale(), r: plot.radialScale()}; };
  55297. exports.setUndoPoint = function() {
  55298. var that = this;
  55299. var configClone = micropolar.util.cloneJson(config);
  55300. (function(_configClone, _previousConfigClone) {
  55301. undoManager.add({
  55302. undo: function() {
  55303. if(_previousConfigClone) that(_previousConfigClone);
  55304. },
  55305. redo: function() {
  55306. that(_configClone);
  55307. }
  55308. });
  55309. })(configClone, previousConfigClone);
  55310. previousConfigClone = micropolar.util.cloneJson(configClone);
  55311. };
  55312. exports.undo = function() { undoManager.undo(); };
  55313. exports.redo = function() { undoManager.redo(); };
  55314. return exports;
  55315. };
  55316. manager.fillLayout = function(_gd) {
  55317. var container = d3.select(_gd).selectAll('.plot-container');
  55318. var paperDiv = container.selectAll('.svg-container');
  55319. var paper = _gd.framework && _gd.framework.svg && _gd.framework.svg();
  55320. var dflts = {
  55321. width: 800,
  55322. height: 600,
  55323. paper_bgcolor: Color.background,
  55324. _container: container,
  55325. _paperdiv: paperDiv,
  55326. _paper: paper
  55327. };
  55328. _gd._fullLayout = extendDeepAll(dflts, _gd.layout);
  55329. };
  55330. },{"../../../components/color":51,"../../../lib":168,"./micropolar":249,"./undo_manager":251,"d3":16}],251:[function(_dereq_,module,exports){
  55331. /**
  55332. * Copyright 2012-2019, Plotly, Inc.
  55333. * All rights reserved.
  55334. *
  55335. * This source code is licensed under the MIT license found in the
  55336. * LICENSE file in the root directory of this source tree.
  55337. */
  55338. 'use strict';
  55339. // Modified from https://github.com/ArthurClemens/Javascript-Undo-Manager
  55340. // Copyright (c) 2010-2013 Arthur Clemens, arthur@visiblearea.com
  55341. module.exports = function UndoManager() {
  55342. var undoCommands = [];
  55343. var index = -1;
  55344. var isExecuting = false;
  55345. var callback;
  55346. function execute(command, action) {
  55347. if(!command) return this;
  55348. isExecuting = true;
  55349. command[action]();
  55350. isExecuting = false;
  55351. return this;
  55352. }
  55353. return {
  55354. add: function(command) {
  55355. if(isExecuting) return this;
  55356. undoCommands.splice(index + 1, undoCommands.length - index);
  55357. undoCommands.push(command);
  55358. index = undoCommands.length - 1;
  55359. return this;
  55360. },
  55361. setCallback: function(callbackFunc) { callback = callbackFunc; },
  55362. undo: function() {
  55363. var command = undoCommands[index];
  55364. if(!command) return this;
  55365. execute(command, 'undo');
  55366. index -= 1;
  55367. if(callback) callback(command.undo);
  55368. return this;
  55369. },
  55370. redo: function() {
  55371. var command = undoCommands[index + 1];
  55372. if(!command) return this;
  55373. execute(command, 'redo');
  55374. index += 1;
  55375. if(callback) callback(command.redo);
  55376. return this;
  55377. },
  55378. clear: function() {
  55379. undoCommands = [];
  55380. index = -1;
  55381. },
  55382. hasUndo: function() { return index !== -1; },
  55383. hasRedo: function() { return index < (undoCommands.length - 1); },
  55384. getCommands: function() { return undoCommands; },
  55385. getPreviousCommand: function() { return undoCommands[index - 1]; },
  55386. getIndex: function() { return index; }
  55387. };
  55388. };
  55389. },{}],252:[function(_dereq_,module,exports){
  55390. /**
  55391. * Copyright 2012-2019, Plotly, Inc.
  55392. * All rights reserved.
  55393. *
  55394. * This source code is licensed under the MIT license found in the
  55395. * LICENSE file in the root directory of this source tree.
  55396. */
  55397. 'use strict';
  55398. var Lib = _dereq_('../lib');
  55399. var Template = _dereq_('../plot_api/plot_template');
  55400. var handleDomainDefaults = _dereq_('./domain').defaults;
  55401. /**
  55402. * Find and supply defaults to all subplots of a given type
  55403. * This handles subplots that are contained within one container - so
  55404. * gl3d, geo, ternary... but not 2d axes which have separate x and y axes
  55405. * finds subplots, coerces their `domain` attributes, then calls the
  55406. * given handleDefaults function to fill in everything else.
  55407. *
  55408. * layoutIn: the complete user-supplied input layout
  55409. * layoutOut: the complete finished layout
  55410. * fullData: the finished data array, used only to find subplots
  55411. * opts: {
  55412. * type: subplot type string
  55413. * attributes: subplot attributes object
  55414. * partition: 'x' or 'y', which direction to divide domain space by default
  55415. * (default 'x', ie side-by-side subplots)
  55416. * TODO: this option is only here because 3D and geo made opposite
  55417. * choices in this regard previously and I didn't want to change it.
  55418. * Instead we should do:
  55419. * - something consistent
  55420. * - something more square (4 cuts 2x2, 5/6 cuts 2x3, etc.)
  55421. * - something that includes all subplot types in one arrangement,
  55422. * now that we can have them together!
  55423. * handleDefaults: function of (subplotLayoutIn, subplotLayoutOut, coerce, opts)
  55424. * this opts object is passed through to handleDefaults, so attach any
  55425. * additional items needed by this function here as well
  55426. * }
  55427. */
  55428. module.exports = function handleSubplotDefaults(layoutIn, layoutOut, fullData, opts) {
  55429. var subplotType = opts.type;
  55430. var subplotAttributes = opts.attributes;
  55431. var handleDefaults = opts.handleDefaults;
  55432. var partition = opts.partition || 'x';
  55433. var ids = layoutOut._subplots[subplotType];
  55434. var idsLength = ids.length;
  55435. var baseId = idsLength && ids[0].replace(/\d+$/, '');
  55436. var subplotLayoutIn, subplotLayoutOut;
  55437. function coerce(attr, dflt) {
  55438. return Lib.coerce(subplotLayoutIn, subplotLayoutOut, subplotAttributes, attr, dflt);
  55439. }
  55440. for(var i = 0; i < idsLength; i++) {
  55441. var id = ids[i];
  55442. // ternary traces get a layout ternary for free!
  55443. if(layoutIn[id]) subplotLayoutIn = layoutIn[id];
  55444. else subplotLayoutIn = layoutIn[id] = {};
  55445. subplotLayoutOut = Template.newContainer(layoutOut, id, baseId);
  55446. // All subplot containers get a `uirevision` inheriting from the base.
  55447. // Currently all subplots containers have some user interaction
  55448. // attributes, but if we ever add one that doesn't, we would need an
  55449. // option to skip this step.
  55450. coerce('uirevision', layoutOut.uirevision);
  55451. var dfltDomains = {};
  55452. dfltDomains[partition] = [i / idsLength, (i + 1) / idsLength];
  55453. handleDomainDefaults(subplotLayoutOut, layoutOut, coerce, dfltDomains);
  55454. opts.id = id;
  55455. handleDefaults(subplotLayoutIn, subplotLayoutOut, coerce, opts);
  55456. }
  55457. };
  55458. },{"../lib":168,"../plot_api/plot_template":202,"./domain":238}],253:[function(_dereq_,module,exports){
  55459. /**
  55460. * Copyright 2012-2019, Plotly, Inc.
  55461. * All rights reserved.
  55462. *
  55463. * This source code is licensed under the MIT license found in the
  55464. * LICENSE file in the root directory of this source tree.
  55465. */
  55466. 'use strict';
  55467. var Ternary = _dereq_('./ternary');
  55468. var getSubplotCalcData = _dereq_('../../plots/get_data').getSubplotCalcData;
  55469. var counterRegex = _dereq_('../../lib').counterRegex;
  55470. var TERNARY = 'ternary';
  55471. exports.name = TERNARY;
  55472. var attr = exports.attr = 'subplot';
  55473. exports.idRoot = TERNARY;
  55474. exports.idRegex = exports.attrRegex = counterRegex(TERNARY);
  55475. var attributes = exports.attributes = {};
  55476. attributes[attr] = {
  55477. valType: 'subplotid',
  55478. dflt: 'ternary',
  55479. editType: 'calc',
  55480. };
  55481. exports.layoutAttributes = _dereq_('./layout_attributes');
  55482. exports.supplyLayoutDefaults = _dereq_('./layout_defaults');
  55483. exports.plot = function plotTernary(gd) {
  55484. var fullLayout = gd._fullLayout;
  55485. var calcData = gd.calcdata;
  55486. var ternaryIds = fullLayout._subplots[TERNARY];
  55487. for(var i = 0; i < ternaryIds.length; i++) {
  55488. var ternaryId = ternaryIds[i];
  55489. var ternaryCalcData = getSubplotCalcData(calcData, TERNARY, ternaryId);
  55490. var ternary = fullLayout[ternaryId]._subplot;
  55491. // If ternary is not instantiated, create one!
  55492. if(!ternary) {
  55493. ternary = new Ternary({
  55494. id: ternaryId,
  55495. graphDiv: gd,
  55496. container: fullLayout._ternarylayer.node()
  55497. },
  55498. fullLayout
  55499. );
  55500. fullLayout[ternaryId]._subplot = ternary;
  55501. }
  55502. ternary.plot(ternaryCalcData, fullLayout, gd._promises);
  55503. }
  55504. };
  55505. exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
  55506. var oldTernaryKeys = oldFullLayout._subplots[TERNARY] || [];
  55507. for(var i = 0; i < oldTernaryKeys.length; i++) {
  55508. var oldTernaryKey = oldTernaryKeys[i];
  55509. var oldTernary = oldFullLayout[oldTernaryKey]._subplot;
  55510. if(!newFullLayout[oldTernaryKey] && !!oldTernary) {
  55511. oldTernary.plotContainer.remove();
  55512. oldTernary.clipDef.remove();
  55513. oldTernary.clipDefRelative.remove();
  55514. oldTernary.layers['a-title'].remove();
  55515. oldTernary.layers['b-title'].remove();
  55516. oldTernary.layers['c-title'].remove();
  55517. }
  55518. }
  55519. };
  55520. },{"../../lib":168,"../../plots/get_data":241,"./layout_attributes":254,"./layout_defaults":255,"./ternary":256}],254:[function(_dereq_,module,exports){
  55521. /**
  55522. * Copyright 2012-2019, Plotly, Inc.
  55523. * All rights reserved.
  55524. *
  55525. * This source code is licensed under the MIT license found in the
  55526. * LICENSE file in the root directory of this source tree.
  55527. */
  55528. 'use strict';
  55529. var colorAttrs = _dereq_('../../components/color/attributes');
  55530. var domainAttrs = _dereq_('../domain').attributes;
  55531. var axesAttrs = _dereq_('../cartesian/layout_attributes');
  55532. var overrideAll = _dereq_('../../plot_api/edit_types').overrideAll;
  55533. var extendFlat = _dereq_('../../lib/extend').extendFlat;
  55534. var ternaryAxesAttrs = {
  55535. title: axesAttrs.title,
  55536. color: axesAttrs.color,
  55537. // ticks
  55538. tickmode: axesAttrs.tickmode,
  55539. nticks: extendFlat({}, axesAttrs.nticks, {dflt: 6, min: 1}),
  55540. tick0: axesAttrs.tick0,
  55541. dtick: axesAttrs.dtick,
  55542. tickvals: axesAttrs.tickvals,
  55543. ticktext: axesAttrs.ticktext,
  55544. ticks: axesAttrs.ticks,
  55545. ticklen: axesAttrs.ticklen,
  55546. tickwidth: axesAttrs.tickwidth,
  55547. tickcolor: axesAttrs.tickcolor,
  55548. showticklabels: axesAttrs.showticklabels,
  55549. showtickprefix: axesAttrs.showtickprefix,
  55550. tickprefix: axesAttrs.tickprefix,
  55551. showticksuffix: axesAttrs.showticksuffix,
  55552. ticksuffix: axesAttrs.ticksuffix,
  55553. showexponent: axesAttrs.showexponent,
  55554. exponentformat: axesAttrs.exponentformat,
  55555. separatethousands: axesAttrs.separatethousands,
  55556. tickfont: axesAttrs.tickfont,
  55557. tickangle: axesAttrs.tickangle,
  55558. tickformat: axesAttrs.tickformat,
  55559. tickformatstops: axesAttrs.tickformatstops,
  55560. hoverformat: axesAttrs.hoverformat,
  55561. // lines and grids
  55562. showline: extendFlat({}, axesAttrs.showline, {dflt: true}),
  55563. linecolor: axesAttrs.linecolor,
  55564. linewidth: axesAttrs.linewidth,
  55565. showgrid: extendFlat({}, axesAttrs.showgrid, {dflt: true}),
  55566. gridcolor: axesAttrs.gridcolor,
  55567. gridwidth: axesAttrs.gridwidth,
  55568. layer: axesAttrs.layer,
  55569. // range
  55570. min: {
  55571. valType: 'number',
  55572. dflt: 0,
  55573. min: 0,
  55574. },
  55575. _deprecated: {
  55576. title: axesAttrs._deprecated.title,
  55577. titlefont: axesAttrs._deprecated.titlefont
  55578. }
  55579. };
  55580. var attrs = module.exports = overrideAll({
  55581. domain: domainAttrs({name: 'ternary'}),
  55582. bgcolor: {
  55583. valType: 'color',
  55584. dflt: colorAttrs.background,
  55585. },
  55586. sum: {
  55587. valType: 'number',
  55588. dflt: 1,
  55589. min: 0,
  55590. },
  55591. aaxis: ternaryAxesAttrs,
  55592. baxis: ternaryAxesAttrs,
  55593. caxis: ternaryAxesAttrs
  55594. }, 'plot', 'from-root');
  55595. // set uirevisions outside of `overrideAll` so we can get `editType: none`
  55596. attrs.uirevision = {
  55597. valType: 'any',
  55598. editType: 'none',
  55599. };
  55600. attrs.aaxis.uirevision = attrs.baxis.uirevision = attrs.caxis.uirevision = {
  55601. valType: 'any',
  55602. editType: 'none',
  55603. };
  55604. },{"../../components/color/attributes":50,"../../lib/extend":162,"../../plot_api/edit_types":195,"../cartesian/layout_attributes":225,"../domain":238}],255:[function(_dereq_,module,exports){
  55605. /**
  55606. * Copyright 2012-2019, Plotly, Inc.
  55607. * All rights reserved.
  55608. *
  55609. * This source code is licensed under the MIT license found in the
  55610. * LICENSE file in the root directory of this source tree.
  55611. */
  55612. 'use strict';
  55613. var Color = _dereq_('../../components/color');
  55614. var Template = _dereq_('../../plot_api/plot_template');
  55615. var Lib = _dereq_('../../lib');
  55616. var handleSubplotDefaults = _dereq_('../subplot_defaults');
  55617. var handleTickLabelDefaults = _dereq_('../cartesian/tick_label_defaults');
  55618. var handleTickMarkDefaults = _dereq_('../cartesian/tick_mark_defaults');
  55619. var handleTickValueDefaults = _dereq_('../cartesian/tick_value_defaults');
  55620. var handleLineGridDefaults = _dereq_('../cartesian/line_grid_defaults');
  55621. var layoutAttributes = _dereq_('./layout_attributes');
  55622. var axesNames = ['aaxis', 'baxis', 'caxis'];
  55623. module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
  55624. handleSubplotDefaults(layoutIn, layoutOut, fullData, {
  55625. type: 'ternary',
  55626. attributes: layoutAttributes,
  55627. handleDefaults: handleTernaryDefaults,
  55628. font: layoutOut.font,
  55629. paper_bgcolor: layoutOut.paper_bgcolor
  55630. });
  55631. };
  55632. function handleTernaryDefaults(ternaryLayoutIn, ternaryLayoutOut, coerce, options) {
  55633. var bgColor = coerce('bgcolor');
  55634. var sum = coerce('sum');
  55635. options.bgColor = Color.combine(bgColor, options.paper_bgcolor);
  55636. var axName, containerIn, containerOut;
  55637. // TODO: allow most (if not all) axis attributes to be set
  55638. // in the outer container and used as defaults in the individual axes?
  55639. for(var j = 0; j < axesNames.length; j++) {
  55640. axName = axesNames[j];
  55641. containerIn = ternaryLayoutIn[axName] || {};
  55642. containerOut = Template.newContainer(ternaryLayoutOut, axName);
  55643. containerOut._name = axName;
  55644. handleAxisDefaults(containerIn, containerOut, options, ternaryLayoutOut);
  55645. }
  55646. // if the min values contradict each other, set them all to default (0)
  55647. // and delete *all* the inputs so the user doesn't get confused later by
  55648. // changing one and having them all change.
  55649. var aaxis = ternaryLayoutOut.aaxis;
  55650. var baxis = ternaryLayoutOut.baxis;
  55651. var caxis = ternaryLayoutOut.caxis;
  55652. if(aaxis.min + baxis.min + caxis.min >= sum) {
  55653. aaxis.min = 0;
  55654. baxis.min = 0;
  55655. caxis.min = 0;
  55656. if(ternaryLayoutIn.aaxis) delete ternaryLayoutIn.aaxis.min;
  55657. if(ternaryLayoutIn.baxis) delete ternaryLayoutIn.baxis.min;
  55658. if(ternaryLayoutIn.caxis) delete ternaryLayoutIn.caxis.min;
  55659. }
  55660. }
  55661. function handleAxisDefaults(containerIn, containerOut, options, ternaryLayoutOut) {
  55662. var axAttrs = layoutAttributes[containerOut._name];
  55663. function coerce(attr, dflt) {
  55664. return Lib.coerce(containerIn, containerOut, axAttrs, attr, dflt);
  55665. }
  55666. coerce('uirevision', ternaryLayoutOut.uirevision);
  55667. containerOut.type = 'linear'; // no other types allowed for ternary
  55668. var dfltColor = coerce('color');
  55669. // if axis.color was provided, use it for fonts too; otherwise,
  55670. // inherit from global font color in case that was provided.
  55671. var dfltFontColor = (dfltColor !== axAttrs.color.dflt) ? dfltColor : options.font.color;
  55672. var axName = containerOut._name;
  55673. var letterUpper = axName.charAt(0).toUpperCase();
  55674. var dfltTitle = 'Component ' + letterUpper;
  55675. var title = coerce('title.text', dfltTitle);
  55676. containerOut._hovertitle = title === dfltTitle ? title : letterUpper;
  55677. Lib.coerceFont(coerce, 'title.font', {
  55678. family: options.font.family,
  55679. size: Math.round(options.font.size * 1.2),
  55680. color: dfltFontColor
  55681. });
  55682. // range is just set by 'min' - max is determined by the other axes mins
  55683. coerce('min');
  55684. handleTickValueDefaults(containerIn, containerOut, coerce, 'linear');
  55685. handleTickLabelDefaults(containerIn, containerOut, coerce, 'linear', {});
  55686. handleTickMarkDefaults(containerIn, containerOut, coerce,
  55687. { outerTicks: true });
  55688. var showTickLabels = coerce('showticklabels');
  55689. if(showTickLabels) {
  55690. Lib.coerceFont(coerce, 'tickfont', {
  55691. family: options.font.family,
  55692. size: options.font.size,
  55693. color: dfltFontColor
  55694. });
  55695. coerce('tickangle');
  55696. coerce('tickformat');
  55697. }
  55698. handleLineGridDefaults(containerIn, containerOut, coerce, {
  55699. dfltColor: dfltColor,
  55700. bgColor: options.bgColor,
  55701. // default grid color is darker here (60%, vs cartesian default ~91%)
  55702. // because the grid is not square so the eye needs heavier cues to follow
  55703. blend: 60,
  55704. showLine: true,
  55705. showGrid: true,
  55706. noZeroLine: true,
  55707. attributes: axAttrs
  55708. });
  55709. coerce('hoverformat');
  55710. coerce('layer');
  55711. }
  55712. },{"../../components/color":51,"../../lib":168,"../../plot_api/plot_template":202,"../cartesian/line_grid_defaults":227,"../cartesian/tick_label_defaults":232,"../cartesian/tick_mark_defaults":233,"../cartesian/tick_value_defaults":234,"../subplot_defaults":252,"./layout_attributes":254}],256:[function(_dereq_,module,exports){
  55713. /**
  55714. * Copyright 2012-2019, Plotly, Inc.
  55715. * All rights reserved.
  55716. *
  55717. * This source code is licensed under the MIT license found in the
  55718. * LICENSE file in the root directory of this source tree.
  55719. */
  55720. 'use strict';
  55721. var d3 = _dereq_('d3');
  55722. var tinycolor = _dereq_('tinycolor2');
  55723. var Registry = _dereq_('../../registry');
  55724. var Lib = _dereq_('../../lib');
  55725. var _ = Lib._;
  55726. var Color = _dereq_('../../components/color');
  55727. var Drawing = _dereq_('../../components/drawing');
  55728. var setConvert = _dereq_('../cartesian/set_convert');
  55729. var extendFlat = _dereq_('../../lib/extend').extendFlat;
  55730. var Plots = _dereq_('../plots');
  55731. var Axes = _dereq_('../cartesian/axes');
  55732. var dragElement = _dereq_('../../components/dragelement');
  55733. var Fx = _dereq_('../../components/fx');
  55734. var Titles = _dereq_('../../components/titles');
  55735. var prepSelect = _dereq_('../cartesian/select').prepSelect;
  55736. var selectOnClick = _dereq_('../cartesian/select').selectOnClick;
  55737. var clearSelect = _dereq_('../cartesian/select').clearSelect;
  55738. var constants = _dereq_('../cartesian/constants');
  55739. function Ternary(options, fullLayout) {
  55740. this.id = options.id;
  55741. this.graphDiv = options.graphDiv;
  55742. this.init(fullLayout);
  55743. this.makeFramework(fullLayout);
  55744. // unfortunately, we have to keep track of some axis tick settings
  55745. // as ternary subplots do not implement the 'ticks' editType
  55746. this.aTickLayout = null;
  55747. this.bTickLayout = null;
  55748. this.cTickLayout = null;
  55749. }
  55750. module.exports = Ternary;
  55751. var proto = Ternary.prototype;
  55752. proto.init = function(fullLayout) {
  55753. this.container = fullLayout._ternarylayer;
  55754. this.defs = fullLayout._defs;
  55755. this.layoutId = fullLayout._uid;
  55756. this.traceHash = {};
  55757. this.layers = {};
  55758. };
  55759. proto.plot = function(ternaryCalcData, fullLayout) {
  55760. var _this = this;
  55761. var ternaryLayout = fullLayout[_this.id];
  55762. var graphSize = fullLayout._size;
  55763. _this._hasClipOnAxisFalse = false;
  55764. for(var i = 0; i < ternaryCalcData.length; i++) {
  55765. var trace = ternaryCalcData[i][0].trace;
  55766. if(trace.cliponaxis === false) {
  55767. _this._hasClipOnAxisFalse = true;
  55768. break;
  55769. }
  55770. }
  55771. _this.updateLayers(ternaryLayout);
  55772. _this.adjustLayout(ternaryLayout, graphSize);
  55773. Plots.generalUpdatePerTraceModule(_this.graphDiv, _this, ternaryCalcData, ternaryLayout);
  55774. _this.layers.plotbg.select('path').call(Color.fill, ternaryLayout.bgcolor);
  55775. };
  55776. proto.makeFramework = function(fullLayout) {
  55777. var _this = this;
  55778. var gd = _this.graphDiv;
  55779. var ternaryLayout = fullLayout[_this.id];
  55780. var clipId = _this.clipId = 'clip' + _this.layoutId + _this.id;
  55781. var clipIdRelative = _this.clipIdRelative = 'clip-relative' + _this.layoutId + _this.id;
  55782. // clippath for this ternary subplot
  55783. _this.clipDef = Lib.ensureSingleById(fullLayout._clips, 'clipPath', clipId, function(s) {
  55784. s.append('path').attr('d', 'M0,0Z');
  55785. });
  55786. // 'relative' clippath (i.e. no translation) for this ternary subplot
  55787. _this.clipDefRelative = Lib.ensureSingleById(fullLayout._clips, 'clipPath', clipIdRelative, function(s) {
  55788. s.append('path').attr('d', 'M0,0Z');
  55789. });
  55790. // container for everything in this ternary subplot
  55791. _this.plotContainer = Lib.ensureSingle(_this.container, 'g', _this.id);
  55792. _this.updateLayers(ternaryLayout);
  55793. Drawing.setClipUrl(_this.layers.backplot, clipId, gd);
  55794. Drawing.setClipUrl(_this.layers.grids, clipId, gd);
  55795. };
  55796. proto.updateLayers = function(ternaryLayout) {
  55797. var _this = this;
  55798. var layers = _this.layers;
  55799. // inside that container, we have one container for the data, and
  55800. // one each for the three axes around it.
  55801. var plotLayers = ['draglayer', 'plotbg', 'backplot', 'grids'];
  55802. if(ternaryLayout.aaxis.layer === 'below traces') {
  55803. plotLayers.push('aaxis', 'aline');
  55804. }
  55805. if(ternaryLayout.baxis.layer === 'below traces') {
  55806. plotLayers.push('baxis', 'bline');
  55807. }
  55808. if(ternaryLayout.caxis.layer === 'below traces') {
  55809. plotLayers.push('caxis', 'cline');
  55810. }
  55811. plotLayers.push('frontplot');
  55812. if(ternaryLayout.aaxis.layer === 'above traces') {
  55813. plotLayers.push('aaxis', 'aline');
  55814. }
  55815. if(ternaryLayout.baxis.layer === 'above traces') {
  55816. plotLayers.push('baxis', 'bline');
  55817. }
  55818. if(ternaryLayout.caxis.layer === 'above traces') {
  55819. plotLayers.push('caxis', 'cline');
  55820. }
  55821. var toplevel = _this.plotContainer.selectAll('g.toplevel')
  55822. .data(plotLayers, String);
  55823. var grids = ['agrid', 'bgrid', 'cgrid'];
  55824. toplevel.enter().append('g')
  55825. .attr('class', function(d) { return 'toplevel ' + d; })
  55826. .each(function(d) {
  55827. var s = d3.select(this);
  55828. layers[d] = s;
  55829. // containers for different trace types.
  55830. // NOTE - this is different from cartesian, where all traces
  55831. // are in front of grids. Here I'm putting maps behind the grids
  55832. // so the grids will always be visible if they're requested.
  55833. // Perhaps we want that for cartesian too?
  55834. if(d === 'frontplot') {
  55835. s.append('g').classed('scatterlayer', true);
  55836. } else if(d === 'backplot') {
  55837. s.append('g').classed('maplayer', true);
  55838. } else if(d === 'plotbg') {
  55839. s.append('path').attr('d', 'M0,0Z');
  55840. } else if(d === 'aline' || d === 'bline' || d === 'cline') {
  55841. s.append('path');
  55842. } else if(d === 'grids') {
  55843. grids.forEach(function(d) {
  55844. layers[d] = s.append('g').classed('grid ' + d, true);
  55845. });
  55846. }
  55847. });
  55848. toplevel.order();
  55849. };
  55850. var whRatio = Math.sqrt(4 / 3);
  55851. proto.adjustLayout = function(ternaryLayout, graphSize) {
  55852. var _this = this;
  55853. var domain = ternaryLayout.domain;
  55854. var xDomainCenter = (domain.x[0] + domain.x[1]) / 2;
  55855. var yDomainCenter = (domain.y[0] + domain.y[1]) / 2;
  55856. var xDomain = domain.x[1] - domain.x[0];
  55857. var yDomain = domain.y[1] - domain.y[0];
  55858. var wmax = xDomain * graphSize.w;
  55859. var hmax = yDomain * graphSize.h;
  55860. var sum = ternaryLayout.sum;
  55861. var amin = ternaryLayout.aaxis.min;
  55862. var bmin = ternaryLayout.baxis.min;
  55863. var cmin = ternaryLayout.caxis.min;
  55864. var x0, y0, w, h, xDomainFinal, yDomainFinal;
  55865. if(wmax > whRatio * hmax) {
  55866. h = hmax;
  55867. w = h * whRatio;
  55868. }
  55869. else {
  55870. w = wmax;
  55871. h = w / whRatio;
  55872. }
  55873. xDomainFinal = xDomain * w / wmax;
  55874. yDomainFinal = yDomain * h / hmax;
  55875. x0 = graphSize.l + graphSize.w * xDomainCenter - w / 2;
  55876. y0 = graphSize.t + graphSize.h * (1 - yDomainCenter) - h / 2;
  55877. _this.x0 = x0;
  55878. _this.y0 = y0;
  55879. _this.w = w;
  55880. _this.h = h;
  55881. _this.sum = sum;
  55882. // set up the x and y axis objects we'll use to lay out the points
  55883. _this.xaxis = {
  55884. type: 'linear',
  55885. range: [amin + 2 * cmin - sum, sum - amin - 2 * bmin],
  55886. domain: [
  55887. xDomainCenter - xDomainFinal / 2,
  55888. xDomainCenter + xDomainFinal / 2
  55889. ],
  55890. _id: 'x'
  55891. };
  55892. setConvert(_this.xaxis, _this.graphDiv._fullLayout);
  55893. _this.xaxis.setScale();
  55894. _this.xaxis.isPtWithinRange = function(d) {
  55895. return (
  55896. d.a >= _this.aaxis.range[0] &&
  55897. d.a <= _this.aaxis.range[1] &&
  55898. d.b >= _this.baxis.range[1] &&
  55899. d.b <= _this.baxis.range[0] &&
  55900. d.c >= _this.caxis.range[1] &&
  55901. d.c <= _this.caxis.range[0]
  55902. );
  55903. };
  55904. _this.yaxis = {
  55905. type: 'linear',
  55906. range: [amin, sum - bmin - cmin],
  55907. domain: [
  55908. yDomainCenter - yDomainFinal / 2,
  55909. yDomainCenter + yDomainFinal / 2
  55910. ],
  55911. _id: 'y'
  55912. };
  55913. setConvert(_this.yaxis, _this.graphDiv._fullLayout);
  55914. _this.yaxis.setScale();
  55915. _this.yaxis.isPtWithinRange = function() { return true; };
  55916. // set up the modified axes for tick drawing
  55917. var yDomain0 = _this.yaxis.domain[0];
  55918. // aaxis goes up the left side. Set it up as a y axis, but with
  55919. // fictitious angles and domain, but then rotate and translate
  55920. // it into place at the end
  55921. var aaxis = _this.aaxis = extendFlat({}, ternaryLayout.aaxis, {
  55922. range: [amin, sum - bmin - cmin],
  55923. side: 'left',
  55924. // tickangle = 'auto' means 0 anyway for a y axis, need to coerce to 0 here
  55925. // so we can shift by 30.
  55926. tickangle: (+ternaryLayout.aaxis.tickangle || 0) - 30,
  55927. domain: [yDomain0, yDomain0 + yDomainFinal * whRatio],
  55928. anchor: 'free',
  55929. position: 0,
  55930. _id: 'y',
  55931. _length: w
  55932. });
  55933. setConvert(aaxis, _this.graphDiv._fullLayout);
  55934. aaxis.setScale();
  55935. // baxis goes across the bottom (backward). We can set it up as an x axis
  55936. // without any enclosing transformation.
  55937. var baxis = _this.baxis = extendFlat({}, ternaryLayout.baxis, {
  55938. range: [sum - amin - cmin, bmin],
  55939. side: 'bottom',
  55940. domain: _this.xaxis.domain,
  55941. anchor: 'free',
  55942. position: 0,
  55943. _id: 'x',
  55944. _length: w
  55945. });
  55946. setConvert(baxis, _this.graphDiv._fullLayout);
  55947. baxis.setScale();
  55948. // caxis goes down the right side. Set it up as a y axis, with
  55949. // post-transformation similar to aaxis
  55950. var caxis = _this.caxis = extendFlat({}, ternaryLayout.caxis, {
  55951. range: [sum - amin - bmin, cmin],
  55952. side: 'right',
  55953. tickangle: (+ternaryLayout.caxis.tickangle || 0) + 30,
  55954. domain: [yDomain0, yDomain0 + yDomainFinal * whRatio],
  55955. anchor: 'free',
  55956. position: 0,
  55957. _id: 'y',
  55958. _length: w
  55959. });
  55960. setConvert(caxis, _this.graphDiv._fullLayout);
  55961. caxis.setScale();
  55962. var triangleClip = 'M' + x0 + ',' + (y0 + h) + 'h' + w + 'l-' + (w / 2) + ',-' + h + 'Z';
  55963. _this.clipDef.select('path').attr('d', triangleClip);
  55964. _this.layers.plotbg.select('path').attr('d', triangleClip);
  55965. var triangleClipRelative = 'M0,' + h + 'h' + w + 'l-' + (w / 2) + ',-' + h + 'Z';
  55966. _this.clipDefRelative.select('path').attr('d', triangleClipRelative);
  55967. var plotTransform = 'translate(' + x0 + ',' + y0 + ')';
  55968. _this.plotContainer.selectAll('.scatterlayer,.maplayer')
  55969. .attr('transform', plotTransform);
  55970. _this.clipDefRelative.select('path').attr('transform', null);
  55971. // TODO: shift axes to accommodate linewidth*sin(30) tick mark angle
  55972. // TODO: there's probably an easier way to handle these translations/offsets now...
  55973. var bTransform = 'translate(' + (x0 - baxis._offset) + ',' + (y0 + h) + ')';
  55974. _this.layers.baxis.attr('transform', bTransform);
  55975. _this.layers.bgrid.attr('transform', bTransform);
  55976. var aTransform = 'translate(' + (x0 + w / 2) + ',' + y0 +
  55977. ')rotate(30)translate(0,' + -aaxis._offset + ')';
  55978. _this.layers.aaxis.attr('transform', aTransform);
  55979. _this.layers.agrid.attr('transform', aTransform);
  55980. var cTransform = 'translate(' + (x0 + w / 2) + ',' + y0 +
  55981. ')rotate(-30)translate(0,' + -caxis._offset + ')';
  55982. _this.layers.caxis.attr('transform', cTransform);
  55983. _this.layers.cgrid.attr('transform', cTransform);
  55984. _this.drawAxes(true);
  55985. _this.layers.aline.select('path')
  55986. .attr('d', aaxis.showline ?
  55987. 'M' + x0 + ',' + (y0 + h) + 'l' + (w / 2) + ',-' + h : 'M0,0')
  55988. .call(Color.stroke, aaxis.linecolor || '#000')
  55989. .style('stroke-width', (aaxis.linewidth || 0) + 'px');
  55990. _this.layers.bline.select('path')
  55991. .attr('d', baxis.showline ?
  55992. 'M' + x0 + ',' + (y0 + h) + 'h' + w : 'M0,0')
  55993. .call(Color.stroke, baxis.linecolor || '#000')
  55994. .style('stroke-width', (baxis.linewidth || 0) + 'px');
  55995. _this.layers.cline.select('path')
  55996. .attr('d', caxis.showline ?
  55997. 'M' + (x0 + w / 2) + ',' + y0 + 'l' + (w / 2) + ',' + h : 'M0,0')
  55998. .call(Color.stroke, caxis.linecolor || '#000')
  55999. .style('stroke-width', (caxis.linewidth || 0) + 'px');
  56000. if(!_this.graphDiv._context.staticPlot) {
  56001. _this.initInteractions();
  56002. }
  56003. Drawing.setClipUrl(
  56004. _this.layers.frontplot,
  56005. _this._hasClipOnAxisFalse ? null : _this.clipId,
  56006. _this.graphDiv
  56007. );
  56008. };
  56009. proto.drawAxes = function(doTitles) {
  56010. var _this = this;
  56011. var gd = _this.graphDiv;
  56012. var titlesuffix = _this.id.substr(7) + 'title';
  56013. var layers = _this.layers;
  56014. var aaxis = _this.aaxis;
  56015. var baxis = _this.baxis;
  56016. var caxis = _this.caxis;
  56017. _this.drawAx(aaxis);
  56018. _this.drawAx(baxis);
  56019. _this.drawAx(caxis);
  56020. if(doTitles) {
  56021. var apad = Math.max(aaxis.showticklabels ? aaxis.tickfont.size / 2 : 0,
  56022. (caxis.showticklabels ? caxis.tickfont.size * 0.75 : 0) +
  56023. (caxis.ticks === 'outside' ? caxis.ticklen * 0.87 : 0));
  56024. var bpad = (baxis.showticklabels ? baxis.tickfont.size : 0) +
  56025. (baxis.ticks === 'outside' ? baxis.ticklen : 0) + 3;
  56026. layers['a-title'] = Titles.draw(gd, 'a' + titlesuffix, {
  56027. propContainer: aaxis,
  56028. propName: _this.id + '.aaxis.title',
  56029. placeholder: _(gd, 'Click to enter Component A title'),
  56030. attributes: {
  56031. x: _this.x0 + _this.w / 2,
  56032. y: _this.y0 - aaxis.title.font.size / 3 - apad,
  56033. 'text-anchor': 'middle'
  56034. }
  56035. });
  56036. layers['b-title'] = Titles.draw(gd, 'b' + titlesuffix, {
  56037. propContainer: baxis,
  56038. propName: _this.id + '.baxis.title',
  56039. placeholder: _(gd, 'Click to enter Component B title'),
  56040. attributes: {
  56041. x: _this.x0 - bpad,
  56042. y: _this.y0 + _this.h + baxis.title.font.size * 0.83 + bpad,
  56043. 'text-anchor': 'middle'
  56044. }
  56045. });
  56046. layers['c-title'] = Titles.draw(gd, 'c' + titlesuffix, {
  56047. propContainer: caxis,
  56048. propName: _this.id + '.caxis.title',
  56049. placeholder: _(gd, 'Click to enter Component C title'),
  56050. attributes: {
  56051. x: _this.x0 + _this.w + bpad,
  56052. y: _this.y0 + _this.h + caxis.title.font.size * 0.83 + bpad,
  56053. 'text-anchor': 'middle'
  56054. }
  56055. });
  56056. }
  56057. };
  56058. proto.drawAx = function(ax) {
  56059. var _this = this;
  56060. var gd = _this.graphDiv;
  56061. var axName = ax._name;
  56062. var axLetter = axName.charAt(0);
  56063. var axId = ax._id;
  56064. var axLayer = _this.layers[axName];
  56065. var counterAngle = 30;
  56066. var stashKey = axLetter + 'tickLayout';
  56067. var newTickLayout = strTickLayout(ax);
  56068. if(_this[stashKey] !== newTickLayout) {
  56069. axLayer.selectAll('.' + axId + 'tick').remove();
  56070. _this[stashKey] = newTickLayout;
  56071. }
  56072. ax.setScale();
  56073. var vals = Axes.calcTicks(ax);
  56074. var valsClipped = Axes.clipEnds(ax, vals);
  56075. var transFn = Axes.makeTransFn(ax);
  56076. var tickSign = Axes.getTickSigns(ax)[2];
  56077. var caRad = Lib.deg2rad(counterAngle);
  56078. var pad = tickSign * (ax.linewidth || 1) / 2;
  56079. var len = tickSign * ax.ticklen;
  56080. var w = _this.w;
  56081. var h = _this.h;
  56082. var tickPath = axLetter === 'b' ?
  56083. 'M0,' + pad + 'l' + (Math.sin(caRad) * len) + ',' + (Math.cos(caRad) * len) :
  56084. 'M' + pad + ',0l' + (Math.cos(caRad) * len) + ',' + (-Math.sin(caRad) * len);
  56085. var gridPath = {
  56086. a: 'M0,0l' + h + ',-' + (w / 2),
  56087. b: 'M0,0l-' + (w / 2) + ',-' + h,
  56088. c: 'M0,0l-' + h + ',' + (w / 2)
  56089. }[axLetter];
  56090. Axes.drawTicks(gd, ax, {
  56091. vals: ax.ticks === 'inside' ? valsClipped : vals,
  56092. layer: axLayer,
  56093. path: tickPath,
  56094. transFn: transFn,
  56095. crisp: false
  56096. });
  56097. Axes.drawGrid(gd, ax, {
  56098. vals: valsClipped,
  56099. layer: _this.layers[axLetter + 'grid'],
  56100. path: gridPath,
  56101. transFn: transFn,
  56102. crisp: false
  56103. });
  56104. var labelFns = Axes.makeLabelFns(ax, 0, counterAngle);
  56105. Axes.drawLabels(gd, ax, {
  56106. vals: vals,
  56107. layer: axLayer,
  56108. transFn: transFn,
  56109. labelXFn: labelFns.labelXFn,
  56110. labelYFn: labelFns.labelYFn,
  56111. labelAnchorFn: labelFns.labelAnchorFn
  56112. });
  56113. };
  56114. function strTickLayout(axLayout) {
  56115. return axLayout.ticks + String(axLayout.ticklen) + String(axLayout.showticklabels);
  56116. }
  56117. // hard coded paths for zoom corners
  56118. // uses the same sizing as cartesian, length is MINZOOM/2, width is 3px
  56119. var CLEN = constants.MINZOOM / 2 + 0.87;
  56120. var BLPATH = 'm-0.87,.5h' + CLEN + 'v3h-' + (CLEN + 5.2) +
  56121. 'l' + (CLEN / 2 + 2.6) + ',-' + (CLEN * 0.87 + 4.5) +
  56122. 'l2.6,1.5l-' + (CLEN / 2) + ',' + (CLEN * 0.87) + 'Z';
  56123. var BRPATH = 'm0.87,.5h-' + CLEN + 'v3h' + (CLEN + 5.2) +
  56124. 'l-' + (CLEN / 2 + 2.6) + ',-' + (CLEN * 0.87 + 4.5) +
  56125. 'l-2.6,1.5l' + (CLEN / 2) + ',' + (CLEN * 0.87) + 'Z';
  56126. var TOPPATH = 'm0,1l' + (CLEN / 2) + ',' + (CLEN * 0.87) +
  56127. 'l2.6,-1.5l-' + (CLEN / 2 + 2.6) + ',-' + (CLEN * 0.87 + 4.5) +
  56128. 'l-' + (CLEN / 2 + 2.6) + ',' + (CLEN * 0.87 + 4.5) +
  56129. 'l2.6,1.5l' + (CLEN / 2) + ',-' + (CLEN * 0.87) + 'Z';
  56130. var STARTMARKER = 'm0.5,0.5h5v-2h-5v-5h-2v5h-5v2h5v5h2Z';
  56131. // I guess this could be shared with cartesian... but for now it's separate.
  56132. var SHOWZOOMOUTTIP = true;
  56133. proto.initInteractions = function() {
  56134. var _this = this;
  56135. var dragger = _this.layers.plotbg.select('path').node();
  56136. var gd = _this.graphDiv;
  56137. var zoomContainer = gd._fullLayout._zoomlayer;
  56138. // use plotbg for the main interactions
  56139. var dragOptions = {
  56140. element: dragger,
  56141. gd: gd,
  56142. plotinfo: {
  56143. id: _this.id,
  56144. xaxis: _this.xaxis,
  56145. yaxis: _this.yaxis
  56146. },
  56147. subplot: _this.id,
  56148. prepFn: function(e, startX, startY) {
  56149. // these aren't available yet when initInteractions
  56150. // is called
  56151. dragOptions.xaxes = [_this.xaxis];
  56152. dragOptions.yaxes = [_this.yaxis];
  56153. var dragModeNow = gd._fullLayout.dragmode;
  56154. if(dragModeNow === 'lasso') dragOptions.minDrag = 1;
  56155. else dragOptions.minDrag = undefined;
  56156. if(dragModeNow === 'zoom') {
  56157. dragOptions.moveFn = zoomMove;
  56158. dragOptions.clickFn = clickZoomPan;
  56159. dragOptions.doneFn = zoomDone;
  56160. zoomPrep(e, startX, startY);
  56161. }
  56162. else if(dragModeNow === 'pan') {
  56163. dragOptions.moveFn = plotDrag;
  56164. dragOptions.clickFn = clickZoomPan;
  56165. dragOptions.doneFn = dragDone;
  56166. panPrep();
  56167. clearSelect(zoomContainer);
  56168. }
  56169. else if(dragModeNow === 'select' || dragModeNow === 'lasso') {
  56170. prepSelect(e, startX, startY, dragOptions, dragModeNow);
  56171. }
  56172. }
  56173. };
  56174. var x0, y0, mins0, span0, mins, lum, path0, dimmed, zb, corners;
  56175. function makeUpdate(_mins) {
  56176. var attrs = {};
  56177. attrs[_this.id + '.aaxis.min'] = _mins.a;
  56178. attrs[_this.id + '.baxis.min'] = _mins.b;
  56179. attrs[_this.id + '.caxis.min'] = _mins.c;
  56180. return attrs;
  56181. }
  56182. function clickZoomPan(numClicks, evt) {
  56183. var clickMode = gd._fullLayout.clickmode;
  56184. removeZoombox(gd);
  56185. if(numClicks === 2) {
  56186. gd.emit('plotly_doubleclick', null);
  56187. Registry.call('_guiRelayout', gd, makeUpdate({a: 0, b: 0, c: 0}));
  56188. }
  56189. if(clickMode.indexOf('select') > -1 && numClicks === 1) {
  56190. selectOnClick(evt, gd, [_this.xaxis], [_this.yaxis], _this.id, dragOptions);
  56191. }
  56192. if(clickMode.indexOf('event') > -1) {
  56193. Fx.click(gd, evt, _this.id);
  56194. }
  56195. }
  56196. function zoomPrep(e, startX, startY) {
  56197. var dragBBox = dragger.getBoundingClientRect();
  56198. x0 = startX - dragBBox.left;
  56199. y0 = startY - dragBBox.top;
  56200. mins0 = {
  56201. a: _this.aaxis.range[0],
  56202. b: _this.baxis.range[1],
  56203. c: _this.caxis.range[1]
  56204. };
  56205. mins = mins0;
  56206. span0 = _this.aaxis.range[1] - mins0.a;
  56207. lum = tinycolor(_this.graphDiv._fullLayout[_this.id].bgcolor).getLuminance();
  56208. path0 = 'M0,' + _this.h + 'L' + (_this.w / 2) + ', 0L' + _this.w + ',' + _this.h + 'Z';
  56209. dimmed = false;
  56210. zb = zoomContainer.append('path')
  56211. .attr('class', 'zoombox')
  56212. .attr('transform', 'translate(' + _this.x0 + ', ' + _this.y0 + ')')
  56213. .style({
  56214. 'fill': lum > 0.2 ? 'rgba(0,0,0,0)' : 'rgba(255,255,255,0)',
  56215. 'stroke-width': 0
  56216. })
  56217. .attr('d', path0);
  56218. corners = zoomContainer.append('path')
  56219. .attr('class', 'zoombox-corners')
  56220. .attr('transform', 'translate(' + _this.x0 + ', ' + _this.y0 + ')')
  56221. .style({
  56222. fill: Color.background,
  56223. stroke: Color.defaultLine,
  56224. 'stroke-width': 1,
  56225. opacity: 0
  56226. })
  56227. .attr('d', 'M0,0Z');
  56228. clearSelect(zoomContainer);
  56229. }
  56230. function getAFrac(x, y) { return 1 - (y / _this.h); }
  56231. function getBFrac(x, y) { return 1 - ((x + (_this.h - y) / Math.sqrt(3)) / _this.w); }
  56232. function getCFrac(x, y) { return ((x - (_this.h - y) / Math.sqrt(3)) / _this.w); }
  56233. function zoomMove(dx0, dy0) {
  56234. var x1 = x0 + dx0;
  56235. var y1 = y0 + dy0;
  56236. var afrac = Math.max(0, Math.min(1, getAFrac(x0, y0), getAFrac(x1, y1)));
  56237. var bfrac = Math.max(0, Math.min(1, getBFrac(x0, y0), getBFrac(x1, y1)));
  56238. var cfrac = Math.max(0, Math.min(1, getCFrac(x0, y0), getCFrac(x1, y1)));
  56239. var xLeft = ((afrac / 2) + cfrac) * _this.w;
  56240. var xRight = (1 - (afrac / 2) - bfrac) * _this.w;
  56241. var xCenter = (xLeft + xRight) / 2;
  56242. var xSpan = xRight - xLeft;
  56243. var yBottom = (1 - afrac) * _this.h;
  56244. var yTop = yBottom - xSpan / whRatio;
  56245. if(xSpan < constants.MINZOOM) {
  56246. mins = mins0;
  56247. zb.attr('d', path0);
  56248. corners.attr('d', 'M0,0Z');
  56249. }
  56250. else {
  56251. mins = {
  56252. a: mins0.a + afrac * span0,
  56253. b: mins0.b + bfrac * span0,
  56254. c: mins0.c + cfrac * span0
  56255. };
  56256. zb.attr('d', path0 + 'M' + xLeft + ',' + yBottom +
  56257. 'H' + xRight + 'L' + xCenter + ',' + yTop +
  56258. 'L' + xLeft + ',' + yBottom + 'Z');
  56259. corners.attr('d', 'M' + x0 + ',' + y0 + STARTMARKER +
  56260. 'M' + xLeft + ',' + yBottom + BLPATH +
  56261. 'M' + xRight + ',' + yBottom + BRPATH +
  56262. 'M' + xCenter + ',' + yTop + TOPPATH);
  56263. }
  56264. if(!dimmed) {
  56265. zb.transition()
  56266. .style('fill', lum > 0.2 ? 'rgba(0,0,0,0.4)' :
  56267. 'rgba(255,255,255,0.3)')
  56268. .duration(200);
  56269. corners.transition()
  56270. .style('opacity', 1)
  56271. .duration(200);
  56272. dimmed = true;
  56273. }
  56274. }
  56275. function zoomDone() {
  56276. removeZoombox(gd);
  56277. if(mins === mins0) return;
  56278. Registry.call('_guiRelayout', gd, makeUpdate(mins));
  56279. if(SHOWZOOMOUTTIP && gd.data && gd._context.showTips) {
  56280. Lib.notifier(_(gd, 'Double-click to zoom back out'), 'long');
  56281. SHOWZOOMOUTTIP = false;
  56282. }
  56283. }
  56284. function panPrep() {
  56285. mins0 = {
  56286. a: _this.aaxis.range[0],
  56287. b: _this.baxis.range[1],
  56288. c: _this.caxis.range[1]
  56289. };
  56290. mins = mins0;
  56291. }
  56292. function plotDrag(dx, dy) {
  56293. var dxScaled = dx / _this.xaxis._m;
  56294. var dyScaled = dy / _this.yaxis._m;
  56295. mins = {
  56296. a: mins0.a - dyScaled,
  56297. b: mins0.b + (dxScaled + dyScaled) / 2,
  56298. c: mins0.c - (dxScaled - dyScaled) / 2
  56299. };
  56300. var minsorted = [mins.a, mins.b, mins.c].sort();
  56301. var minindices = {
  56302. a: minsorted.indexOf(mins.a),
  56303. b: minsorted.indexOf(mins.b),
  56304. c: minsorted.indexOf(mins.c)
  56305. };
  56306. if(minsorted[0] < 0) {
  56307. if(minsorted[1] + minsorted[0] / 2 < 0) {
  56308. minsorted[2] += minsorted[0] + minsorted[1];
  56309. minsorted[0] = minsorted[1] = 0;
  56310. }
  56311. else {
  56312. minsorted[2] += minsorted[0] / 2;
  56313. minsorted[1] += minsorted[0] / 2;
  56314. minsorted[0] = 0;
  56315. }
  56316. mins = {
  56317. a: minsorted[minindices.a],
  56318. b: minsorted[minindices.b],
  56319. c: minsorted[minindices.c]
  56320. };
  56321. dy = (mins0.a - mins.a) * _this.yaxis._m;
  56322. dx = (mins0.c - mins.c - mins0.b + mins.b) * _this.xaxis._m;
  56323. }
  56324. // move the data (translate, don't redraw)
  56325. var plotTransform = 'translate(' + (_this.x0 + dx) + ',' + (_this.y0 + dy) + ')';
  56326. _this.plotContainer.selectAll('.scatterlayer,.maplayer')
  56327. .attr('transform', plotTransform);
  56328. var plotTransform2 = 'translate(' + -dx + ',' + -dy + ')';
  56329. _this.clipDefRelative.select('path').attr('transform', plotTransform2);
  56330. // move the ticks
  56331. _this.aaxis.range = [mins.a, _this.sum - mins.b - mins.c];
  56332. _this.baxis.range = [_this.sum - mins.a - mins.c, mins.b];
  56333. _this.caxis.range = [_this.sum - mins.a - mins.b, mins.c];
  56334. _this.drawAxes(false);
  56335. if(_this._hasClipOnAxisFalse) {
  56336. _this.plotContainer
  56337. .select('.scatterlayer').selectAll('.trace')
  56338. .call(Drawing.hideOutsideRangePoints, _this);
  56339. }
  56340. }
  56341. function dragDone() {
  56342. Registry.call('_guiRelayout', gd, makeUpdate(mins));
  56343. }
  56344. // finally, set up hover and click
  56345. // these event handlers must already be set before dragElement.init
  56346. // so it can stash them and override them.
  56347. dragger.onmousemove = function(evt) {
  56348. Fx.hover(gd, evt, _this.id);
  56349. gd._fullLayout._lasthover = dragger;
  56350. gd._fullLayout._hoversubplot = _this.id;
  56351. };
  56352. dragger.onmouseout = function(evt) {
  56353. if(gd._dragging) return;
  56354. dragElement.unhover(gd, evt);
  56355. };
  56356. dragElement.init(dragOptions);
  56357. };
  56358. function removeZoombox(gd) {
  56359. d3.select(gd)
  56360. .selectAll('.zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners')
  56361. .remove();
  56362. }
  56363. },{"../../components/color":51,"../../components/dragelement":69,"../../components/drawing":72,"../../components/fx":90,"../../components/titles":139,"../../lib":168,"../../lib/extend":162,"../../registry":257,"../cartesian/axes":212,"../cartesian/constants":218,"../cartesian/select":230,"../cartesian/set_convert":231,"../plots":245,"d3":16,"tinycolor2":34}],257:[function(_dereq_,module,exports){
  56364. /**
  56365. * Copyright 2012-2019, Plotly, Inc.
  56366. * All rights reserved.
  56367. *
  56368. * This source code is licensed under the MIT license found in the
  56369. * LICENSE file in the root directory of this source tree.
  56370. */
  56371. 'use strict';
  56372. var Loggers = _dereq_('./lib/loggers');
  56373. var noop = _dereq_('./lib/noop');
  56374. var pushUnique = _dereq_('./lib/push_unique');
  56375. var isPlainObject = _dereq_('./lib/is_plain_object');
  56376. var ExtendModule = _dereq_('./lib/extend');
  56377. var basePlotAttributes = _dereq_('./plots/attributes');
  56378. var baseLayoutAttributes = _dereq_('./plots/layout_attributes');
  56379. var extendFlat = ExtendModule.extendFlat;
  56380. var extendDeepAll = ExtendModule.extendDeepAll;
  56381. exports.modules = {};
  56382. exports.allCategories = {};
  56383. exports.allTypes = [];
  56384. exports.subplotsRegistry = {};
  56385. exports.transformsRegistry = {};
  56386. exports.componentsRegistry = {};
  56387. exports.layoutArrayContainers = [];
  56388. exports.layoutArrayRegexes = [];
  56389. exports.traceLayoutAttributes = {};
  56390. exports.localeRegistry = {};
  56391. exports.apiMethodRegistry = {};
  56392. exports.collectableSubplotTypes = null;
  56393. /**
  56394. * Top-level register routine, exported as Plotly.register
  56395. *
  56396. * @param {object array or array of objects} _modules :
  56397. * module object or list of module object to register.
  56398. *
  56399. * A valid `moduleType: 'trace'` module has fields:
  56400. * - name {string} : the trace type
  56401. * - categories {array} : categories associated with this trace type,
  56402. * tested with Register.traceIs()
  56403. * - meta {object} : meta info (mostly for plot-schema)
  56404. *
  56405. * A valid `moduleType: 'locale'` module has fields:
  56406. * - name {string} : the locale name. Should be a 2-digit language string ('en', 'de')
  56407. * optionally with a country/region code ('en-GB', 'de-CH'). If a country
  56408. * code is used but the base language locale has not yet been supplied,
  56409. * we will use this locale for the base as well.
  56410. * - dictionary {object} : the dictionary mapping input strings to localized strings
  56411. * generally the keys should be the literal input strings, but
  56412. * if default translations are provided you can use any string as a key.
  56413. * - format {object} : a `d3.locale` format specifier for this locale
  56414. * any omitted keys we'll fall back on en-US.
  56415. *
  56416. * A valid `moduleType: 'transform'` module has fields:
  56417. * - name {string} : transform name
  56418. * - transform {function} : default-level transform function
  56419. * - calcTransform {function} : calc-level transform function
  56420. * - attributes {object} : transform attributes declarations
  56421. * - supplyDefaults {function} : attributes default-supply function
  56422. *
  56423. * A valid `moduleType: 'component'` module has fields:
  56424. * - name {string} : the component name, used it with Register.getComponentMethod()
  56425. * to employ component method.
  56426. *
  56427. * A valid `moduleType: 'apiMethod'` module has fields:
  56428. * - name {string} : the api method name.
  56429. * - fn {function} : the api method called with Register.call();
  56430. *
  56431. */
  56432. exports.register = function register(_modules) {
  56433. exports.collectableSubplotTypes = null;
  56434. if(!_modules) {
  56435. throw new Error('No argument passed to Plotly.register.');
  56436. } else if(_modules && !Array.isArray(_modules)) {
  56437. _modules = [_modules];
  56438. }
  56439. for(var i = 0; i < _modules.length; i++) {
  56440. var newModule = _modules[i];
  56441. if(!newModule) {
  56442. throw new Error('Invalid module was attempted to be registered!');
  56443. }
  56444. switch(newModule.moduleType) {
  56445. case 'trace':
  56446. registerTraceModule(newModule);
  56447. break;
  56448. case 'transform':
  56449. registerTransformModule(newModule);
  56450. break;
  56451. case 'component':
  56452. registerComponentModule(newModule);
  56453. break;
  56454. case 'locale':
  56455. registerLocale(newModule);
  56456. break;
  56457. case 'apiMethod':
  56458. var name = newModule.name;
  56459. exports.apiMethodRegistry[name] = newModule.fn;
  56460. break;
  56461. default:
  56462. throw new Error('Invalid module was attempted to be registered!');
  56463. }
  56464. }
  56465. };
  56466. /**
  56467. * Get registered module using trace object or trace type
  56468. *
  56469. * @param {object||string} trace
  56470. * trace object with prop 'type' or trace type as a string
  56471. * @return {object}
  56472. * module object corresponding to trace type
  56473. */
  56474. exports.getModule = function(trace) {
  56475. var _module = exports.modules[getTraceType(trace)];
  56476. if(!_module) return false;
  56477. return _module._module;
  56478. };
  56479. /**
  56480. * Determine if this trace type is in a given category
  56481. *
  56482. * @param {object||string} traceType
  56483. * a trace (object) or trace type (string)
  56484. * @param {string} category
  56485. * category in question
  56486. * @return {boolean}
  56487. */
  56488. exports.traceIs = function(traceType, category) {
  56489. traceType = getTraceType(traceType);
  56490. // old plot.ly workspace hack, nothing to see here
  56491. if(traceType === 'various') return false;
  56492. var _module = exports.modules[traceType];
  56493. if(!_module) {
  56494. if(traceType && traceType !== 'area') {
  56495. Loggers.log('Unrecognized trace type ' + traceType + '.');
  56496. }
  56497. _module = exports.modules[basePlotAttributes.type.dflt];
  56498. }
  56499. return !!_module.categories[category];
  56500. };
  56501. /**
  56502. * Determine if this trace has a transform of the given type and return
  56503. * array of matching indices.
  56504. *
  56505. * @param {object} data
  56506. * a trace object (member of data or fullData)
  56507. * @param {string} type
  56508. * type of trace to test
  56509. * @return {array}
  56510. * array of matching indices. If none found, returns []
  56511. */
  56512. exports.getTransformIndices = function(data, type) {
  56513. var indices = [];
  56514. var transforms = data.transforms || [];
  56515. for(var i = 0; i < transforms.length; i++) {
  56516. if(transforms[i].type === type) {
  56517. indices.push(i);
  56518. }
  56519. }
  56520. return indices;
  56521. };
  56522. /**
  56523. * Determine if this trace has a transform of the given type
  56524. *
  56525. * @param {object} data
  56526. * a trace object (member of data or fullData)
  56527. * @param {string} type
  56528. * type of trace to test
  56529. * @return {boolean}
  56530. */
  56531. exports.hasTransform = function(data, type) {
  56532. var transforms = data.transforms || [];
  56533. for(var i = 0; i < transforms.length; i++) {
  56534. if(transforms[i].type === type) {
  56535. return true;
  56536. }
  56537. }
  56538. return false;
  56539. };
  56540. /**
  56541. * Retrieve component module method. Falls back on noop if either the
  56542. * module or the method is missing, so the result can always be safely called
  56543. *
  56544. * @param {string} name
  56545. * name of component (as declared in component module)
  56546. * @param {string} method
  56547. * name of component module method
  56548. * @return {function}
  56549. */
  56550. exports.getComponentMethod = function(name, method) {
  56551. var _module = exports.componentsRegistry[name];
  56552. if(!_module) return noop;
  56553. return _module[method] || noop;
  56554. };
  56555. /**
  56556. * Call registered api method.
  56557. *
  56558. * @param {string} name : api method name
  56559. * @param {...array} args : arguments passed to api method
  56560. * @return {any} : returns api method output
  56561. */
  56562. exports.call = function() {
  56563. var name = arguments[0];
  56564. var args = [].slice.call(arguments, 1);
  56565. return exports.apiMethodRegistry[name].apply(null, args);
  56566. };
  56567. function registerTraceModule(_module) {
  56568. var thisType = _module.name;
  56569. var categoriesIn = _module.categories;
  56570. var meta = _module.meta;
  56571. if(exports.modules[thisType]) {
  56572. Loggers.log('Type ' + thisType + ' already registered');
  56573. return;
  56574. }
  56575. if(!exports.subplotsRegistry[_module.basePlotModule.name]) {
  56576. registerSubplot(_module.basePlotModule);
  56577. }
  56578. var categoryObj = {};
  56579. for(var i = 0; i < categoriesIn.length; i++) {
  56580. categoryObj[categoriesIn[i]] = true;
  56581. exports.allCategories[categoriesIn[i]] = true;
  56582. }
  56583. exports.modules[thisType] = {
  56584. _module: _module,
  56585. categories: categoryObj
  56586. };
  56587. if(meta && Object.keys(meta).length) {
  56588. exports.modules[thisType].meta = meta;
  56589. }
  56590. exports.allTypes.push(thisType);
  56591. for(var componentName in exports.componentsRegistry) {
  56592. mergeComponentAttrsToTrace(componentName, thisType);
  56593. }
  56594. /*
  56595. * Collect all trace layout attributes in one place for easier lookup later
  56596. * but don't merge them into the base schema as it would confuse the docs
  56597. * (at least after https://github.com/plotly/documentation/issues/202 gets done!)
  56598. */
  56599. if(_module.layoutAttributes) {
  56600. extendFlat(exports.traceLayoutAttributes, _module.layoutAttributes);
  56601. }
  56602. }
  56603. function registerSubplot(_module) {
  56604. var plotType = _module.name;
  56605. if(exports.subplotsRegistry[plotType]) {
  56606. Loggers.log('Plot type ' + plotType + ' already registered.');
  56607. return;
  56608. }
  56609. // relayout array handling will look for component module methods with this
  56610. // name and won't find them because this is a subplot module... but that
  56611. // should be fine, it will just fall back on redrawing the plot.
  56612. findArrayRegexps(_module);
  56613. // not sure what's best for the 'cartesian' type at this point
  56614. exports.subplotsRegistry[plotType] = _module;
  56615. for(var componentName in exports.componentsRegistry) {
  56616. mergeComponentAttrsToSubplot(componentName, _module.name);
  56617. }
  56618. }
  56619. function registerComponentModule(_module) {
  56620. if(typeof _module.name !== 'string') {
  56621. throw new Error('Component module *name* must be a string.');
  56622. }
  56623. var name = _module.name;
  56624. exports.componentsRegistry[name] = _module;
  56625. if(_module.layoutAttributes) {
  56626. if(_module.layoutAttributes._isLinkedToArray) {
  56627. pushUnique(exports.layoutArrayContainers, name);
  56628. }
  56629. findArrayRegexps(_module);
  56630. }
  56631. for(var traceType in exports.modules) {
  56632. mergeComponentAttrsToTrace(name, traceType);
  56633. }
  56634. for(var subplotName in exports.subplotsRegistry) {
  56635. mergeComponentAttrsToSubplot(name, subplotName);
  56636. }
  56637. for(var transformType in exports.transformsRegistry) {
  56638. mergeComponentAttrsToTransform(name, transformType);
  56639. }
  56640. if(_module.schema && _module.schema.layout) {
  56641. extendDeepAll(baseLayoutAttributes, _module.schema.layout);
  56642. }
  56643. }
  56644. function registerTransformModule(_module) {
  56645. if(typeof _module.name !== 'string') {
  56646. throw new Error('Transform module *name* must be a string.');
  56647. }
  56648. var prefix = 'Transform module ' + _module.name;
  56649. var hasTransform = typeof _module.transform === 'function';
  56650. var hasCalcTransform = typeof _module.calcTransform === 'function';
  56651. if(!hasTransform && !hasCalcTransform) {
  56652. throw new Error(prefix + ' is missing a *transform* or *calcTransform* method.');
  56653. }
  56654. if(hasTransform && hasCalcTransform) {
  56655. Loggers.log([
  56656. prefix + ' has both a *transform* and *calcTransform* methods.',
  56657. 'Please note that all *transform* methods are executed',
  56658. 'before all *calcTransform* methods.'
  56659. ].join(' '));
  56660. }
  56661. if(!isPlainObject(_module.attributes)) {
  56662. Loggers.log(prefix + ' registered without an *attributes* object.');
  56663. }
  56664. if(typeof _module.supplyDefaults !== 'function') {
  56665. Loggers.log(prefix + ' registered without a *supplyDefaults* method.');
  56666. }
  56667. exports.transformsRegistry[_module.name] = _module;
  56668. for(var componentName in exports.componentsRegistry) {
  56669. mergeComponentAttrsToTransform(componentName, _module.name);
  56670. }
  56671. }
  56672. function registerLocale(_module) {
  56673. var locale = _module.name;
  56674. var baseLocale = locale.split('-')[0];
  56675. var newDict = _module.dictionary;
  56676. var newFormat = _module.format;
  56677. var hasDict = newDict && Object.keys(newDict).length;
  56678. var hasFormat = newFormat && Object.keys(newFormat).length;
  56679. var locales = exports.localeRegistry;
  56680. var localeObj = locales[locale];
  56681. if(!localeObj) locales[locale] = localeObj = {};
  56682. // Should we use this dict for the base locale?
  56683. // In case we're overwriting a previous dict for this locale, check
  56684. // whether the base matches the full locale dict now. If we're not
  56685. // overwriting, locales[locale] is undefined so this just checks if
  56686. // baseLocale already had a dict or not.
  56687. // Same logic for dateFormats
  56688. if(baseLocale !== locale) {
  56689. var baseLocaleObj = locales[baseLocale];
  56690. if(!baseLocaleObj) locales[baseLocale] = baseLocaleObj = {};
  56691. if(hasDict && baseLocaleObj.dictionary === localeObj.dictionary) {
  56692. baseLocaleObj.dictionary = newDict;
  56693. }
  56694. if(hasFormat && baseLocaleObj.format === localeObj.format) {
  56695. baseLocaleObj.format = newFormat;
  56696. }
  56697. }
  56698. if(hasDict) localeObj.dictionary = newDict;
  56699. if(hasFormat) localeObj.format = newFormat;
  56700. }
  56701. function findArrayRegexps(_module) {
  56702. if(_module.layoutAttributes) {
  56703. var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps;
  56704. if(arrayAttrRegexps) {
  56705. for(var i = 0; i < arrayAttrRegexps.length; i++) {
  56706. pushUnique(exports.layoutArrayRegexes, arrayAttrRegexps[i]);
  56707. }
  56708. }
  56709. }
  56710. }
  56711. function mergeComponentAttrsToTrace(componentName, traceType) {
  56712. var componentSchema = exports.componentsRegistry[componentName].schema;
  56713. if(!componentSchema || !componentSchema.traces) return;
  56714. var traceAttrs = componentSchema.traces[traceType];
  56715. if(traceAttrs) {
  56716. extendDeepAll(exports.modules[traceType]._module.attributes, traceAttrs);
  56717. }
  56718. }
  56719. function mergeComponentAttrsToTransform(componentName, transformType) {
  56720. var componentSchema = exports.componentsRegistry[componentName].schema;
  56721. if(!componentSchema || !componentSchema.transforms) return;
  56722. var transformAttrs = componentSchema.transforms[transformType];
  56723. if(transformAttrs) {
  56724. extendDeepAll(exports.transformsRegistry[transformType].attributes, transformAttrs);
  56725. }
  56726. }
  56727. function mergeComponentAttrsToSubplot(componentName, subplotName) {
  56728. var componentSchema = exports.componentsRegistry[componentName].schema;
  56729. if(!componentSchema || !componentSchema.subplots) return;
  56730. var subplotModule = exports.subplotsRegistry[subplotName];
  56731. var subplotAttrs = subplotModule.layoutAttributes;
  56732. var subplotAttr = subplotModule.attr === 'subplot' ? subplotModule.name : subplotModule.attr;
  56733. if(Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0];
  56734. var componentLayoutAttrs = componentSchema.subplots[subplotAttr];
  56735. if(subplotAttrs && componentLayoutAttrs) {
  56736. extendDeepAll(subplotAttrs, componentLayoutAttrs);
  56737. }
  56738. }
  56739. function getTraceType(traceType) {
  56740. if(typeof traceType === 'object') traceType = traceType.type;
  56741. return traceType;
  56742. }
  56743. },{"./lib/extend":162,"./lib/is_plain_object":169,"./lib/loggers":172,"./lib/noop":177,"./lib/push_unique":181,"./plots/attributes":209,"./plots/layout_attributes":243}],258:[function(_dereq_,module,exports){
  56744. /**
  56745. * Copyright 2012-2019, Plotly, Inc.
  56746. * All rights reserved.
  56747. *
  56748. * This source code is licensed under the MIT license found in the
  56749. * LICENSE file in the root directory of this source tree.
  56750. */
  56751. 'use strict';
  56752. var Lib = _dereq_('../lib');
  56753. var extendFlat = Lib.extendFlat;
  56754. var extendDeep = Lib.extendDeep;
  56755. // Put default plotTile layouts here
  56756. function cloneLayoutOverride(tileClass) {
  56757. var override;
  56758. switch(tileClass) {
  56759. case 'themes__thumb':
  56760. override = {
  56761. autosize: true,
  56762. width: 150,
  56763. height: 150,
  56764. title: {text: ''},
  56765. showlegend: false,
  56766. margin: {l: 5, r: 5, t: 5, b: 5, pad: 0},
  56767. annotations: []
  56768. };
  56769. break;
  56770. case 'thumbnail':
  56771. override = {
  56772. title: {text: ''},
  56773. hidesources: true,
  56774. showlegend: false,
  56775. borderwidth: 0,
  56776. bordercolor: '',
  56777. margin: {l: 1, r: 1, t: 1, b: 1, pad: 0},
  56778. annotations: []
  56779. };
  56780. break;
  56781. default:
  56782. override = {};
  56783. }
  56784. return override;
  56785. }
  56786. function keyIsAxis(keyName) {
  56787. var types = ['xaxis', 'yaxis', 'zaxis'];
  56788. return (types.indexOf(keyName.slice(0, 5)) > -1);
  56789. }
  56790. module.exports = function clonePlot(graphObj, options) {
  56791. // Polar plot compatibility
  56792. if(graphObj.framework && graphObj.framework.isPolar) {
  56793. graphObj = graphObj.framework.getConfig();
  56794. }
  56795. var i;
  56796. var oldData = graphObj.data;
  56797. var oldLayout = graphObj.layout;
  56798. var newData = extendDeep([], oldData);
  56799. var newLayout = extendDeep({}, oldLayout, cloneLayoutOverride(options.tileClass));
  56800. var context = graphObj._context || {};
  56801. if(options.width) newLayout.width = options.width;
  56802. if(options.height) newLayout.height = options.height;
  56803. if(options.tileClass === 'thumbnail' || options.tileClass === 'themes__thumb') {
  56804. // kill annotations
  56805. newLayout.annotations = [];
  56806. var keys = Object.keys(newLayout);
  56807. for(i = 0; i < keys.length; i++) {
  56808. if(keyIsAxis(keys[i])) {
  56809. newLayout[keys[i]].title = {text: ''};
  56810. }
  56811. }
  56812. // kill colorbar and pie labels
  56813. for(i = 0; i < newData.length; i++) {
  56814. var trace = newData[i];
  56815. trace.showscale = false;
  56816. if(trace.marker) trace.marker.showscale = false;
  56817. if(trace.type === 'pie') trace.textposition = 'none';
  56818. }
  56819. }
  56820. if(Array.isArray(options.annotations)) {
  56821. for(i = 0; i < options.annotations.length; i++) {
  56822. newLayout.annotations.push(options.annotations[i]);
  56823. }
  56824. }
  56825. // TODO: does this scene modification really belong here?
  56826. // If we still need it, can it move into the gl3d module?
  56827. var sceneIds = Object.keys(newLayout).filter(function(key) {
  56828. return key.match(/^scene\d*$/);
  56829. });
  56830. if(sceneIds.length) {
  56831. var axesImageOverride = {};
  56832. if(options.tileClass === 'thumbnail') {
  56833. axesImageOverride = {
  56834. title: {text: ''},
  56835. showaxeslabels: false,
  56836. showticklabels: false,
  56837. linetickenable: false
  56838. };
  56839. }
  56840. for(i = 0; i < sceneIds.length; i++) {
  56841. var scene = newLayout[sceneIds[i]];
  56842. if(!scene.xaxis) {
  56843. scene.xaxis = {};
  56844. }
  56845. if(!scene.yaxis) {
  56846. scene.yaxis = {};
  56847. }
  56848. if(!scene.zaxis) {
  56849. scene.zaxis = {};
  56850. }
  56851. extendFlat(scene.xaxis, axesImageOverride);
  56852. extendFlat(scene.yaxis, axesImageOverride);
  56853. extendFlat(scene.zaxis, axesImageOverride);
  56854. // TODO what does this do?
  56855. scene._scene = null;
  56856. }
  56857. }
  56858. var gd = document.createElement('div');
  56859. if(options.tileClass) gd.className = options.tileClass;
  56860. var plotTile = {
  56861. gd: gd,
  56862. td: gd, // for external (image server) compatibility
  56863. layout: newLayout,
  56864. data: newData,
  56865. config: {
  56866. staticPlot: (options.staticPlot === undefined) ?
  56867. true :
  56868. options.staticPlot,
  56869. plotGlPixelRatio: (options.plotGlPixelRatio === undefined) ?
  56870. 2 :
  56871. options.plotGlPixelRatio,
  56872. displaylogo: options.displaylogo || false,
  56873. showLink: options.showLink || false,
  56874. showTips: options.showTips || false,
  56875. mapboxAccessToken: context.mapboxAccessToken
  56876. }
  56877. };
  56878. if(options.setBackground !== 'transparent') {
  56879. plotTile.config.setBackground = options.setBackground || 'opaque';
  56880. }
  56881. // attaching the default Layout the gd, so you can grab it later
  56882. plotTile.gd.defaultLayout = cloneLayoutOverride(options.tileClass);
  56883. return plotTile;
  56884. };
  56885. },{"../lib":168}],259:[function(_dereq_,module,exports){
  56886. /**
  56887. * Copyright 2012-2019, Plotly, Inc.
  56888. * All rights reserved.
  56889. *
  56890. * This source code is licensed under the MIT license found in the
  56891. * LICENSE file in the root directory of this source tree.
  56892. */
  56893. 'use strict';
  56894. var toImage = _dereq_('../plot_api/to_image');
  56895. var Lib = _dereq_('../lib'); // for isIE
  56896. var fileSaver = _dereq_('./filesaver');
  56897. /** Plotly.downloadImage
  56898. *
  56899. * @param {object | string | HTML div} gd
  56900. * can either be a data/layout/config object
  56901. * or an existing graph <div>
  56902. * or an id to an existing graph <div>
  56903. * @param {object} opts (see ../plot_api/to_image)
  56904. * @return {promise}
  56905. */
  56906. function downloadImage(gd, opts) {
  56907. var _gd;
  56908. if(!Lib.isPlainObject(gd)) _gd = Lib.getGraphDiv(gd);
  56909. // check for undefined opts
  56910. opts = opts || {};
  56911. // default to png
  56912. opts.format = opts.format || 'png';
  56913. return new Promise(function(resolve, reject) {
  56914. if(_gd && _gd._snapshotInProgress) {
  56915. reject(new Error('Snapshotting already in progress.'));
  56916. }
  56917. // see comments within svgtoimg for additional
  56918. // discussion of problems with IE
  56919. // can now draw to canvas, but CORS tainted canvas
  56920. // does not allow toDataURL
  56921. // svg format will work though
  56922. if(Lib.isIE() && opts.format !== 'svg') {
  56923. reject(new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.'));
  56924. }
  56925. if(_gd) _gd._snapshotInProgress = true;
  56926. var promise = toImage(gd, opts);
  56927. var filename = opts.filename || gd.fn || 'newplot';
  56928. filename += '.' + opts.format;
  56929. promise.then(function(result) {
  56930. if(_gd) _gd._snapshotInProgress = false;
  56931. return fileSaver(result, filename);
  56932. }).then(function(name) {
  56933. resolve(name);
  56934. }).catch(function(err) {
  56935. if(_gd) _gd._snapshotInProgress = false;
  56936. reject(err);
  56937. });
  56938. });
  56939. }
  56940. module.exports = downloadImage;
  56941. },{"../lib":168,"../plot_api/to_image":205,"./filesaver":260}],260:[function(_dereq_,module,exports){
  56942. /**
  56943. * Copyright 2012-2019, Plotly, Inc.
  56944. * All rights reserved.
  56945. *
  56946. * This source code is licensed under the MIT license found in the
  56947. * LICENSE file in the root directory of this source tree.
  56948. */
  56949. /*
  56950. * substantial portions of this code from FileSaver.js
  56951. * https://github.com/eligrey/FileSaver.js
  56952. * License: https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
  56953. * FileSaver.js
  56954. * A saveAs() FileSaver implementation.
  56955. * 1.1.20160328
  56956. *
  56957. * By Eli Grey, http://eligrey.com
  56958. * License: MIT
  56959. * See https://github.com/eligrey/FileSaver.js/blob/master/LICENSE.md
  56960. */
  56961. 'use strict';
  56962. var fileSaver = function(url, name) {
  56963. var saveLink = document.createElement('a');
  56964. var canUseSaveLink = 'download' in saveLink;
  56965. var isSafari = /Version\/[\d\.]+.*Safari/.test(navigator.userAgent);
  56966. var promise = new Promise(function(resolve, reject) {
  56967. // IE <10 is explicitly unsupported
  56968. if(typeof navigator !== 'undefined' && /MSIE [1-9]\./.test(navigator.userAgent)) {
  56969. reject(new Error('IE < 10 unsupported'));
  56970. }
  56971. // First try a.download, then web filesystem, then object URLs
  56972. if(isSafari) {
  56973. // Safari doesn't allow downloading of blob urls
  56974. document.location.href = 'data:application/octet-stream' + url.slice(url.search(/[,;]/));
  56975. resolve(name);
  56976. }
  56977. if(!name) {
  56978. name = 'download';
  56979. }
  56980. if(canUseSaveLink) {
  56981. saveLink.href = url;
  56982. saveLink.download = name;
  56983. document.body.appendChild(saveLink);
  56984. saveLink.click();
  56985. document.body.removeChild(saveLink);
  56986. resolve(name);
  56987. }
  56988. // IE 10+ (native saveAs)
  56989. if(typeof navigator !== 'undefined' && navigator.msSaveBlob) {
  56990. // At this point we are only dealing with a SVG encoded as
  56991. // a data URL (since IE only supports SVG)
  56992. var encoded = url.split(/^data:image\/svg\+xml,/)[1];
  56993. var svg = decodeURIComponent(encoded);
  56994. navigator.msSaveBlob(new Blob([svg]), name);
  56995. resolve(name);
  56996. }
  56997. reject(new Error('download error'));
  56998. });
  56999. return promise;
  57000. };
  57001. module.exports = fileSaver;
  57002. },{}],261:[function(_dereq_,module,exports){
  57003. /**
  57004. * Copyright 2012-2019, Plotly, Inc.
  57005. * All rights reserved.
  57006. *
  57007. * This source code is licensed under the MIT license found in the
  57008. * LICENSE file in the root directory of this source tree.
  57009. */
  57010. 'use strict';
  57011. exports.getDelay = function(fullLayout) {
  57012. if(!fullLayout._has) return 0;
  57013. return (
  57014. fullLayout._has('gl3d') ||
  57015. fullLayout._has('gl2d') ||
  57016. fullLayout._has('mapbox')
  57017. ) ? 500 : 0;
  57018. };
  57019. exports.getRedrawFunc = function(gd) {
  57020. var fullLayout = gd._fullLayout || {};
  57021. var hasPolar = fullLayout._has && fullLayout._has('polar');
  57022. var hasLegacyPolar = !hasPolar && gd.data && gd.data[0] && gd.data[0].r;
  57023. // do not work for legacy polar
  57024. if(hasLegacyPolar) return;
  57025. return function() {
  57026. (gd.calcdata || []).forEach(function(d) {
  57027. if(d[0] && d[0].t && d[0].t.cb) d[0].t.cb();
  57028. });
  57029. };
  57030. };
  57031. },{}],262:[function(_dereq_,module,exports){
  57032. /**
  57033. * Copyright 2012-2019, Plotly, Inc.
  57034. * All rights reserved.
  57035. *
  57036. * This source code is licensed under the MIT license found in the
  57037. * LICENSE file in the root directory of this source tree.
  57038. */
  57039. 'use strict';
  57040. var helpers = _dereq_('./helpers');
  57041. var Snapshot = {
  57042. getDelay: helpers.getDelay,
  57043. getRedrawFunc: helpers.getRedrawFunc,
  57044. clone: _dereq_('./cloneplot'),
  57045. toSVG: _dereq_('./tosvg'),
  57046. svgToImg: _dereq_('./svgtoimg'),
  57047. toImage: _dereq_('./toimage'),
  57048. downloadImage: _dereq_('./download')
  57049. };
  57050. module.exports = Snapshot;
  57051. },{"./cloneplot":258,"./download":259,"./helpers":261,"./svgtoimg":263,"./toimage":264,"./tosvg":265}],263:[function(_dereq_,module,exports){
  57052. /**
  57053. * Copyright 2012-2019, Plotly, Inc.
  57054. * All rights reserved.
  57055. *
  57056. * This source code is licensed under the MIT license found in the
  57057. * LICENSE file in the root directory of this source tree.
  57058. */
  57059. 'use strict';
  57060. var Lib = _dereq_('../lib');
  57061. var EventEmitter = _dereq_('events').EventEmitter;
  57062. function svgToImg(opts) {
  57063. var ev = opts.emitter || new EventEmitter();
  57064. var promise = new Promise(function(resolve, reject) {
  57065. var Image = window.Image;
  57066. var svg = opts.svg;
  57067. var format = opts.format || 'png';
  57068. // IE only support svg
  57069. if(Lib.isIE() && format !== 'svg') {
  57070. var ieSvgError = new Error('Sorry IE does not support downloading from canvas. Try {format:\'svg\'} instead.');
  57071. reject(ieSvgError);
  57072. // eventually remove the ev
  57073. // in favor of promises
  57074. if(!opts.promise) {
  57075. return ev.emit('error', ieSvgError);
  57076. } else {
  57077. return promise;
  57078. }
  57079. }
  57080. var canvas = opts.canvas;
  57081. var scale = opts.scale || 1;
  57082. var w0 = opts.width || 300;
  57083. var h0 = opts.height || 150;
  57084. var w1 = scale * w0;
  57085. var h1 = scale * h0;
  57086. var ctx = canvas.getContext('2d');
  57087. var img = new Image();
  57088. // for Safari support, eliminate createObjectURL
  57089. // this decision could cause problems if content
  57090. // is not restricted to svg
  57091. var url = 'data:image/svg+xml,' + encodeURIComponent(svg);
  57092. canvas.width = w1;
  57093. canvas.height = h1;
  57094. img.onload = function() {
  57095. var imgData;
  57096. // don't need to draw to canvas if svg
  57097. // save some time and also avoid failure on IE
  57098. if(format !== 'svg') {
  57099. ctx.drawImage(img, 0, 0, w1, h1);
  57100. }
  57101. switch(format) {
  57102. case 'jpeg':
  57103. imgData = canvas.toDataURL('image/jpeg');
  57104. break;
  57105. case 'png':
  57106. imgData = canvas.toDataURL('image/png');
  57107. break;
  57108. case 'webp':
  57109. imgData = canvas.toDataURL('image/webp');
  57110. break;
  57111. case 'svg':
  57112. imgData = url;
  57113. break;
  57114. default:
  57115. var errorMsg = 'Image format is not jpeg, png, svg or webp.';
  57116. reject(new Error(errorMsg));
  57117. // eventually remove the ev
  57118. // in favor of promises
  57119. if(!opts.promise) {
  57120. return ev.emit('error', errorMsg);
  57121. }
  57122. }
  57123. resolve(imgData);
  57124. // eventually remove the ev
  57125. // in favor of promises
  57126. if(!opts.promise) {
  57127. ev.emit('success', imgData);
  57128. }
  57129. };
  57130. img.onerror = function(err) {
  57131. reject(err);
  57132. // eventually remove the ev
  57133. // in favor of promises
  57134. if(!opts.promise) {
  57135. return ev.emit('error', err);
  57136. }
  57137. };
  57138. img.src = url;
  57139. });
  57140. // temporary for backward compatibility
  57141. // move to only Promise in 2.0.0
  57142. // and eliminate the EventEmitter
  57143. if(opts.promise) {
  57144. return promise;
  57145. }
  57146. return ev;
  57147. }
  57148. module.exports = svgToImg;
  57149. },{"../lib":168,"events":15}],264:[function(_dereq_,module,exports){
  57150. /**
  57151. * Copyright 2012-2019, Plotly, Inc.
  57152. * All rights reserved.
  57153. *
  57154. * This source code is licensed under the MIT license found in the
  57155. * LICENSE file in the root directory of this source tree.
  57156. */
  57157. 'use strict';
  57158. var EventEmitter = _dereq_('events').EventEmitter;
  57159. var Registry = _dereq_('../registry');
  57160. var Lib = _dereq_('../lib');
  57161. var helpers = _dereq_('./helpers');
  57162. var clonePlot = _dereq_('./cloneplot');
  57163. var toSVG = _dereq_('./tosvg');
  57164. var svgToImg = _dereq_('./svgtoimg');
  57165. /**
  57166. * @param {object} gd figure Object
  57167. * @param {object} opts option object
  57168. * @param opts.format 'jpeg' | 'png' | 'webp' | 'svg'
  57169. */
  57170. function toImage(gd, opts) {
  57171. // first clone the GD so we can operate in a clean environment
  57172. var ev = new EventEmitter();
  57173. var clone = clonePlot(gd, {format: 'png'});
  57174. var clonedGd = clone.gd;
  57175. // put the cloned div somewhere off screen before attaching to DOM
  57176. clonedGd.style.position = 'absolute';
  57177. clonedGd.style.left = '-5000px';
  57178. document.body.appendChild(clonedGd);
  57179. function wait() {
  57180. var delay = helpers.getDelay(clonedGd._fullLayout);
  57181. setTimeout(function() {
  57182. var svg = toSVG(clonedGd);
  57183. var canvas = document.createElement('canvas');
  57184. canvas.id = Lib.randstr();
  57185. ev = svgToImg({
  57186. format: opts.format,
  57187. width: clonedGd._fullLayout.width,
  57188. height: clonedGd._fullLayout.height,
  57189. canvas: canvas,
  57190. emitter: ev,
  57191. svg: svg
  57192. });
  57193. ev.clean = function() {
  57194. if(clonedGd) document.body.removeChild(clonedGd);
  57195. };
  57196. }, delay);
  57197. }
  57198. var redrawFunc = helpers.getRedrawFunc(clonedGd);
  57199. Registry.call('plot', clonedGd, clone.data, clone.layout, clone.config)
  57200. .then(redrawFunc)
  57201. .then(wait)
  57202. .catch(function(err) {
  57203. ev.emit('error', err);
  57204. });
  57205. return ev;
  57206. }
  57207. module.exports = toImage;
  57208. },{"../lib":168,"../registry":257,"./cloneplot":258,"./helpers":261,"./svgtoimg":263,"./tosvg":265,"events":15}],265:[function(_dereq_,module,exports){
  57209. /**
  57210. * Copyright 2012-2019, Plotly, Inc.
  57211. * All rights reserved.
  57212. *
  57213. * This source code is licensed under the MIT license found in the
  57214. * LICENSE file in the root directory of this source tree.
  57215. */
  57216. 'use strict';
  57217. var d3 = _dereq_('d3');
  57218. var Lib = _dereq_('../lib');
  57219. var Drawing = _dereq_('../components/drawing');
  57220. var Color = _dereq_('../components/color');
  57221. var xmlnsNamespaces = _dereq_('../constants/xmlns_namespaces');
  57222. var DOUBLEQUOTE_REGEX = /"/g;
  57223. var DUMMY_SUB = 'TOBESTRIPPED';
  57224. var DUMMY_REGEX = new RegExp('("' + DUMMY_SUB + ')|(' + DUMMY_SUB + '")', 'g');
  57225. function htmlEntityDecode(s) {
  57226. var hiddenDiv = d3.select('body').append('div').style({display: 'none'}).html('');
  57227. var replaced = s.replace(/(&[^;]*;)/gi, function(d) {
  57228. if(d === '&lt;') { return '&#60;'; } // special handling for brackets
  57229. if(d === '&rt;') { return '&#62;'; }
  57230. if(d.indexOf('<') !== -1 || d.indexOf('>') !== -1) { return ''; }
  57231. return hiddenDiv.html(d).text(); // everything else, let the browser decode it to unicode
  57232. });
  57233. hiddenDiv.remove();
  57234. return replaced;
  57235. }
  57236. function xmlEntityEncode(str) {
  57237. return str.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g, '&amp;');
  57238. }
  57239. module.exports = function toSVG(gd, format, scale) {
  57240. var fullLayout = gd._fullLayout;
  57241. var svg = fullLayout._paper;
  57242. var toppaper = fullLayout._toppaper;
  57243. var width = fullLayout.width;
  57244. var height = fullLayout.height;
  57245. var i;
  57246. // make background color a rect in the svg, then revert after scraping
  57247. // all other alterations have been dealt with by properly preparing the svg
  57248. // in the first place... like setting cursors with css classes so we don't
  57249. // have to remove them, and providing the right namespaces in the svg to
  57250. // begin with
  57251. svg.insert('rect', ':first-child')
  57252. .call(Drawing.setRect, 0, 0, width, height)
  57253. .call(Color.fill, fullLayout.paper_bgcolor);
  57254. // subplot-specific to-SVG methods
  57255. // which notably add the contents of the gl-container
  57256. // into the main svg node
  57257. var basePlotModules = fullLayout._basePlotModules || [];
  57258. for(i = 0; i < basePlotModules.length; i++) {
  57259. var _module = basePlotModules[i];
  57260. if(_module.toSVG) _module.toSVG(gd);
  57261. }
  57262. // add top items above them assumes everything in toppaper is either
  57263. // a group or a defs, and if it's empty (like hoverlayer) we can ignore it.
  57264. if(toppaper) {
  57265. var nodes = toppaper.node().childNodes;
  57266. // make copy of nodes as childNodes prop gets mutated in loop below
  57267. var topGroups = Array.prototype.slice.call(nodes);
  57268. for(i = 0; i < topGroups.length; i++) {
  57269. var topGroup = topGroups[i];
  57270. if(topGroup.childNodes.length) svg.node().appendChild(topGroup);
  57271. }
  57272. }
  57273. // remove draglayer for Adobe Illustrator compatibility
  57274. if(fullLayout._draggers) {
  57275. fullLayout._draggers.remove();
  57276. }
  57277. // in case the svg element had an explicit background color, remove this
  57278. // we want the rect to get the color so it's the right size; svg bg will
  57279. // fill whatever container it's displayed in regardless of plot size.
  57280. svg.node().style.background = '';
  57281. svg.selectAll('text')
  57282. .attr({'data-unformatted': null, 'data-math': null})
  57283. .each(function() {
  57284. var txt = d3.select(this);
  57285. // hidden text is pre-formatting mathjax, the browser ignores it
  57286. // but in a static plot it's useless and it can confuse batik
  57287. // we've tried to standardize on display:none but make sure we still
  57288. // catch visibility:hidden if it ever arises
  57289. if(this.style.visibility === 'hidden' || this.style.display === 'none') {
  57290. txt.remove();
  57291. return;
  57292. }
  57293. else {
  57294. // clear other visibility/display values to default
  57295. // to not potentially confuse non-browser SVG implementations
  57296. txt.style({visibility: null, display: null});
  57297. }
  57298. // Font family styles break things because of quotation marks,
  57299. // so we must remove them *after* the SVG DOM has been serialized
  57300. // to a string (browsers convert singles back)
  57301. var ff = this.style.fontFamily;
  57302. if(ff && ff.indexOf('"') !== -1) {
  57303. txt.style('font-family', ff.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB));
  57304. }
  57305. });
  57306. svg.selectAll('.point, .scatterpts, .legendfill>path, .legendlines>path, .cbfill').each(function() {
  57307. var pt = d3.select(this);
  57308. // similar to font family styles above,
  57309. // we must remove " after the SVG DOM has been serialized
  57310. var fill = this.style.fill;
  57311. if(fill && fill.indexOf('url(') !== -1) {
  57312. pt.style('fill', fill.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB));
  57313. }
  57314. var stroke = this.style.stroke;
  57315. if(stroke && stroke.indexOf('url(') !== -1) {
  57316. pt.style('stroke', stroke.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB));
  57317. }
  57318. });
  57319. if(format === 'pdf' || format === 'eps') {
  57320. // these formats make the extra line MathJax adds around symbols look super thick in some cases
  57321. // it looks better if this is removed entirely.
  57322. svg.selectAll('#MathJax_SVG_glyphs path')
  57323. .attr('stroke-width', 0);
  57324. }
  57325. // fix for IE namespacing quirk?
  57326. // http://stackoverflow.com/questions/19610089/unwanted-namespaces-on-svg-markup-when-using-xmlserializer-in-javascript-with-ie
  57327. svg.node().setAttributeNS(xmlnsNamespaces.xmlns, 'xmlns', xmlnsNamespaces.svg);
  57328. svg.node().setAttributeNS(xmlnsNamespaces.xmlns, 'xmlns:xlink', xmlnsNamespaces.xlink);
  57329. if(format === 'svg' && scale) {
  57330. svg.attr('width', scale * width);
  57331. svg.attr('height', scale * height);
  57332. svg.attr('viewBox', '0 0 ' + width + ' ' + height);
  57333. }
  57334. var s = new window.XMLSerializer().serializeToString(svg.node());
  57335. s = htmlEntityDecode(s);
  57336. s = xmlEntityEncode(s);
  57337. // Fix quotations around font strings and gradient URLs
  57338. s = s.replace(DUMMY_REGEX, '\'');
  57339. // IE is very strict, so we will need to clean
  57340. // svg with the following regex
  57341. // yes this is messy, but do not know a better way
  57342. // Even with this IE will not work due to tainted canvas
  57343. // see https://github.com/kangax/fabric.js/issues/1957
  57344. // http://stackoverflow.com/questions/18112047/canvas-todataurl-working-in-all-browsers-except-ie10
  57345. // Leave here just in case the CORS/tainted IE issue gets resolved
  57346. if(Lib.isIE()) {
  57347. // replace double quote with single quote
  57348. s = s.replace(/"/gi, '\'');
  57349. // url in svg are single quoted
  57350. // since we changed double to single
  57351. // we'll need to change these to double-quoted
  57352. s = s.replace(/(\('#)([^']*)('\))/gi, '(\"#$2\")');
  57353. // font names with spaces will be escaped single-quoted
  57354. // we'll need to change these to double-quoted
  57355. s = s.replace(/(\\')/gi, '\"');
  57356. }
  57357. return s;
  57358. };
  57359. },{"../components/color":51,"../components/drawing":72,"../constants/xmlns_namespaces":150,"../lib":168,"d3":16}],266:[function(_dereq_,module,exports){
  57360. /**
  57361. * Copyright 2012-2019, Plotly, Inc.
  57362. * All rights reserved.
  57363. *
  57364. * This source code is licensed under the MIT license found in the
  57365. * LICENSE file in the root directory of this source tree.
  57366. */
  57367. 'use strict';
  57368. var mergeArray = _dereq_('../../lib').mergeArray;
  57369. // arrayOk attributes, merge them into calcdata array
  57370. module.exports = function arraysToCalcdata(cd, trace) {
  57371. for(var i = 0; i < cd.length; i++) cd[i].i = i;
  57372. mergeArray(trace.text, cd, 'tx');
  57373. mergeArray(trace.hovertext, cd, 'htx');
  57374. var marker = trace.marker;
  57375. if(marker) {
  57376. mergeArray(marker.opacity, cd, 'mo');
  57377. mergeArray(marker.color, cd, 'mc');
  57378. var markerLine = marker.line;
  57379. if(markerLine) {
  57380. mergeArray(markerLine.color, cd, 'mlc');
  57381. mergeArray(markerLine.width, cd, 'mlw');
  57382. }
  57383. }
  57384. };
  57385. },{"../../lib":168}],267:[function(_dereq_,module,exports){
  57386. /**
  57387. * Copyright 2012-2019, Plotly, Inc.
  57388. * All rights reserved.
  57389. *
  57390. * This source code is licensed under the MIT license found in the
  57391. * LICENSE file in the root directory of this source tree.
  57392. */
  57393. 'use strict';
  57394. var scatterAttrs = _dereq_('../scatter/attributes');
  57395. var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
  57396. var colorAttributes = _dereq_('../../components/colorscale/attributes');
  57397. var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
  57398. var fontAttrs = _dereq_('../../plots/font_attributes');
  57399. var constants = _dereq_('./constants.js');
  57400. var extendFlat = _dereq_('../../lib/extend').extendFlat;
  57401. var textFontAttrs = fontAttrs({
  57402. editType: 'calc',
  57403. arrayOk: true,
  57404. colorEditType: 'style',
  57405. });
  57406. var scatterMarkerAttrs = scatterAttrs.marker;
  57407. var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
  57408. var markerLineWidth = extendFlat({},
  57409. scatterMarkerLineAttrs.width, { dflt: 0 });
  57410. var markerLine = extendFlat({
  57411. width: markerLineWidth,
  57412. editType: 'calc'
  57413. }, colorAttributes('marker.line'));
  57414. var marker = extendFlat({
  57415. line: markerLine,
  57416. editType: 'calc'
  57417. }, colorAttributes('marker'), {
  57418. colorbar: colorbarAttrs,
  57419. opacity: {
  57420. valType: 'number',
  57421. arrayOk: true,
  57422. dflt: 1,
  57423. min: 0,
  57424. max: 1,
  57425. editType: 'style',
  57426. }
  57427. });
  57428. module.exports = {
  57429. x: scatterAttrs.x,
  57430. x0: scatterAttrs.x0,
  57431. dx: scatterAttrs.dx,
  57432. y: scatterAttrs.y,
  57433. y0: scatterAttrs.y0,
  57434. dy: scatterAttrs.dy,
  57435. text: scatterAttrs.text,
  57436. hovertext: scatterAttrs.hovertext,
  57437. hovertemplate: hovertemplateAttrs({}, {
  57438. keys: constants.eventDataKeys
  57439. }),
  57440. textposition: {
  57441. valType: 'enumerated',
  57442. values: ['inside', 'outside', 'auto', 'none'],
  57443. dflt: 'none',
  57444. arrayOk: true,
  57445. editType: 'calc',
  57446. },
  57447. textfont: extendFlat({}, textFontAttrs, {
  57448. }),
  57449. insidetextfont: extendFlat({}, textFontAttrs, {
  57450. }),
  57451. outsidetextfont: extendFlat({}, textFontAttrs, {
  57452. }),
  57453. constraintext: {
  57454. valType: 'enumerated',
  57455. values: ['inside', 'outside', 'both', 'none'],
  57456. dflt: 'both',
  57457. editType: 'calc',
  57458. },
  57459. cliponaxis: extendFlat({}, scatterAttrs.cliponaxis, {
  57460. }),
  57461. orientation: {
  57462. valType: 'enumerated',
  57463. values: ['v', 'h'],
  57464. editType: 'calc+clearAxisTypes',
  57465. },
  57466. base: {
  57467. valType: 'any',
  57468. dflt: null,
  57469. arrayOk: true,
  57470. editType: 'calc',
  57471. },
  57472. offset: {
  57473. valType: 'number',
  57474. dflt: null,
  57475. arrayOk: true,
  57476. editType: 'calc',
  57477. },
  57478. width: {
  57479. valType: 'number',
  57480. dflt: null,
  57481. min: 0,
  57482. arrayOk: true,
  57483. editType: 'calc',
  57484. },
  57485. marker: marker,
  57486. selected: {
  57487. marker: {
  57488. opacity: scatterAttrs.selected.marker.opacity,
  57489. color: scatterAttrs.selected.marker.color,
  57490. editType: 'style'
  57491. },
  57492. textfont: scatterAttrs.selected.textfont,
  57493. editType: 'style'
  57494. },
  57495. unselected: {
  57496. marker: {
  57497. opacity: scatterAttrs.unselected.marker.opacity,
  57498. color: scatterAttrs.unselected.marker.color,
  57499. editType: 'style'
  57500. },
  57501. textfont: scatterAttrs.unselected.textfont,
  57502. editType: 'style'
  57503. },
  57504. r: scatterAttrs.r,
  57505. t: scatterAttrs.t,
  57506. _deprecated: {
  57507. bardir: {
  57508. valType: 'enumerated',
  57509. editType: 'calc',
  57510. values: ['v', 'h'],
  57511. }
  57512. }
  57513. };
  57514. },{"../../components/colorbar/attributes":52,"../../components/colorscale/attributes":58,"../../components/fx/hovertemplate_attributes":89,"../../lib/extend":162,"../../plots/font_attributes":239,"../scatter/attributes":367,"./constants.js":269}],268:[function(_dereq_,module,exports){
  57515. /**
  57516. * Copyright 2012-2019, Plotly, Inc.
  57517. * All rights reserved.
  57518. *
  57519. * This source code is licensed under the MIT license found in the
  57520. * LICENSE file in the root directory of this source tree.
  57521. */
  57522. 'use strict';
  57523. var Axes = _dereq_('../../plots/cartesian/axes');
  57524. var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
  57525. var colorscaleCalc = _dereq_('../../components/colorscale/calc');
  57526. var arraysToCalcdata = _dereq_('./arrays_to_calcdata');
  57527. var calcSelection = _dereq_('../scatter/calc_selection');
  57528. module.exports = function calc(gd, trace) {
  57529. var xa = Axes.getFromId(gd, trace.xaxis || 'x');
  57530. var ya = Axes.getFromId(gd, trace.yaxis || 'y');
  57531. var size, pos;
  57532. if(trace.orientation === 'h') {
  57533. size = xa.makeCalcdata(trace, 'x');
  57534. pos = ya.makeCalcdata(trace, 'y');
  57535. } else {
  57536. size = ya.makeCalcdata(trace, 'y');
  57537. pos = xa.makeCalcdata(trace, 'x');
  57538. }
  57539. // create the "calculated data" to plot
  57540. var serieslen = Math.min(pos.length, size.length);
  57541. var cd = new Array(serieslen);
  57542. // set position and size
  57543. for(var i = 0; i < serieslen; i++) {
  57544. cd[i] = { p: pos[i], s: size[i] };
  57545. if(trace.ids) {
  57546. cd[i].id = String(trace.ids[i]);
  57547. }
  57548. }
  57549. // auto-z and autocolorscale if applicable
  57550. if(hasColorscale(trace, 'marker')) {
  57551. colorscaleCalc(gd, trace, {
  57552. vals: trace.marker.color,
  57553. containerStr: 'marker',
  57554. cLetter: 'c'
  57555. });
  57556. }
  57557. if(hasColorscale(trace, 'marker.line')) {
  57558. colorscaleCalc(gd, trace, {
  57559. vals: trace.marker.line.color,
  57560. containerStr: 'marker.line',
  57561. cLetter: 'c'
  57562. });
  57563. }
  57564. arraysToCalcdata(cd, trace);
  57565. calcSelection(cd, trace);
  57566. return cd;
  57567. };
  57568. },{"../../components/colorscale/calc":59,"../../components/colorscale/helpers":62,"../../plots/cartesian/axes":212,"../scatter/calc_selection":369,"./arrays_to_calcdata":266}],269:[function(_dereq_,module,exports){
  57569. /**
  57570. * Copyright 2012-2019, Plotly, Inc.
  57571. * All rights reserved.
  57572. *
  57573. * This source code is licensed under the MIT license found in the
  57574. * LICENSE file in the root directory of this source tree.
  57575. */
  57576. 'use strict';
  57577. module.exports = {
  57578. eventDataKeys: []
  57579. };
  57580. },{}],270:[function(_dereq_,module,exports){
  57581. /**
  57582. * Copyright 2012-2019, Plotly, Inc.
  57583. * All rights reserved.
  57584. *
  57585. * This source code is licensed under the MIT license found in the
  57586. * LICENSE file in the root directory of this source tree.
  57587. */
  57588. 'use strict';
  57589. var isNumeric = _dereq_('fast-isnumeric');
  57590. var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;
  57591. var BADNUM = _dereq_('../../constants/numerical').BADNUM;
  57592. var Registry = _dereq_('../../registry');
  57593. var Axes = _dereq_('../../plots/cartesian/axes');
  57594. var Sieve = _dereq_('./sieve.js');
  57595. /*
  57596. * Bar chart stacking/grouping positioning and autoscaling calculations
  57597. * for each direction separately calculate the ranges and positions
  57598. * note that this handles histograms too
  57599. * now doing this one subplot at a time
  57600. */
  57601. function crossTraceCalc(gd, plotinfo) {
  57602. var xa = plotinfo.xaxis;
  57603. var ya = plotinfo.yaxis;
  57604. var fullTraces = gd._fullData;
  57605. var calcTraces = gd.calcdata;
  57606. var calcTracesHorizontal = [];
  57607. var calcTracesVertical = [];
  57608. for(var i = 0; i < fullTraces.length; i++) {
  57609. var fullTrace = fullTraces[i];
  57610. if(
  57611. fullTrace.visible === true &&
  57612. Registry.traceIs(fullTrace, 'bar') &&
  57613. fullTrace.xaxis === xa._id &&
  57614. fullTrace.yaxis === ya._id
  57615. ) {
  57616. if(fullTrace.orientation === 'h') {
  57617. calcTracesHorizontal.push(calcTraces[i]);
  57618. } else {
  57619. calcTracesVertical.push(calcTraces[i]);
  57620. }
  57621. }
  57622. }
  57623. setGroupPositions(gd, xa, ya, calcTracesVertical);
  57624. setGroupPositions(gd, ya, xa, calcTracesHorizontal);
  57625. }
  57626. function setGroupPositions(gd, pa, sa, calcTraces) {
  57627. if(!calcTraces.length) return;
  57628. var barmode = gd._fullLayout.barmode;
  57629. var overlay = (barmode === 'overlay');
  57630. var group = (barmode === 'group');
  57631. var excluded;
  57632. var included;
  57633. var i, calcTrace, fullTrace;
  57634. initBase(gd, pa, sa, calcTraces);
  57635. if(overlay) {
  57636. setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces);
  57637. } else if(group) {
  57638. // exclude from the group those traces for which the user set an offset
  57639. excluded = [];
  57640. included = [];
  57641. for(i = 0; i < calcTraces.length; i++) {
  57642. calcTrace = calcTraces[i];
  57643. fullTrace = calcTrace[0].trace;
  57644. if(fullTrace.offset === undefined) included.push(calcTrace);
  57645. else excluded.push(calcTrace);
  57646. }
  57647. if(included.length) {
  57648. setGroupPositionsInGroupMode(gd, pa, sa, included);
  57649. }
  57650. if(excluded.length) {
  57651. setGroupPositionsInOverlayMode(gd, pa, sa, excluded);
  57652. }
  57653. } else {
  57654. // exclude from the stack those traces for which the user set a base
  57655. excluded = [];
  57656. included = [];
  57657. for(i = 0; i < calcTraces.length; i++) {
  57658. calcTrace = calcTraces[i];
  57659. fullTrace = calcTrace[0].trace;
  57660. if(fullTrace.base === undefined) included.push(calcTrace);
  57661. else excluded.push(calcTrace);
  57662. }
  57663. if(included.length) {
  57664. setGroupPositionsInStackOrRelativeMode(gd, pa, sa, included);
  57665. }
  57666. if(excluded.length) {
  57667. setGroupPositionsInOverlayMode(gd, pa, sa, excluded);
  57668. }
  57669. }
  57670. collectExtents(calcTraces, pa);
  57671. }
  57672. function initBase(gd, pa, sa, calcTraces) {
  57673. var i, j;
  57674. for(i = 0; i < calcTraces.length; i++) {
  57675. var cd = calcTraces[i];
  57676. var trace = cd[0].trace;
  57677. var base = trace.base;
  57678. var b;
  57679. // not sure if it really makes sense to have dates for bar size data...
  57680. // ideally if we want to make gantt charts or something we'd treat
  57681. // the actual size (trace.x or y) as time delta but base as absolute
  57682. // time. But included here for completeness.
  57683. var scalendar = trace.orientation === 'h' ? trace.xcalendar : trace.ycalendar;
  57684. // 'base' on categorical axes makes no sense
  57685. var d2c = sa.type === 'category' || sa.type === 'multicategory' ?
  57686. function() { return null; } :
  57687. sa.d2c;
  57688. if(isArrayOrTypedArray(base)) {
  57689. for(j = 0; j < Math.min(base.length, cd.length); j++) {
  57690. b = d2c(base[j], 0, scalendar);
  57691. if(isNumeric(b)) {
  57692. cd[j].b = +b;
  57693. cd[j].hasB = 1;
  57694. }
  57695. else cd[j].b = 0;
  57696. }
  57697. for(; j < cd.length; j++) {
  57698. cd[j].b = 0;
  57699. }
  57700. } else {
  57701. b = d2c(base, 0, scalendar);
  57702. var hasBase = isNumeric(b);
  57703. b = hasBase ? b : 0;
  57704. for(j = 0; j < cd.length; j++) {
  57705. cd[j].b = b;
  57706. if(hasBase) cd[j].hasB = 1;
  57707. }
  57708. }
  57709. }
  57710. }
  57711. function setGroupPositionsInOverlayMode(gd, pa, sa, calcTraces) {
  57712. var barnorm = gd._fullLayout.barnorm;
  57713. var separateNegativeValues = false;
  57714. var dontMergeOverlappingData = !barnorm;
  57715. // update position axis and set bar offsets and widths
  57716. for(var i = 0; i < calcTraces.length; i++) {
  57717. var calcTrace = calcTraces[i];
  57718. var sieve = new Sieve([calcTrace], separateNegativeValues, dontMergeOverlappingData);
  57719. // set bar offsets and widths, and update position axis
  57720. setOffsetAndWidth(gd, pa, sieve);
  57721. // set bar bases and sizes, and update size axis
  57722. //
  57723. // (note that `setGroupPositionsInOverlayMode` handles the case barnorm
  57724. // is defined, because this function is also invoked for traces that
  57725. // can't be grouped or stacked)
  57726. if(barnorm) {
  57727. sieveBars(gd, sa, sieve);
  57728. normalizeBars(gd, sa, sieve);
  57729. } else {
  57730. setBaseAndTop(gd, sa, sieve);
  57731. }
  57732. }
  57733. }
  57734. function setGroupPositionsInGroupMode(gd, pa, sa, calcTraces) {
  57735. var fullLayout = gd._fullLayout;
  57736. var barnorm = fullLayout.barnorm;
  57737. var separateNegativeValues = false;
  57738. var dontMergeOverlappingData = !barnorm;
  57739. var sieve = new Sieve(calcTraces, separateNegativeValues, dontMergeOverlappingData);
  57740. // set bar offsets and widths, and update position axis
  57741. setOffsetAndWidthInGroupMode(gd, pa, sieve);
  57742. // set bar bases and sizes, and update size axis
  57743. if(barnorm) {
  57744. sieveBars(gd, sa, sieve);
  57745. normalizeBars(gd, sa, sieve);
  57746. } else {
  57747. setBaseAndTop(gd, sa, sieve);
  57748. }
  57749. }
  57750. function setGroupPositionsInStackOrRelativeMode(gd, pa, sa, calcTraces) {
  57751. var fullLayout = gd._fullLayout;
  57752. var barmode = fullLayout.barmode;
  57753. var stack = barmode === 'stack';
  57754. var relative = barmode === 'relative';
  57755. var barnorm = fullLayout.barnorm;
  57756. var separateNegativeValues = relative;
  57757. var dontMergeOverlappingData = !(barnorm || stack || relative);
  57758. var sieve = new Sieve(calcTraces, separateNegativeValues, dontMergeOverlappingData);
  57759. // set bar offsets and widths, and update position axis
  57760. setOffsetAndWidth(gd, pa, sieve);
  57761. // set bar bases and sizes, and update size axis
  57762. stackBars(gd, sa, sieve);
  57763. // flag the outmost bar (for text display purposes)
  57764. for(var i = 0; i < calcTraces.length; i++) {
  57765. var calcTrace = calcTraces[i];
  57766. for(var j = 0; j < calcTrace.length; j++) {
  57767. var bar = calcTrace[j];
  57768. if(bar.s !== BADNUM) {
  57769. var isOutmostBar = ((bar.b + bar.s) === sieve.get(bar.p, bar.s));
  57770. if(isOutmostBar) bar._outmost = true;
  57771. }
  57772. }
  57773. }
  57774. // Note that marking the outmost bars has to be done
  57775. // before `normalizeBars` changes `bar.b` and `bar.s`.
  57776. if(barnorm) normalizeBars(gd, sa, sieve);
  57777. }
  57778. function setOffsetAndWidth(gd, pa, sieve) {
  57779. var fullLayout = gd._fullLayout;
  57780. var bargap = fullLayout.bargap;
  57781. var bargroupgap = fullLayout.bargroupgap || 0;
  57782. var minDiff = sieve.minDiff;
  57783. var calcTraces = sieve.traces;
  57784. // set bar offsets and widths
  57785. var barGroupWidth = minDiff * (1 - bargap);
  57786. var barWidthPlusGap = barGroupWidth;
  57787. var barWidth = barWidthPlusGap * (1 - bargroupgap);
  57788. // computer bar group center and bar offset
  57789. var offsetFromCenter = -barWidth / 2;
  57790. for(var i = 0; i < calcTraces.length; i++) {
  57791. var calcTrace = calcTraces[i];
  57792. var t = calcTrace[0].t;
  57793. // store bar width and offset for this trace
  57794. t.barwidth = barWidth;
  57795. t.poffset = offsetFromCenter;
  57796. t.bargroupwidth = barGroupWidth;
  57797. t.bardelta = minDiff;
  57798. }
  57799. // stack bars that only differ by rounding
  57800. sieve.binWidth = calcTraces[0][0].t.barwidth / 100;
  57801. // if defined, apply trace offset and width
  57802. applyAttributes(sieve);
  57803. // store the bar center in each calcdata item
  57804. setBarCenterAndWidth(gd, pa, sieve);
  57805. // update position axes
  57806. updatePositionAxis(gd, pa, sieve);
  57807. }
  57808. function setOffsetAndWidthInGroupMode(gd, pa, sieve) {
  57809. var fullLayout = gd._fullLayout;
  57810. var bargap = fullLayout.bargap;
  57811. var bargroupgap = fullLayout.bargroupgap || 0;
  57812. var positions = sieve.positions;
  57813. var distinctPositions = sieve.distinctPositions;
  57814. var minDiff = sieve.minDiff;
  57815. var calcTraces = sieve.traces;
  57816. // if there aren't any overlapping positions,
  57817. // let them have full width even if mode is group
  57818. var overlap = (positions.length !== distinctPositions.length);
  57819. var nTraces = calcTraces.length;
  57820. var barGroupWidth = minDiff * (1 - bargap);
  57821. var barWidthPlusGap = (overlap) ? barGroupWidth / nTraces : barGroupWidth;
  57822. var barWidth = barWidthPlusGap * (1 - bargroupgap);
  57823. for(var i = 0; i < nTraces; i++) {
  57824. var calcTrace = calcTraces[i];
  57825. var t = calcTrace[0].t;
  57826. // computer bar group center and bar offset
  57827. var offsetFromCenter = overlap ?
  57828. ((2 * i + 1 - nTraces) * barWidthPlusGap - barWidth) / 2 :
  57829. -barWidth / 2;
  57830. // store bar width and offset for this trace
  57831. t.barwidth = barWidth;
  57832. t.poffset = offsetFromCenter;
  57833. t.bargroupwidth = barGroupWidth;
  57834. t.bardelta = minDiff;
  57835. }
  57836. // stack bars that only differ by rounding
  57837. sieve.binWidth = calcTraces[0][0].t.barwidth / 100;
  57838. // if defined, apply trace width
  57839. applyAttributes(sieve);
  57840. // store the bar center in each calcdata item
  57841. setBarCenterAndWidth(gd, pa, sieve);
  57842. // update position axes
  57843. updatePositionAxis(gd, pa, sieve, overlap);
  57844. }
  57845. function applyAttributes(sieve) {
  57846. var calcTraces = sieve.traces;
  57847. var i, j;
  57848. for(i = 0; i < calcTraces.length; i++) {
  57849. var calcTrace = calcTraces[i];
  57850. var calcTrace0 = calcTrace[0];
  57851. var fullTrace = calcTrace0.trace;
  57852. var t = calcTrace0.t;
  57853. var offset = fullTrace._offset || fullTrace.offset;
  57854. var initialPoffset = t.poffset;
  57855. var newPoffset;
  57856. if(isArrayOrTypedArray(offset)) {
  57857. // if offset is an array, then clone it into t.poffset.
  57858. newPoffset = Array.prototype.slice.call(offset, 0, calcTrace.length);
  57859. // guard against non-numeric items
  57860. for(j = 0; j < newPoffset.length; j++) {
  57861. if(!isNumeric(newPoffset[j])) {
  57862. newPoffset[j] = initialPoffset;
  57863. }
  57864. }
  57865. // if the length of the array is too short,
  57866. // then extend it with the initial value of t.poffset
  57867. for(j = newPoffset.length; j < calcTrace.length; j++) {
  57868. newPoffset.push(initialPoffset);
  57869. }
  57870. t.poffset = newPoffset;
  57871. } else if(offset !== undefined) {
  57872. t.poffset = offset;
  57873. }
  57874. var width = fullTrace._width || fullTrace.width;
  57875. var initialBarwidth = t.barwidth;
  57876. if(isArrayOrTypedArray(width)) {
  57877. // if width is an array, then clone it into t.barwidth.
  57878. var newBarwidth = Array.prototype.slice.call(width, 0, calcTrace.length);
  57879. // guard against non-numeric items
  57880. for(j = 0; j < newBarwidth.length; j++) {
  57881. if(!isNumeric(newBarwidth[j])) newBarwidth[j] = initialBarwidth;
  57882. }
  57883. // if the length of the array is too short,
  57884. // then extend it with the initial value of t.barwidth
  57885. for(j = newBarwidth.length; j < calcTrace.length; j++) {
  57886. newBarwidth.push(initialBarwidth);
  57887. }
  57888. t.barwidth = newBarwidth;
  57889. // if user didn't set offset,
  57890. // then correct t.poffset to ensure bars remain centered
  57891. if(offset === undefined) {
  57892. newPoffset = [];
  57893. for(j = 0; j < calcTrace.length; j++) {
  57894. newPoffset.push(
  57895. initialPoffset + (initialBarwidth - newBarwidth[j]) / 2
  57896. );
  57897. }
  57898. t.poffset = newPoffset;
  57899. }
  57900. } else if(width !== undefined) {
  57901. t.barwidth = width;
  57902. // if user didn't set offset,
  57903. // then correct t.poffset to ensure bars remain centered
  57904. if(offset === undefined) {
  57905. t.poffset = initialPoffset + (initialBarwidth - width) / 2;
  57906. }
  57907. }
  57908. }
  57909. }
  57910. function setBarCenterAndWidth(gd, pa, sieve) {
  57911. var calcTraces = sieve.traces;
  57912. var pLetter = getAxisLetter(pa);
  57913. for(var i = 0; i < calcTraces.length; i++) {
  57914. var calcTrace = calcTraces[i];
  57915. var t = calcTrace[0].t;
  57916. var poffset = t.poffset;
  57917. var poffsetIsArray = Array.isArray(poffset);
  57918. var barwidth = t.barwidth;
  57919. var barwidthIsArray = Array.isArray(barwidth);
  57920. for(var j = 0; j < calcTrace.length; j++) {
  57921. var calcBar = calcTrace[j];
  57922. // store the actual bar width and position, for use by hover
  57923. var width = calcBar.w = barwidthIsArray ? barwidth[j] : barwidth;
  57924. calcBar[pLetter] = calcBar.p + (poffsetIsArray ? poffset[j] : poffset) + width / 2;
  57925. }
  57926. }
  57927. }
  57928. function updatePositionAxis(gd, pa, sieve, allowMinDtick) {
  57929. var calcTraces = sieve.traces;
  57930. var minDiff = sieve.minDiff;
  57931. var vpad = minDiff / 2;
  57932. Axes.minDtick(pa, sieve.minDiff, sieve.distinctPositions[0], allowMinDtick);
  57933. for(var i = 0; i < calcTraces.length; i++) {
  57934. var calcTrace = calcTraces[i];
  57935. var calcTrace0 = calcTrace[0];
  57936. var fullTrace = calcTrace0.trace;
  57937. var pts = [];
  57938. var bar, l, r, j;
  57939. for(j = 0; j < calcTrace.length; j++) {
  57940. bar = calcTrace[j];
  57941. l = bar.p - vpad;
  57942. r = bar.p + vpad;
  57943. pts.push(l, r);
  57944. }
  57945. if(fullTrace.width || fullTrace.offset) {
  57946. var t = calcTrace0.t;
  57947. var poffset = t.poffset;
  57948. var barwidth = t.barwidth;
  57949. var poffsetIsArray = Array.isArray(poffset);
  57950. var barwidthIsArray = Array.isArray(barwidth);
  57951. for(j = 0; j < calcTrace.length; j++) {
  57952. bar = calcTrace[j];
  57953. var calcBarOffset = poffsetIsArray ? poffset[j] : poffset;
  57954. var calcBarWidth = barwidthIsArray ? barwidth[j] : barwidth;
  57955. l = bar.p + calcBarOffset;
  57956. r = l + calcBarWidth;
  57957. pts.push(l, r);
  57958. }
  57959. }
  57960. fullTrace._extremes[pa._id] = Axes.findExtremes(pa, pts, {padded: false});
  57961. }
  57962. }
  57963. // store these bar bases and tops in calcdata
  57964. // and make sure the size axis includes zero,
  57965. // along with the bases and tops of each bar.
  57966. function setBaseAndTop(gd, sa, sieve) {
  57967. var calcTraces = sieve.traces;
  57968. var sLetter = getAxisLetter(sa);
  57969. for(var i = 0; i < calcTraces.length; i++) {
  57970. var calcTrace = calcTraces[i];
  57971. var fullTrace = calcTrace[0].trace;
  57972. var pts = [];
  57973. var allBarBaseAboveZero = true;
  57974. for(var j = 0; j < calcTrace.length; j++) {
  57975. var bar = calcTrace[j];
  57976. var barBase = bar.b;
  57977. var barTop = barBase + bar.s;
  57978. bar[sLetter] = barTop;
  57979. pts.push(barTop);
  57980. if(bar.hasB) pts.push(barBase);
  57981. if(!bar.hasB || !(bar.b > 0 && bar.s > 0)) {
  57982. allBarBaseAboveZero = false;
  57983. }
  57984. }
  57985. fullTrace._extremes[sa._id] = Axes.findExtremes(sa, pts, {
  57986. tozero: !allBarBaseAboveZero,
  57987. padded: true
  57988. });
  57989. }
  57990. }
  57991. function stackBars(gd, sa, sieve) {
  57992. var fullLayout = gd._fullLayout;
  57993. var barnorm = fullLayout.barnorm;
  57994. var sLetter = getAxisLetter(sa);
  57995. var calcTraces = sieve.traces;
  57996. for(var i = 0; i < calcTraces.length; i++) {
  57997. var calcTrace = calcTraces[i];
  57998. var fullTrace = calcTrace[0].trace;
  57999. var pts = [];
  58000. for(var j = 0; j < calcTrace.length; j++) {
  58001. var bar = calcTrace[j];
  58002. if(bar.s !== BADNUM) {
  58003. // stack current bar and get previous sum
  58004. var barBase = sieve.put(bar.p, bar.b + bar.s);
  58005. var barTop = barBase + bar.b + bar.s;
  58006. // store the bar base and top in each calcdata item
  58007. bar.b = barBase;
  58008. bar[sLetter] = barTop;
  58009. if(!barnorm) {
  58010. pts.push(barTop);
  58011. if(bar.hasB) pts.push(barBase);
  58012. }
  58013. }
  58014. }
  58015. // if barnorm is set, let normalizeBars update the axis range
  58016. if(!barnorm) {
  58017. fullTrace._extremes[sa._id] = Axes.findExtremes(sa, pts, {
  58018. // N.B. we don't stack base with 'base',
  58019. // so set tozero:true always!
  58020. tozero: true,
  58021. padded: true
  58022. });
  58023. }
  58024. }
  58025. }
  58026. function sieveBars(gd, sa, sieve) {
  58027. var calcTraces = sieve.traces;
  58028. for(var i = 0; i < calcTraces.length; i++) {
  58029. var calcTrace = calcTraces[i];
  58030. for(var j = 0; j < calcTrace.length; j++) {
  58031. var bar = calcTrace[j];
  58032. if(bar.s !== BADNUM) sieve.put(bar.p, bar.b + bar.s);
  58033. }
  58034. }
  58035. }
  58036. // Note:
  58037. //
  58038. // normalizeBars requires that either sieveBars or stackBars has been
  58039. // previously invoked.
  58040. function normalizeBars(gd, sa, sieve) {
  58041. var fullLayout = gd._fullLayout;
  58042. var calcTraces = sieve.traces;
  58043. var sLetter = getAxisLetter(sa);
  58044. var sTop = fullLayout.barnorm === 'fraction' ? 1 : 100;
  58045. var sTiny = sTop / 1e9; // in case of rounding error in sum
  58046. var sMin = sa.l2c(sa.c2l(0));
  58047. var sMax = fullLayout.barmode === 'stack' ? sTop : sMin;
  58048. function needsPadding(v) {
  58049. return (
  58050. isNumeric(sa.c2l(v)) &&
  58051. ((v < sMin - sTiny) || (v > sMax + sTiny) || !isNumeric(sMin))
  58052. );
  58053. }
  58054. for(var i = 0; i < calcTraces.length; i++) {
  58055. var calcTrace = calcTraces[i];
  58056. var fullTrace = calcTrace[0].trace;
  58057. var pts = [];
  58058. var allBarBaseAboveZero = true;
  58059. var padded = false;
  58060. for(var j = 0; j < calcTrace.length; j++) {
  58061. var bar = calcTrace[j];
  58062. if(bar.s !== BADNUM) {
  58063. var scale = Math.abs(sTop / sieve.get(bar.p, bar.s));
  58064. bar.b *= scale;
  58065. bar.s *= scale;
  58066. var barBase = bar.b;
  58067. var barTop = barBase + bar.s;
  58068. bar[sLetter] = barTop;
  58069. pts.push(barTop);
  58070. padded = padded || needsPadding(barTop);
  58071. if(bar.hasB) {
  58072. pts.push(barBase);
  58073. padded = padded || needsPadding(barBase);
  58074. }
  58075. if(!bar.hasB || !(bar.b > 0 && bar.s > 0)) {
  58076. allBarBaseAboveZero = false;
  58077. }
  58078. }
  58079. }
  58080. fullTrace._extremes[sa._id] = Axes.findExtremes(sa, pts, {
  58081. tozero: !allBarBaseAboveZero,
  58082. padded: padded
  58083. });
  58084. }
  58085. }
  58086. // find the full position span of bars at each position
  58087. // for use by hover, to ensure labels move in if bars are
  58088. // narrower than the space they're in.
  58089. // run once per trace group (subplot & direction) and
  58090. // the same mapping is attached to all calcdata traces
  58091. function collectExtents(calcTraces, pa) {
  58092. var pLetter = getAxisLetter(pa);
  58093. var extents = {};
  58094. var i, j, cd;
  58095. var pMin = Infinity;
  58096. var pMax = -Infinity;
  58097. for(i = 0; i < calcTraces.length; i++) {
  58098. cd = calcTraces[i];
  58099. for(j = 0; j < cd.length; j++) {
  58100. var p = cd[j].p;
  58101. if(isNumeric(p)) {
  58102. pMin = Math.min(pMin, p);
  58103. pMax = Math.max(pMax, p);
  58104. }
  58105. }
  58106. }
  58107. // this is just for positioning of hover labels, and nobody will care if
  58108. // the label is 1px too far out; so round positions to 1/10K in case
  58109. // position values don't exactly match from trace to trace
  58110. var roundFactor = 10000 / (pMax - pMin);
  58111. var round = extents.round = function(p) {
  58112. return String(Math.round(roundFactor * (p - pMin)));
  58113. };
  58114. for(i = 0; i < calcTraces.length; i++) {
  58115. cd = calcTraces[i];
  58116. cd[0].t.extents = extents;
  58117. var poffset = cd[0].t.poffset;
  58118. var poffsetIsArray = Array.isArray(poffset);
  58119. for(j = 0; j < cd.length; j++) {
  58120. var di = cd[j];
  58121. var p0 = di[pLetter] - di.w / 2;
  58122. if(isNumeric(p0)) {
  58123. var p1 = di[pLetter] + di.w / 2;
  58124. var pVal = round(di.p);
  58125. if(extents[pVal]) {
  58126. extents[pVal] = [Math.min(p0, extents[pVal][0]), Math.max(p1, extents[pVal][1])];
  58127. } else {
  58128. extents[pVal] = [p0, p1];
  58129. }
  58130. }
  58131. di.p0 = di.p + (poffsetIsArray ? poffset[j] : poffset);
  58132. di.p1 = di.p0 + di.w;
  58133. di.s0 = di.b;
  58134. di.s1 = di.s0 + di.s;
  58135. }
  58136. }
  58137. }
  58138. function getAxisLetter(ax) {
  58139. return ax._id.charAt(0);
  58140. }
  58141. module.exports = {
  58142. crossTraceCalc: crossTraceCalc,
  58143. setGroupPositions: setGroupPositions
  58144. };
  58145. },{"../../constants/numerical":149,"../../lib":168,"../../plots/cartesian/axes":212,"../../registry":257,"./sieve.js":279,"fast-isnumeric":18}],271:[function(_dereq_,module,exports){
  58146. /**
  58147. * Copyright 2012-2019, Plotly, Inc.
  58148. * All rights reserved.
  58149. *
  58150. * This source code is licensed under the MIT license found in the
  58151. * LICENSE file in the root directory of this source tree.
  58152. */
  58153. 'use strict';
  58154. var Lib = _dereq_('../../lib');
  58155. var Color = _dereq_('../../components/color');
  58156. var Registry = _dereq_('../../registry');
  58157. var handleXYDefaults = _dereq_('../scatter/xy_defaults');
  58158. var handleStyleDefaults = _dereq_('../bar/style_defaults');
  58159. var attributes = _dereq_('./attributes');
  58160. module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
  58161. function coerce(attr, dflt) {
  58162. return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
  58163. }
  58164. var coerceFont = Lib.coerceFont;
  58165. var len = handleXYDefaults(traceIn, traceOut, layout, coerce);
  58166. if(!len) {
  58167. traceOut.visible = false;
  58168. return;
  58169. }
  58170. coerce('orientation', (traceOut.x && !traceOut.y) ? 'h' : 'v');
  58171. coerce('base');
  58172. coerce('offset');
  58173. coerce('width');
  58174. coerce('text');
  58175. coerce('hovertext');
  58176. coerce('hovertemplate');
  58177. var textPosition = coerce('textposition');
  58178. var hasBoth = Array.isArray(textPosition) || textPosition === 'auto';
  58179. var hasInside = hasBoth || textPosition === 'inside';
  58180. var hasOutside = hasBoth || textPosition === 'outside';
  58181. if(hasInside || hasOutside) {
  58182. var textFont = coerceFont(coerce, 'textfont', layout.font);
  58183. // Note that coercing `insidetextfont` is always needed –
  58184. // even if `textposition` is `outside` for each trace – since
  58185. // an outside label can become an inside one, for example because
  58186. // of a bar being stacked on top of it.
  58187. var insideTextFontDefault = Lib.extendFlat({}, textFont);
  58188. var isTraceTextfontColorSet = traceIn.textfont && traceIn.textfont.color;
  58189. var isColorInheritedFromLayoutFont = !isTraceTextfontColorSet;
  58190. if(isColorInheritedFromLayoutFont) {
  58191. delete insideTextFontDefault.color;
  58192. }
  58193. coerceFont(coerce, 'insidetextfont', insideTextFontDefault);
  58194. if(hasOutside) coerceFont(coerce, 'outsidetextfont', textFont);
  58195. coerce('constraintext');
  58196. coerce('selected.textfont.color');
  58197. coerce('unselected.textfont.color');
  58198. coerce('cliponaxis');
  58199. }
  58200. handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout);
  58201. var lineColor = (traceOut.marker.line || {}).color;
  58202. // override defaultColor for error bars with defaultLine
  58203. var errorBarsSupplyDefaults = Registry.getComponentMethod('errorbars', 'supplyDefaults');
  58204. errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color.defaultLine, {axis: 'y'});
  58205. errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color.defaultLine, {axis: 'x', inherit: 'y'});
  58206. Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
  58207. };
  58208. },{"../../components/color":51,"../../lib":168,"../../registry":257,"../bar/style_defaults":281,"../scatter/xy_defaults":393,"./attributes":267}],272:[function(_dereq_,module,exports){
  58209. /**
  58210. * Copyright 2012-2019, Plotly, Inc.
  58211. * All rights reserved.
  58212. *
  58213. * This source code is licensed under the MIT license found in the
  58214. * LICENSE file in the root directory of this source tree.
  58215. */
  58216. 'use strict';
  58217. var isNumeric = _dereq_('fast-isnumeric');
  58218. var tinycolor = _dereq_('tinycolor2');
  58219. exports.coerceString = function(attributeDefinition, value, defaultValue) {
  58220. if(typeof value === 'string') {
  58221. if(value || !attributeDefinition.noBlank) return value;
  58222. } else if(typeof value === 'number') {
  58223. if(!attributeDefinition.strict) return String(value);
  58224. }
  58225. return (defaultValue !== undefined) ?
  58226. defaultValue :
  58227. attributeDefinition.dflt;
  58228. };
  58229. exports.coerceNumber = function(attributeDefinition, value, defaultValue) {
  58230. if(isNumeric(value)) {
  58231. value = +value;
  58232. var min = attributeDefinition.min;
  58233. var max = attributeDefinition.max;
  58234. var isOutOfBounds = (min !== undefined && value < min) ||
  58235. (max !== undefined && value > max);
  58236. if(!isOutOfBounds) return value;
  58237. }
  58238. return (defaultValue !== undefined) ?
  58239. defaultValue :
  58240. attributeDefinition.dflt;
  58241. };
  58242. exports.coerceColor = function(attributeDefinition, value, defaultValue) {
  58243. if(tinycolor(value).isValid()) return value;
  58244. return (defaultValue !== undefined) ?
  58245. defaultValue :
  58246. attributeDefinition.dflt;
  58247. };
  58248. exports.coerceEnumerated = function(attributeDefinition, value, defaultValue) {
  58249. if(attributeDefinition.coerceNumber) value = +value;
  58250. if(attributeDefinition.values.indexOf(value) !== -1) return value;
  58251. return (defaultValue !== undefined) ?
  58252. defaultValue :
  58253. attributeDefinition.dflt;
  58254. };
  58255. exports.getValue = function(arrayOrScalar, index) {
  58256. var value;
  58257. if(!Array.isArray(arrayOrScalar)) value = arrayOrScalar;
  58258. else if(index < arrayOrScalar.length) value = arrayOrScalar[index];
  58259. return value;
  58260. };
  58261. },{"fast-isnumeric":18,"tinycolor2":34}],273:[function(_dereq_,module,exports){
  58262. /**
  58263. * Copyright 2012-2019, Plotly, Inc.
  58264. * All rights reserved.
  58265. *
  58266. * This source code is licensed under the MIT license found in the
  58267. * LICENSE file in the root directory of this source tree.
  58268. */
  58269. 'use strict';
  58270. var Fx = _dereq_('../../components/fx');
  58271. var Registry = _dereq_('../../registry');
  58272. var Color = _dereq_('../../components/color');
  58273. var fillHoverText = _dereq_('../scatter/fill_hover_text');
  58274. function hoverPoints(pointData, xval, yval, hovermode) {
  58275. var cd = pointData.cd;
  58276. var trace = cd[0].trace;
  58277. var t = cd[0].t;
  58278. var isClosest = (hovermode === 'closest');
  58279. var maxHoverDistance = pointData.maxHoverDistance;
  58280. var maxSpikeDistance = pointData.maxSpikeDistance;
  58281. var posVal, sizeVal, posLetter, sizeLetter, dx, dy, pRangeCalc;
  58282. function thisBarMinPos(di) { return di[posLetter] - di.w / 2; }
  58283. function thisBarMaxPos(di) { return di[posLetter] + di.w / 2; }
  58284. var minPos = isClosest ?
  58285. thisBarMinPos :
  58286. function(di) {
  58287. /*
  58288. * In compare mode, accept a bar if you're on it *or* its group.
  58289. * Nearly always it's the group that matters, but in case the bar
  58290. * was explicitly set wider than its group we'd better accept the
  58291. * whole bar.
  58292. *
  58293. * use `bardelta` instead of `bargroupwidth` so we accept hover
  58294. * in the gap. That way hover doesn't flash on and off as you
  58295. * mouse over the plot in compare modes.
  58296. * In 'closest' mode though the flashing seems inevitable,
  58297. * without far more complex logic
  58298. */
  58299. return Math.min(thisBarMinPos(di), di.p - t.bardelta / 2);
  58300. };
  58301. var maxPos = isClosest ?
  58302. thisBarMaxPos :
  58303. function(di) {
  58304. return Math.max(thisBarMaxPos(di), di.p + t.bardelta / 2);
  58305. };
  58306. function _positionFn(_minPos, _maxPos) {
  58307. // add a little to the pseudo-distance for wider bars, so that like scatter,
  58308. // if you are over two overlapping bars, the narrower one wins.
  58309. return Fx.inbox(_minPos - posVal, _maxPos - posVal,
  58310. maxHoverDistance + Math.min(1, Math.abs(_maxPos - _minPos) / pRangeCalc) - 1);
  58311. }
  58312. function positionFn(di) {
  58313. return _positionFn(minPos(di), maxPos(di));
  58314. }
  58315. function thisBarPositionFn(di) {
  58316. return _positionFn(thisBarMinPos(di), thisBarMaxPos(di));
  58317. }
  58318. function sizeFn(di) {
  58319. // add a gradient so hovering near the end of a
  58320. // bar makes it a little closer match
  58321. return Fx.inbox(di.b - sizeVal, di[sizeLetter] - sizeVal,
  58322. maxHoverDistance + (di[sizeLetter] - sizeVal) / (di[sizeLetter] - di.b) - 1);
  58323. }
  58324. if(trace.orientation === 'h') {
  58325. posVal = yval;
  58326. sizeVal = xval;
  58327. posLetter = 'y';
  58328. sizeLetter = 'x';
  58329. dx = sizeFn;
  58330. dy = positionFn;
  58331. }
  58332. else {
  58333. posVal = xval;
  58334. sizeVal = yval;
  58335. posLetter = 'x';
  58336. sizeLetter = 'y';
  58337. dy = sizeFn;
  58338. dx = positionFn;
  58339. }
  58340. var pa = pointData[posLetter + 'a'];
  58341. var sa = pointData[sizeLetter + 'a'];
  58342. pRangeCalc = Math.abs(pa.r2c(pa.range[1]) - pa.r2c(pa.range[0]));
  58343. function dxy(di) { return (dx(di) + dy(di)) / 2; }
  58344. var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);
  58345. Fx.getClosest(cd, distfn, pointData);
  58346. // skip the rest (for this trace) if we didn't find a close point
  58347. if(pointData.index === false) return;
  58348. // if we get here and we're not in 'closest' mode, push min/max pos back
  58349. // onto the group - even though that means occasionally the mouse will be
  58350. // over the hover label.
  58351. if(!isClosest) {
  58352. minPos = function(di) {
  58353. return Math.min(thisBarMinPos(di), di.p - t.bargroupwidth / 2);
  58354. };
  58355. maxPos = function(di) {
  58356. return Math.max(thisBarMaxPos(di), di.p + t.bargroupwidth / 2);
  58357. };
  58358. }
  58359. // the closest data point
  58360. var index = pointData.index;
  58361. var di = cd[index];
  58362. var size = (trace.base) ? di.b + di.s : di.s;
  58363. pointData[sizeLetter + '0'] = pointData[sizeLetter + '1'] = sa.c2p(di[sizeLetter], true);
  58364. pointData[sizeLetter + 'LabelVal'] = size;
  58365. var extent = t.extents[t.extents.round(di.p)];
  58366. pointData[posLetter + '0'] = pa.c2p(isClosest ? minPos(di) : extent[0], true);
  58367. pointData[posLetter + '1'] = pa.c2p(isClosest ? maxPos(di) : extent[1], true);
  58368. pointData[posLetter + 'LabelVal'] = di.p;
  58369. // spikelines always want "closest" distance regardless of hovermode
  58370. pointData.spikeDistance = (sizeFn(di) + thisBarPositionFn(di)) / 2 + maxSpikeDistance - maxHoverDistance;
  58371. // they also want to point to the data value, regardless of where the label goes
  58372. // in case of bars shifted within groups
  58373. pointData[posLetter + 'Spike'] = pa.c2p(di.p, true);
  58374. pointData.color = getTraceColor(trace, di);
  58375. fillHoverText(di, trace, pointData);
  58376. Registry.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData);
  58377. pointData.hovertemplate = trace.hovertemplate;
  58378. return [pointData];
  58379. }
  58380. function getTraceColor(trace, di) {
  58381. var mc = di.mcc || trace.marker.color;
  58382. var mlc = di.mlcc || trace.marker.line.color;
  58383. var mlw = di.mlw || trace.marker.line.width;
  58384. if(Color.opacity(mc)) return mc;
  58385. else if(Color.opacity(mlc) && mlw) return mlc;
  58386. }
  58387. module.exports = {
  58388. hoverPoints: hoverPoints,
  58389. getTraceColor: getTraceColor
  58390. };
  58391. },{"../../components/color":51,"../../components/fx":90,"../../registry":257,"../scatter/fill_hover_text":375}],274:[function(_dereq_,module,exports){
  58392. /**
  58393. * Copyright 2012-2019, Plotly, Inc.
  58394. * All rights reserved.
  58395. *
  58396. * This source code is licensed under the MIT license found in the
  58397. * LICENSE file in the root directory of this source tree.
  58398. */
  58399. 'use strict';
  58400. var Bar = {};
  58401. Bar.attributes = _dereq_('./attributes');
  58402. Bar.layoutAttributes = _dereq_('./layout_attributes');
  58403. Bar.supplyDefaults = _dereq_('./defaults');
  58404. Bar.supplyLayoutDefaults = _dereq_('./layout_defaults');
  58405. Bar.calc = _dereq_('./calc');
  58406. Bar.crossTraceCalc = _dereq_('./cross_trace_calc').crossTraceCalc;
  58407. Bar.colorbar = _dereq_('../scatter/marker_colorbar');
  58408. Bar.arraysToCalcdata = _dereq_('./arrays_to_calcdata');
  58409. Bar.plot = _dereq_('./plot');
  58410. Bar.style = _dereq_('./style').style;
  58411. Bar.styleOnSelect = _dereq_('./style').styleOnSelect;
  58412. Bar.hoverPoints = _dereq_('./hover').hoverPoints;
  58413. Bar.selectPoints = _dereq_('./select');
  58414. Bar.moduleType = 'trace';
  58415. Bar.name = 'bar';
  58416. Bar.basePlotModule = _dereq_('../../plots/cartesian');
  58417. Bar.categories = ['cartesian', 'svg', 'bar', 'oriented', 'errorBarsOK', 'showLegend', 'zoomScale'];
  58418. Bar.meta = {
  58419. };
  58420. module.exports = Bar;
  58421. },{"../../plots/cartesian":224,"../scatter/marker_colorbar":385,"./arrays_to_calcdata":266,"./attributes":267,"./calc":268,"./cross_trace_calc":270,"./defaults":271,"./hover":273,"./layout_attributes":275,"./layout_defaults":276,"./plot":277,"./select":278,"./style":280}],275:[function(_dereq_,module,exports){
  58422. /**
  58423. * Copyright 2012-2019, Plotly, Inc.
  58424. * All rights reserved.
  58425. *
  58426. * This source code is licensed under the MIT license found in the
  58427. * LICENSE file in the root directory of this source tree.
  58428. */
  58429. 'use strict';
  58430. module.exports = {
  58431. barmode: {
  58432. valType: 'enumerated',
  58433. values: ['stack', 'group', 'overlay', 'relative'],
  58434. dflt: 'group',
  58435. editType: 'calc',
  58436. },
  58437. barnorm: {
  58438. valType: 'enumerated',
  58439. values: ['', 'fraction', 'percent'],
  58440. dflt: '',
  58441. editType: 'calc',
  58442. },
  58443. bargap: {
  58444. valType: 'number',
  58445. min: 0,
  58446. max: 1,
  58447. editType: 'calc',
  58448. },
  58449. bargroupgap: {
  58450. valType: 'number',
  58451. min: 0,
  58452. max: 1,
  58453. dflt: 0,
  58454. editType: 'calc',
  58455. }
  58456. };
  58457. },{}],276:[function(_dereq_,module,exports){
  58458. /**
  58459. * Copyright 2012-2019, Plotly, Inc.
  58460. * All rights reserved.
  58461. *
  58462. * This source code is licensed under the MIT license found in the
  58463. * LICENSE file in the root directory of this source tree.
  58464. */
  58465. 'use strict';
  58466. var Registry = _dereq_('../../registry');
  58467. var Axes = _dereq_('../../plots/cartesian/axes');
  58468. var Lib = _dereq_('../../lib');
  58469. var layoutAttributes = _dereq_('./layout_attributes');
  58470. module.exports = function(layoutIn, layoutOut, fullData) {
  58471. function coerce(attr, dflt) {
  58472. return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
  58473. }
  58474. var hasBars = false;
  58475. var shouldBeGapless = false;
  58476. var gappedAnyway = false;
  58477. var usedSubplots = {};
  58478. for(var i = 0; i < fullData.length; i++) {
  58479. var trace = fullData[i];
  58480. if(Registry.traceIs(trace, 'bar') && trace.visible) hasBars = true;
  58481. else continue;
  58482. // if we have at least 2 grouped bar traces on the same subplot,
  58483. // we should default to a gap anyway, even if the data is histograms
  58484. if(layoutIn.barmode !== 'overlay' && layoutIn.barmode !== 'stack') {
  58485. var subploti = trace.xaxis + trace.yaxis;
  58486. if(usedSubplots[subploti]) gappedAnyway = true;
  58487. usedSubplots[subploti] = true;
  58488. }
  58489. if(trace.visible && trace.type === 'histogram') {
  58490. var pa = Axes.getFromId({_fullLayout: layoutOut},
  58491. trace[trace.orientation === 'v' ? 'xaxis' : 'yaxis']);
  58492. if(pa.type !== 'category') shouldBeGapless = true;
  58493. }
  58494. }
  58495. if(!hasBars) return;
  58496. var mode = coerce('barmode');
  58497. if(mode !== 'overlay') coerce('barnorm');
  58498. coerce('bargap', (shouldBeGapless && !gappedAnyway) ? 0 : 0.2);
  58499. coerce('bargroupgap');
  58500. };
  58501. },{"../../lib":168,"../../plots/cartesian/axes":212,"../../registry":257,"./layout_attributes":275}],277:[function(_dereq_,module,exports){
  58502. /**
  58503. * Copyright 2012-2019, Plotly, Inc.
  58504. * All rights reserved.
  58505. *
  58506. * This source code is licensed under the MIT license found in the
  58507. * LICENSE file in the root directory of this source tree.
  58508. */
  58509. 'use strict';
  58510. var d3 = _dereq_('d3');
  58511. var isNumeric = _dereq_('fast-isnumeric');
  58512. var Lib = _dereq_('../../lib');
  58513. var svgTextUtils = _dereq_('../../lib/svg_text_utils');
  58514. var Color = _dereq_('../../components/color');
  58515. var Drawing = _dereq_('../../components/drawing');
  58516. var Registry = _dereq_('../../registry');
  58517. var attributes = _dereq_('./attributes');
  58518. var attributeText = attributes.text;
  58519. var attributeTextPosition = attributes.textposition;
  58520. var helpers = _dereq_('./helpers');
  58521. var style = _dereq_('./style');
  58522. // padding in pixels around text
  58523. var TEXTPAD = 3;
  58524. module.exports = function plot(gd, plotinfo, cdbar, barLayer) {
  58525. var xa = plotinfo.xaxis;
  58526. var ya = plotinfo.yaxis;
  58527. var fullLayout = gd._fullLayout;
  58528. var bartraces = Lib.makeTraceGroups(barLayer, cdbar, 'trace bars').each(function(cd) {
  58529. var plotGroup = d3.select(this);
  58530. var cd0 = cd[0];
  58531. var trace = cd0.trace;
  58532. if(!plotinfo.isRangePlot) cd0.node3 = plotGroup;
  58533. var pointGroup = Lib.ensureSingle(plotGroup, 'g', 'points');
  58534. var bars = pointGroup.selectAll('g.point').data(Lib.identity);
  58535. bars.enter().append('g')
  58536. .classed('point', true);
  58537. bars.exit().remove();
  58538. bars.each(function(di, i) {
  58539. var bar = d3.select(this);
  58540. // now display the bar
  58541. // clipped xf/yf (2nd arg true): non-positive
  58542. // log values go off-screen by plotwidth
  58543. // so you see them continue if you drag the plot
  58544. var x0, x1, y0, y1;
  58545. if(trace.orientation === 'h') {
  58546. y0 = ya.c2p(di.p0, true);
  58547. y1 = ya.c2p(di.p1, true);
  58548. x0 = xa.c2p(di.s0, true);
  58549. x1 = xa.c2p(di.s1, true);
  58550. // for selections
  58551. di.ct = [x1, (y0 + y1) / 2];
  58552. }
  58553. else {
  58554. x0 = xa.c2p(di.p0, true);
  58555. x1 = xa.c2p(di.p1, true);
  58556. y0 = ya.c2p(di.s0, true);
  58557. y1 = ya.c2p(di.s1, true);
  58558. // for selections
  58559. di.ct = [(x0 + x1) / 2, y1];
  58560. }
  58561. if(!isNumeric(x0) || !isNumeric(x1) ||
  58562. !isNumeric(y0) || !isNumeric(y1) ||
  58563. x0 === x1 || y0 === y1) {
  58564. bar.remove();
  58565. return;
  58566. }
  58567. var lw = (di.mlw + 1 || trace.marker.line.width + 1 ||
  58568. (di.trace ? di.trace.marker.line.width : 0) + 1) - 1;
  58569. var offset = d3.round((lw / 2) % 1, 2);
  58570. function roundWithLine(v) {
  58571. // if there are explicit gaps, don't round,
  58572. // it can make the gaps look crappy
  58573. return (fullLayout.bargap === 0 && fullLayout.bargroupgap === 0) ?
  58574. d3.round(Math.round(v) - offset, 2) : v;
  58575. }
  58576. function expandToVisible(v, vc) {
  58577. // if it's not in danger of disappearing entirely,
  58578. // round more precisely
  58579. return Math.abs(v - vc) >= 2 ? roundWithLine(v) :
  58580. // but if it's very thin, expand it so it's
  58581. // necessarily visible, even if it might overlap
  58582. // its neighbor
  58583. (v > vc ? Math.ceil(v) : Math.floor(v));
  58584. }
  58585. if(!gd._context.staticPlot) {
  58586. // if bars are not fully opaque or they have a line
  58587. // around them, round to integer pixels, mainly for
  58588. // safari so we prevent overlaps from its expansive
  58589. // pixelation. if the bars ARE fully opaque and have
  58590. // no line, expand to a full pixel to make sure we
  58591. // can see them
  58592. var op = Color.opacity(di.mc || trace.marker.color);
  58593. var fixpx = (op < 1 || lw > 0.01) ? roundWithLine : expandToVisible;
  58594. x0 = fixpx(x0, x1);
  58595. x1 = fixpx(x1, x0);
  58596. y0 = fixpx(y0, y1);
  58597. y1 = fixpx(y1, y0);
  58598. }
  58599. Lib.ensureSingle(bar, 'path')
  58600. .style('vector-effect', 'non-scaling-stroke')
  58601. .attr('d',
  58602. 'M' + x0 + ',' + y0 + 'V' + y1 + 'H' + x1 + 'V' + y0 + 'Z')
  58603. .call(Drawing.setClipUrl, plotinfo.layerClipId, gd);
  58604. appendBarText(gd, bar, cd, i, x0, x1, y0, y1);
  58605. if(plotinfo.layerClipId) {
  58606. Drawing.hideOutsideRangePoint(di, bar.select('text'), xa, ya, trace.xcalendar, trace.ycalendar);
  58607. }
  58608. });
  58609. // lastly, clip points groups of `cliponaxis !== false` traces
  58610. // on `plotinfo._hasClipOnAxisFalse === true` subplots
  58611. var hasClipOnAxisFalse = cd0.trace.cliponaxis === false;
  58612. Drawing.setClipUrl(plotGroup, hasClipOnAxisFalse ? null : plotinfo.layerClipId, gd);
  58613. });
  58614. // error bars are on the top
  58615. Registry.getComponentMethod('errorbars', 'plot')(gd, bartraces, plotinfo);
  58616. };
  58617. function appendBarText(gd, bar, calcTrace, i, x0, x1, y0, y1) {
  58618. var textPosition;
  58619. function appendTextNode(bar, text, textFont) {
  58620. var textSelection = Lib.ensureSingle(bar, 'text')
  58621. .text(text)
  58622. .attr({
  58623. 'class': 'bartext bartext-' + textPosition,
  58624. transform: '',
  58625. 'text-anchor': 'middle',
  58626. // prohibit tex interpretation until we can handle
  58627. // tex and regular text together
  58628. 'data-notex': 1
  58629. })
  58630. .call(Drawing.font, textFont)
  58631. .call(svgTextUtils.convertToTspans, gd);
  58632. return textSelection;
  58633. }
  58634. // get trace attributes
  58635. var trace = calcTrace[0].trace;
  58636. var orientation = trace.orientation;
  58637. var text = getText(trace, i);
  58638. textPosition = getTextPosition(trace, i);
  58639. if(!text || textPosition === 'none') {
  58640. bar.select('text').remove();
  58641. return;
  58642. }
  58643. var layoutFont = gd._fullLayout.font;
  58644. var barColor = style.getBarColor(calcTrace[i], trace);
  58645. var insideTextFont = style.getInsideTextFont(trace, i, layoutFont, barColor);
  58646. var outsideTextFont = style.getOutsideTextFont(trace, i, layoutFont);
  58647. // compute text position
  58648. var barmode = gd._fullLayout.barmode;
  58649. var inStackMode = (barmode === 'stack');
  58650. var inRelativeMode = (barmode === 'relative');
  58651. var inStackOrRelativeMode = inStackMode || inRelativeMode;
  58652. var calcBar = calcTrace[i];
  58653. var isOutmostBar = !inStackOrRelativeMode || calcBar._outmost;
  58654. var barWidth = Math.abs(x1 - x0) - 2 * TEXTPAD; // padding excluded
  58655. var barHeight = Math.abs(y1 - y0) - 2 * TEXTPAD; // padding excluded
  58656. var textSelection;
  58657. var textBB;
  58658. var textWidth;
  58659. var textHeight;
  58660. if(textPosition === 'outside') {
  58661. if(!isOutmostBar && !calcBar.hasB) textPosition = 'inside';
  58662. }
  58663. if(textPosition === 'auto') {
  58664. if(isOutmostBar) {
  58665. // draw text using insideTextFont and check if it fits inside bar
  58666. textPosition = 'inside';
  58667. textSelection = appendTextNode(bar, text, insideTextFont);
  58668. textBB = Drawing.bBox(textSelection.node()),
  58669. textWidth = textBB.width,
  58670. textHeight = textBB.height;
  58671. var textHasSize = (textWidth > 0 && textHeight > 0);
  58672. var fitsInside = (textWidth <= barWidth && textHeight <= barHeight);
  58673. var fitsInsideIfRotated = (textWidth <= barHeight && textHeight <= barWidth);
  58674. var fitsInsideIfShrunk = (orientation === 'h') ?
  58675. (barWidth >= textWidth * (barHeight / textHeight)) :
  58676. (barHeight >= textHeight * (barWidth / textWidth));
  58677. if(textHasSize &&
  58678. (fitsInside || fitsInsideIfRotated || fitsInsideIfShrunk)) {
  58679. textPosition = 'inside';
  58680. }
  58681. else {
  58682. textPosition = 'outside';
  58683. textSelection.remove();
  58684. textSelection = null;
  58685. }
  58686. }
  58687. else textPosition = 'inside';
  58688. }
  58689. if(!textSelection) {
  58690. textSelection = appendTextNode(bar, text,
  58691. (textPosition === 'outside') ?
  58692. outsideTextFont : insideTextFont);
  58693. textBB = Drawing.bBox(textSelection.node()),
  58694. textWidth = textBB.width,
  58695. textHeight = textBB.height;
  58696. if(textWidth <= 0 || textHeight <= 0) {
  58697. textSelection.remove();
  58698. return;
  58699. }
  58700. }
  58701. // compute text transform
  58702. var transform, constrained;
  58703. if(textPosition === 'outside') {
  58704. constrained = trace.constraintext === 'both' || trace.constraintext === 'outside';
  58705. transform = getTransformToMoveOutsideBar(x0, x1, y0, y1, textBB,
  58706. orientation, constrained);
  58707. }
  58708. else {
  58709. constrained = trace.constraintext === 'both' || trace.constraintext === 'inside';
  58710. transform = getTransformToMoveInsideBar(x0, x1, y0, y1, textBB,
  58711. orientation, constrained);
  58712. }
  58713. textSelection.attr('transform', transform);
  58714. }
  58715. function getTransformToMoveInsideBar(x0, x1, y0, y1, textBB, orientation, constrained) {
  58716. // compute text and target positions
  58717. var textWidth = textBB.width;
  58718. var textHeight = textBB.height;
  58719. var textX = (textBB.left + textBB.right) / 2;
  58720. var textY = (textBB.top + textBB.bottom) / 2;
  58721. var barWidth = Math.abs(x1 - x0);
  58722. var barHeight = Math.abs(y1 - y0);
  58723. var targetWidth;
  58724. var targetHeight;
  58725. var targetX;
  58726. var targetY;
  58727. // apply text padding
  58728. var textpad;
  58729. if(barWidth > (2 * TEXTPAD) && barHeight > (2 * TEXTPAD)) {
  58730. textpad = TEXTPAD;
  58731. barWidth -= 2 * textpad;
  58732. barHeight -= 2 * textpad;
  58733. }
  58734. else textpad = 0;
  58735. // compute rotation and scale
  58736. var rotate,
  58737. scale;
  58738. if(textWidth <= barWidth && textHeight <= barHeight) {
  58739. // no scale or rotation is required
  58740. rotate = false;
  58741. scale = 1;
  58742. }
  58743. else if(textWidth <= barHeight && textHeight <= barWidth) {
  58744. // only rotation is required
  58745. rotate = true;
  58746. scale = 1;
  58747. }
  58748. else if((textWidth < textHeight) === (barWidth < barHeight)) {
  58749. // only scale is required
  58750. rotate = false;
  58751. scale = constrained ? Math.min(barWidth / textWidth, barHeight / textHeight) : 1;
  58752. }
  58753. else {
  58754. // both scale and rotation are required
  58755. rotate = true;
  58756. scale = constrained ? Math.min(barHeight / textWidth, barWidth / textHeight) : 1;
  58757. }
  58758. if(rotate) rotate = 90; // rotate clockwise
  58759. // compute text and target positions
  58760. if(rotate) {
  58761. targetWidth = scale * textHeight;
  58762. targetHeight = scale * textWidth;
  58763. }
  58764. else {
  58765. targetWidth = scale * textWidth;
  58766. targetHeight = scale * textHeight;
  58767. }
  58768. if(orientation === 'h') {
  58769. if(x1 < x0) {
  58770. // bar end is on the left hand side
  58771. targetX = x1 + textpad + targetWidth / 2;
  58772. targetY = (y0 + y1) / 2;
  58773. }
  58774. else {
  58775. targetX = x1 - textpad - targetWidth / 2;
  58776. targetY = (y0 + y1) / 2;
  58777. }
  58778. }
  58779. else {
  58780. if(y1 > y0) {
  58781. // bar end is on the bottom
  58782. targetX = (x0 + x1) / 2;
  58783. targetY = y1 - textpad - targetHeight / 2;
  58784. }
  58785. else {
  58786. targetX = (x0 + x1) / 2;
  58787. targetY = y1 + textpad + targetHeight / 2;
  58788. }
  58789. }
  58790. return getTransform(textX, textY, targetX, targetY, scale, rotate);
  58791. }
  58792. function getTransformToMoveOutsideBar(x0, x1, y0, y1, textBB, orientation, constrained) {
  58793. var barWidth = (orientation === 'h') ?
  58794. Math.abs(y1 - y0) :
  58795. Math.abs(x1 - x0);
  58796. var textpad;
  58797. // Keep the padding so the text doesn't sit right against
  58798. // the bars, but don't factor it into barWidth
  58799. if(barWidth > 2 * TEXTPAD) {
  58800. textpad = TEXTPAD;
  58801. }
  58802. // compute rotation and scale
  58803. var scale = 1;
  58804. if(constrained) {
  58805. scale = (orientation === 'h') ?
  58806. Math.min(1, barWidth / textBB.height) :
  58807. Math.min(1, barWidth / textBB.width);
  58808. }
  58809. // compute text and target positions
  58810. var textX = (textBB.left + textBB.right) / 2;
  58811. var textY = (textBB.top + textBB.bottom) / 2;
  58812. var targetWidth;
  58813. var targetHeight;
  58814. var targetX;
  58815. var targetY;
  58816. targetWidth = scale * textBB.width;
  58817. targetHeight = scale * textBB.height;
  58818. if(orientation === 'h') {
  58819. if(x1 < x0) {
  58820. // bar end is on the left hand side
  58821. targetX = x1 - textpad - targetWidth / 2;
  58822. targetY = (y0 + y1) / 2;
  58823. }
  58824. else {
  58825. targetX = x1 + textpad + targetWidth / 2;
  58826. targetY = (y0 + y1) / 2;
  58827. }
  58828. }
  58829. else {
  58830. if(y1 > y0) {
  58831. // bar end is on the bottom
  58832. targetX = (x0 + x1) / 2;
  58833. targetY = y1 + textpad + targetHeight / 2;
  58834. }
  58835. else {
  58836. targetX = (x0 + x1) / 2;
  58837. targetY = y1 - textpad - targetHeight / 2;
  58838. }
  58839. }
  58840. return getTransform(textX, textY, targetX, targetY, scale, false);
  58841. }
  58842. function getTransform(textX, textY, targetX, targetY, scale, rotate) {
  58843. var transformScale;
  58844. var transformRotate;
  58845. var transformTranslate;
  58846. if(scale < 1) transformScale = 'scale(' + scale + ') ';
  58847. else {
  58848. scale = 1;
  58849. transformScale = '';
  58850. }
  58851. transformRotate = (rotate) ?
  58852. 'rotate(' + rotate + ' ' + textX + ' ' + textY + ') ' : '';
  58853. // Note that scaling also affects the center of the text box
  58854. var translateX = (targetX - scale * textX);
  58855. var translateY = (targetY - scale * textY);
  58856. transformTranslate = 'translate(' + translateX + ' ' + translateY + ')';
  58857. return transformTranslate + transformScale + transformRotate;
  58858. }
  58859. function getText(trace, index) {
  58860. var value = helpers.getValue(trace.text, index);
  58861. return helpers.coerceString(attributeText, value);
  58862. }
  58863. function getTextPosition(trace, index) {
  58864. var value = helpers.getValue(trace.textposition, index);
  58865. return helpers.coerceEnumerated(attributeTextPosition, value);
  58866. }
  58867. },{"../../components/color":51,"../../components/drawing":72,"../../lib":168,"../../lib/svg_text_utils":189,"../../registry":257,"./attributes":267,"./helpers":272,"./style":280,"d3":16,"fast-isnumeric":18}],278:[function(_dereq_,module,exports){
  58868. /**
  58869. * Copyright 2012-2019, Plotly, Inc.
  58870. * All rights reserved.
  58871. *
  58872. * This source code is licensed under the MIT license found in the
  58873. * LICENSE file in the root directory of this source tree.
  58874. */
  58875. 'use strict';
  58876. module.exports = function selectPoints(searchInfo, selectionTester) {
  58877. var cd = searchInfo.cd;
  58878. var xa = searchInfo.xaxis;
  58879. var ya = searchInfo.yaxis;
  58880. var selection = [];
  58881. var i;
  58882. if(selectionTester === false) {
  58883. // clear selection
  58884. for(i = 0; i < cd.length; i++) {
  58885. cd[i].selected = 0;
  58886. }
  58887. } else {
  58888. for(i = 0; i < cd.length; i++) {
  58889. var di = cd[i];
  58890. if(selectionTester.contains(di.ct, false, i, searchInfo)) {
  58891. selection.push({
  58892. pointNumber: i,
  58893. x: xa.c2d(di.x),
  58894. y: ya.c2d(di.y)
  58895. });
  58896. di.selected = 1;
  58897. } else {
  58898. di.selected = 0;
  58899. }
  58900. }
  58901. }
  58902. return selection;
  58903. };
  58904. },{}],279:[function(_dereq_,module,exports){
  58905. /**
  58906. * Copyright 2012-2019, Plotly, Inc.
  58907. * All rights reserved.
  58908. *
  58909. * This source code is licensed under the MIT license found in the
  58910. * LICENSE file in the root directory of this source tree.
  58911. */
  58912. 'use strict';
  58913. module.exports = Sieve;
  58914. var Lib = _dereq_('../../lib');
  58915. var BADNUM = _dereq_('../../constants/numerical').BADNUM;
  58916. /**
  58917. * Helper class to sieve data from traces into bins
  58918. *
  58919. * @class
  58920. * @param {Array} traces
  58921. * Array of calculated traces
  58922. * @param {boolean} [separateNegativeValues]
  58923. * If true, then split data at the same position into a bar
  58924. * for positive values and another for negative values
  58925. * @param {boolean} [dontMergeOverlappingData]
  58926. * If true, then don't merge overlapping bars into a single bar
  58927. */
  58928. function Sieve(traces, separateNegativeValues, dontMergeOverlappingData) {
  58929. this.traces = traces;
  58930. this.separateNegativeValues = separateNegativeValues;
  58931. this.dontMergeOverlappingData = dontMergeOverlappingData;
  58932. // for single-bin histograms - see histogram/calc
  58933. var width1 = Infinity;
  58934. var positions = [];
  58935. for(var i = 0; i < traces.length; i++) {
  58936. var trace = traces[i];
  58937. for(var j = 0; j < trace.length; j++) {
  58938. var bar = trace[j];
  58939. if(bar.p !== BADNUM) positions.push(bar.p);
  58940. }
  58941. if(trace[0] && trace[0].width1) {
  58942. width1 = Math.min(trace[0].width1, width1);
  58943. }
  58944. }
  58945. this.positions = positions;
  58946. var dv = Lib.distinctVals(positions);
  58947. this.distinctPositions = dv.vals;
  58948. if(dv.vals.length === 1 && width1 !== Infinity) this.minDiff = width1;
  58949. else this.minDiff = Math.min(dv.minDiff, width1);
  58950. this.binWidth = this.minDiff;
  58951. this.bins = {};
  58952. }
  58953. /**
  58954. * Sieve datum
  58955. *
  58956. * @method
  58957. * @param {number} position
  58958. * @param {number} value
  58959. * @returns {number} Previous bin value
  58960. */
  58961. Sieve.prototype.put = function put(position, value) {
  58962. var label = this.getLabel(position, value);
  58963. var oldValue = this.bins[label] || 0;
  58964. this.bins[label] = oldValue + value;
  58965. return oldValue;
  58966. };
  58967. /**
  58968. * Get current bin value for a given datum
  58969. *
  58970. * @method
  58971. * @param {number} position Position of datum
  58972. * @param {number} [value] Value of datum
  58973. * (required if this.separateNegativeValues is true)
  58974. * @returns {number} Current bin value
  58975. */
  58976. Sieve.prototype.get = function put(position, value) {
  58977. var label = this.getLabel(position, value);
  58978. return this.bins[label] || 0;
  58979. };
  58980. /**
  58981. * Get bin label for a given datum
  58982. *
  58983. * @method
  58984. * @param {number} position Position of datum
  58985. * @param {number} [value] Value of datum
  58986. * (required if this.separateNegativeValues is true)
  58987. * @returns {string} Bin label
  58988. * (prefixed with a 'v' if value is negative and this.separateNegativeValues is
  58989. * true; otherwise prefixed with '^')
  58990. */
  58991. Sieve.prototype.getLabel = function getLabel(position, value) {
  58992. var prefix = (value < 0 && this.separateNegativeValues) ? 'v' : '^';
  58993. var label = (this.dontMergeOverlappingData) ?
  58994. position :
  58995. Math.round(position / this.binWidth);
  58996. return prefix + label;
  58997. };
  58998. },{"../../constants/numerical":149,"../../lib":168}],280:[function(_dereq_,module,exports){
  58999. /**
  59000. * Copyright 2012-2019, Plotly, Inc.
  59001. * All rights reserved.
  59002. *
  59003. * This source code is licensed under the MIT license found in the
  59004. * LICENSE file in the root directory of this source tree.
  59005. */
  59006. 'use strict';
  59007. var d3 = _dereq_('d3');
  59008. var Color = _dereq_('../../components/color');
  59009. var Drawing = _dereq_('../../components/drawing');
  59010. var Lib = _dereq_('../../lib');
  59011. var Registry = _dereq_('../../registry');
  59012. var attributes = _dereq_('./attributes');
  59013. var attributeTextFont = attributes.textfont;
  59014. var attributeInsideTextFont = attributes.insidetextfont;
  59015. var attributeOutsideTextFont = attributes.outsidetextfont;
  59016. var helpers = _dereq_('./helpers');
  59017. function style(gd, cd) {
  59018. var s = cd ? cd[0].node3 : d3.select(gd).selectAll('g.trace.bars');
  59019. var barcount = s.size();
  59020. var fullLayout = gd._fullLayout;
  59021. // trace styling
  59022. s.style('opacity', function(d) { return d[0].trace.opacity; })
  59023. // for gapless (either stacked or neighboring grouped) bars use
  59024. // crispEdges to turn off antialiasing so an artificial gap
  59025. // isn't introduced.
  59026. .each(function(d) {
  59027. if((fullLayout.barmode === 'stack' && barcount > 1) ||
  59028. (fullLayout.bargap === 0 &&
  59029. fullLayout.bargroupgap === 0 &&
  59030. !d[0].trace.marker.line.width)) {
  59031. d3.select(this).attr('shape-rendering', 'crispEdges');
  59032. }
  59033. });
  59034. s.selectAll('g.points').each(function(d) {
  59035. var sel = d3.select(this);
  59036. var trace = d[0].trace;
  59037. stylePoints(sel, trace, gd);
  59038. });
  59039. Registry.getComponentMethod('errorbars', 'style')(s);
  59040. }
  59041. function stylePoints(sel, trace, gd) {
  59042. var pts = sel.selectAll('path');
  59043. var txs = sel.selectAll('text');
  59044. Drawing.pointStyle(pts, trace, gd);
  59045. txs.each(function(d) {
  59046. var tx = d3.select(this);
  59047. var font = determineFont(tx, d, trace, gd);
  59048. Drawing.font(tx, font);
  59049. });
  59050. }
  59051. function styleOnSelect(gd, cd) {
  59052. var s = cd[0].node3;
  59053. var trace = cd[0].trace;
  59054. if(trace.selectedpoints) {
  59055. stylePointsInSelectionMode(s, trace, gd);
  59056. } else {
  59057. stylePoints(s, trace, gd);
  59058. }
  59059. }
  59060. function stylePointsInSelectionMode(s, trace, gd) {
  59061. Drawing.selectedPointStyle(s.selectAll('path'), trace);
  59062. styleTextInSelectionMode(s.selectAll('text'), trace, gd);
  59063. }
  59064. function styleTextInSelectionMode(txs, trace, gd) {
  59065. txs.each(function(d) {
  59066. var tx = d3.select(this);
  59067. var font;
  59068. if(d.selected) {
  59069. font = Lib.extendFlat({}, determineFont(tx, d, trace, gd));
  59070. var selectedFontColor = trace.selected.textfont && trace.selected.textfont.color;
  59071. if(selectedFontColor) {
  59072. font.color = selectedFontColor;
  59073. }
  59074. Drawing.font(tx, font);
  59075. } else {
  59076. Drawing.selectedTextStyle(tx, trace);
  59077. }
  59078. });
  59079. }
  59080. function determineFont(tx, d, trace, gd) {
  59081. var layoutFont = gd._fullLayout.font;
  59082. var textFont = trace.textfont;
  59083. if(tx.classed('bartext-inside')) {
  59084. var barColor = getBarColor(d, trace);
  59085. textFont = getInsideTextFont(trace, d.i, layoutFont, barColor);
  59086. } else if(tx.classed('bartext-outside')) {
  59087. textFont = getOutsideTextFont(trace, d.i, layoutFont);
  59088. }
  59089. return textFont;
  59090. }
  59091. function getTextFont(trace, index, defaultValue) {
  59092. return getFontValue(
  59093. attributeTextFont, trace.textfont, index, defaultValue);
  59094. }
  59095. function getInsideTextFont(trace, index, layoutFont, barColor) {
  59096. var defaultFont = getTextFont(trace, index, layoutFont);
  59097. var wouldFallBackToLayoutFont =
  59098. (trace._input.textfont === undefined || trace._input.textfont.color === undefined) ||
  59099. (Array.isArray(trace.textfont.color) && trace.textfont.color[index] === undefined);
  59100. if(wouldFallBackToLayoutFont) {
  59101. defaultFont = {
  59102. color: Color.contrast(barColor),
  59103. family: defaultFont.family,
  59104. size: defaultFont.size
  59105. };
  59106. }
  59107. return getFontValue(
  59108. attributeInsideTextFont, trace.insidetextfont, index, defaultFont);
  59109. }
  59110. function getOutsideTextFont(trace, index, layoutFont) {
  59111. var defaultFont = getTextFont(trace, index, layoutFont);
  59112. return getFontValue(
  59113. attributeOutsideTextFont, trace.outsidetextfont, index, defaultFont);
  59114. }
  59115. function getFontValue(attributeDefinition, attributeValue, index, defaultValue) {
  59116. attributeValue = attributeValue || {};
  59117. var familyValue = helpers.getValue(attributeValue.family, index);
  59118. var sizeValue = helpers.getValue(attributeValue.size, index);
  59119. var colorValue = helpers.getValue(attributeValue.color, index);
  59120. return {
  59121. family: helpers.coerceString(
  59122. attributeDefinition.family, familyValue, defaultValue.family),
  59123. size: helpers.coerceNumber(
  59124. attributeDefinition.size, sizeValue, defaultValue.size),
  59125. color: helpers.coerceColor(
  59126. attributeDefinition.color, colorValue, defaultValue.color)
  59127. };
  59128. }
  59129. function getBarColor(cd, trace) {
  59130. return cd.mc || trace.marker.color;
  59131. }
  59132. module.exports = {
  59133. style: style,
  59134. styleOnSelect: styleOnSelect,
  59135. getInsideTextFont: getInsideTextFont,
  59136. getOutsideTextFont: getOutsideTextFont,
  59137. getBarColor: getBarColor
  59138. };
  59139. },{"../../components/color":51,"../../components/drawing":72,"../../lib":168,"../../registry":257,"./attributes":267,"./helpers":272,"d3":16}],281:[function(_dereq_,module,exports){
  59140. /**
  59141. * Copyright 2012-2019, Plotly, Inc.
  59142. * All rights reserved.
  59143. *
  59144. * This source code is licensed under the MIT license found in the
  59145. * LICENSE file in the root directory of this source tree.
  59146. */
  59147. 'use strict';
  59148. var Color = _dereq_('../../components/color');
  59149. var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
  59150. var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
  59151. module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout) {
  59152. coerce('marker.color', defaultColor);
  59153. if(hasColorscale(traceIn, 'marker')) {
  59154. colorscaleDefaults(
  59155. traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'}
  59156. );
  59157. }
  59158. coerce('marker.line.color', Color.defaultLine);
  59159. if(hasColorscale(traceIn, 'marker.line')) {
  59160. colorscaleDefaults(
  59161. traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'}
  59162. );
  59163. }
  59164. coerce('marker.line.width');
  59165. coerce('marker.opacity');
  59166. coerce('selected.marker.color');
  59167. coerce('unselected.marker.color');
  59168. };
  59169. },{"../../components/color":51,"../../components/colorscale/defaults":61,"../../components/colorscale/helpers":62}],282:[function(_dereq_,module,exports){
  59170. /**
  59171. * Copyright 2012-2019, Plotly, Inc.
  59172. * All rights reserved.
  59173. *
  59174. * This source code is licensed under the MIT license found in the
  59175. * LICENSE file in the root directory of this source tree.
  59176. */
  59177. 'use strict';
  59178. var scatterAttrs = _dereq_('../scatter/attributes');
  59179. var colorAttrs = _dereq_('../../components/color/attributes');
  59180. var extendFlat = _dereq_('../../lib/extend').extendFlat;
  59181. var scatterMarkerAttrs = scatterAttrs.marker;
  59182. var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
  59183. module.exports = {
  59184. y: {
  59185. valType: 'data_array',
  59186. editType: 'calc+clearAxisTypes',
  59187. },
  59188. x: {
  59189. valType: 'data_array',
  59190. editType: 'calc+clearAxisTypes',
  59191. },
  59192. x0: {
  59193. valType: 'any',
  59194. editType: 'calc+clearAxisTypes',
  59195. },
  59196. y0: {
  59197. valType: 'any',
  59198. editType: 'calc+clearAxisTypes',
  59199. },
  59200. name: {
  59201. valType: 'string',
  59202. editType: 'calc+clearAxisTypes',
  59203. },
  59204. text: extendFlat({}, scatterAttrs.text, {
  59205. }),
  59206. whiskerwidth: {
  59207. valType: 'number',
  59208. min: 0,
  59209. max: 1,
  59210. dflt: 0.5,
  59211. editType: 'calc',
  59212. },
  59213. notched: {
  59214. valType: 'boolean',
  59215. editType: 'calc',
  59216. },
  59217. notchwidth: {
  59218. valType: 'number',
  59219. min: 0,
  59220. max: 0.5,
  59221. dflt: 0.25,
  59222. editType: 'calc',
  59223. },
  59224. boxpoints: {
  59225. valType: 'enumerated',
  59226. values: ['all', 'outliers', 'suspectedoutliers', false],
  59227. dflt: 'outliers',
  59228. editType: 'calc',
  59229. },
  59230. boxmean: {
  59231. valType: 'enumerated',
  59232. values: [true, 'sd', false],
  59233. dflt: false,
  59234. editType: 'calc',
  59235. },
  59236. jitter: {
  59237. valType: 'number',
  59238. min: 0,
  59239. max: 1,
  59240. editType: 'calc',
  59241. },
  59242. pointpos: {
  59243. valType: 'number',
  59244. min: -2,
  59245. max: 2,
  59246. editType: 'calc',
  59247. },
  59248. orientation: {
  59249. valType: 'enumerated',
  59250. values: ['v', 'h'],
  59251. editType: 'calc+clearAxisTypes',
  59252. },
  59253. width: {
  59254. valType: 'number',
  59255. min: 0,
  59256. dflt: 0,
  59257. editType: 'calc',
  59258. },
  59259. marker: {
  59260. outliercolor: {
  59261. valType: 'color',
  59262. dflt: 'rgba(0, 0, 0, 0)',
  59263. editType: 'style',
  59264. },
  59265. symbol: extendFlat({}, scatterMarkerAttrs.symbol,
  59266. {arrayOk: false, editType: 'plot'}),
  59267. opacity: extendFlat({}, scatterMarkerAttrs.opacity,
  59268. {arrayOk: false, dflt: 1, editType: 'style'}),
  59269. size: extendFlat({}, scatterMarkerAttrs.size,
  59270. {arrayOk: false, editType: 'calc'}),
  59271. color: extendFlat({}, scatterMarkerAttrs.color,
  59272. {arrayOk: false, editType: 'style'}),
  59273. line: {
  59274. color: extendFlat({}, scatterMarkerLineAttrs.color,
  59275. {arrayOk: false, dflt: colorAttrs.defaultLine, editType: 'style'}
  59276. ),
  59277. width: extendFlat({}, scatterMarkerLineAttrs.width,
  59278. {arrayOk: false, dflt: 0, editType: 'style'}
  59279. ),
  59280. outliercolor: {
  59281. valType: 'color',
  59282. editType: 'style',
  59283. },
  59284. outlierwidth: {
  59285. valType: 'number',
  59286. min: 0,
  59287. dflt: 1,
  59288. editType: 'style',
  59289. },
  59290. editType: 'style'
  59291. },
  59292. editType: 'plot'
  59293. },
  59294. line: {
  59295. color: {
  59296. valType: 'color',
  59297. editType: 'style',
  59298. },
  59299. width: {
  59300. valType: 'number',
  59301. min: 0,
  59302. dflt: 2,
  59303. editType: 'style',
  59304. },
  59305. editType: 'plot'
  59306. },
  59307. fillcolor: scatterAttrs.fillcolor,
  59308. selected: {
  59309. marker: scatterAttrs.selected.marker,
  59310. editType: 'style'
  59311. },
  59312. unselected: {
  59313. marker: scatterAttrs.unselected.marker,
  59314. editType: 'style'
  59315. },
  59316. hoveron: {
  59317. valType: 'flaglist',
  59318. flags: ['boxes', 'points'],
  59319. dflt: 'boxes+points',
  59320. editType: 'style',
  59321. }
  59322. };
  59323. },{"../../components/color/attributes":50,"../../lib/extend":162,"../scatter/attributes":367}],283:[function(_dereq_,module,exports){
  59324. /**
  59325. * Copyright 2012-2019, Plotly, Inc.
  59326. * All rights reserved.
  59327. *
  59328. * This source code is licensed under the MIT license found in the
  59329. * LICENSE file in the root directory of this source tree.
  59330. */
  59331. 'use strict';
  59332. var isNumeric = _dereq_('fast-isnumeric');
  59333. var Lib = _dereq_('../../lib');
  59334. var _ = Lib._;
  59335. var Axes = _dereq_('../../plots/cartesian/axes');
  59336. // outlier definition based on http://www.physics.csbsju.edu/stats/box2.html
  59337. module.exports = function calc(gd, trace) {
  59338. var fullLayout = gd._fullLayout;
  59339. var xa = Axes.getFromId(gd, trace.xaxis || 'x');
  59340. var ya = Axes.getFromId(gd, trace.yaxis || 'y');
  59341. var cd = [];
  59342. // N.B. violin reuses same Box.calc
  59343. var numKey = trace.type === 'violin' ? '_numViolins' : '_numBoxes';
  59344. var i;
  59345. var valAxis, valLetter;
  59346. var posAxis, posLetter;
  59347. if(trace.orientation === 'h') {
  59348. valAxis = xa;
  59349. valLetter = 'x';
  59350. posAxis = ya;
  59351. posLetter = 'y';
  59352. } else {
  59353. valAxis = ya;
  59354. valLetter = 'y';
  59355. posAxis = xa;
  59356. posLetter = 'x';
  59357. }
  59358. var val = valAxis.makeCalcdata(trace, valLetter);
  59359. var pos = getPos(trace, posLetter, posAxis, val, fullLayout[numKey]);
  59360. var dv = Lib.distinctVals(pos);
  59361. var posDistinct = dv.vals;
  59362. var dPos = dv.minDiff / 2;
  59363. var posBins = makeBins(posDistinct, dPos);
  59364. var pLen = posDistinct.length;
  59365. var ptsPerBin = initNestedArray(pLen);
  59366. // bin pts info per position bins
  59367. for(i = 0; i < trace._length; i++) {
  59368. var v = val[i];
  59369. if(!isNumeric(v)) continue;
  59370. var n = Lib.findBin(pos[i], posBins);
  59371. if(n >= 0 && n < pLen) {
  59372. var pt = {v: v, i: i};
  59373. arraysToCalcdata(pt, trace, i);
  59374. ptsPerBin[n].push(pt);
  59375. }
  59376. }
  59377. var cdi;
  59378. var ptFilterFn = (trace.boxpoints || trace.points) === 'all' ?
  59379. Lib.identity :
  59380. function(pt) { return (pt.v < cdi.lf || pt.v > cdi.uf); };
  59381. // build calcdata trace items, one item per distinct position
  59382. for(i = 0; i < pLen; i++) {
  59383. if(ptsPerBin[i].length > 0) {
  59384. var pts = ptsPerBin[i].sort(sortByVal);
  59385. var boxVals = pts.map(extractVal);
  59386. var bvLen = boxVals.length;
  59387. cdi = {};
  59388. cdi.pos = posDistinct[i];
  59389. cdi.pts = pts;
  59390. cdi.min = boxVals[0];
  59391. cdi.max = boxVals[bvLen - 1];
  59392. cdi.mean = Lib.mean(boxVals, bvLen);
  59393. cdi.sd = Lib.stdev(boxVals, bvLen, cdi.mean);
  59394. // first quartile
  59395. cdi.q1 = Lib.interp(boxVals, 0.25);
  59396. // median
  59397. cdi.med = Lib.interp(boxVals, 0.5);
  59398. // third quartile
  59399. cdi.q3 = Lib.interp(boxVals, 0.75);
  59400. // lower and upper fences - last point inside
  59401. // 1.5 interquartile ranges from quartiles
  59402. cdi.lf = Math.min(
  59403. cdi.q1,
  59404. boxVals[Math.min(
  59405. Lib.findBin(2.5 * cdi.q1 - 1.5 * cdi.q3, boxVals, true) + 1,
  59406. bvLen - 1
  59407. )]
  59408. );
  59409. cdi.uf = Math.max(
  59410. cdi.q3,
  59411. boxVals[Math.max(
  59412. Lib.findBin(2.5 * cdi.q3 - 1.5 * cdi.q1, boxVals),
  59413. 0
  59414. )]
  59415. );
  59416. // lower and upper outliers - 3 IQR out (don't clip to max/min,
  59417. // this is only for discriminating suspected & far outliers)
  59418. cdi.lo = 4 * cdi.q1 - 3 * cdi.q3;
  59419. cdi.uo = 4 * cdi.q3 - 3 * cdi.q1;
  59420. // lower and upper notches ~95% Confidence Intervals for median
  59421. var iqr = cdi.q3 - cdi.q1;
  59422. var mci = 1.57 * iqr / Math.sqrt(bvLen);
  59423. cdi.ln = cdi.med - mci;
  59424. cdi.un = cdi.med + mci;
  59425. cdi.pts2 = pts.filter(ptFilterFn);
  59426. cd.push(cdi);
  59427. }
  59428. }
  59429. calcSelection(cd, trace);
  59430. var extremes = Axes.findExtremes(valAxis, val, {padded: true});
  59431. trace._extremes[valAxis._id] = extremes;
  59432. if(cd.length > 0) {
  59433. cd[0].t = {
  59434. num: fullLayout[numKey],
  59435. dPos: dPos,
  59436. posLetter: posLetter,
  59437. valLetter: valLetter,
  59438. labels: {
  59439. med: _(gd, 'median:'),
  59440. min: _(gd, 'min:'),
  59441. q1: _(gd, 'q1:'),
  59442. q3: _(gd, 'q3:'),
  59443. max: _(gd, 'max:'),
  59444. mean: trace.boxmean === 'sd' ? _(gd, 'mean ± σ:') : _(gd, 'mean:'),
  59445. lf: _(gd, 'lower fence:'),
  59446. uf: _(gd, 'upper fence:')
  59447. }
  59448. };
  59449. fullLayout[numKey]++;
  59450. return cd;
  59451. } else {
  59452. return [{t: {empty: true}}];
  59453. }
  59454. };
  59455. // In vertical (horizontal) box plots:
  59456. // if no x (y) data, use x0 (y0), or name
  59457. // so if you want one box
  59458. // per trace, set x0 (y0) to the x (y) value or category for this trace
  59459. // (or set x (y) to a constant array matching y (x))
  59460. function getPos(trace, posLetter, posAxis, val, num) {
  59461. if(posLetter in trace) {
  59462. return posAxis.makeCalcdata(trace, posLetter);
  59463. }
  59464. var pos0;
  59465. if(posLetter + '0' in trace) {
  59466. pos0 = trace[posLetter + '0'];
  59467. } else if('name' in trace && (
  59468. posAxis.type === 'category' || (
  59469. isNumeric(trace.name) &&
  59470. ['linear', 'log'].indexOf(posAxis.type) !== -1
  59471. ) || (
  59472. Lib.isDateTime(trace.name) &&
  59473. posAxis.type === 'date'
  59474. )
  59475. )) {
  59476. pos0 = trace.name;
  59477. } else {
  59478. pos0 = num;
  59479. }
  59480. var pos0c = posAxis.type === 'multicategory' ?
  59481. posAxis.r2c_just_indices(pos0) :
  59482. posAxis.d2c(pos0, 0, trace[posLetter + 'calendar']);
  59483. return val.map(function() { return pos0c; });
  59484. }
  59485. function makeBins(x, dx) {
  59486. var len = x.length;
  59487. var bins = new Array(len + 1);
  59488. for(var i = 0; i < len; i++) {
  59489. bins[i] = x[i] - dx;
  59490. }
  59491. bins[len] = x[len - 1] + dx;
  59492. return bins;
  59493. }
  59494. function initNestedArray(len) {
  59495. var arr = new Array(len);
  59496. for(var i = 0; i < len; i++) {
  59497. arr[i] = [];
  59498. }
  59499. return arr;
  59500. }
  59501. function arraysToCalcdata(pt, trace, i) {
  59502. var trace2calc = {
  59503. text: 'tx'
  59504. };
  59505. for(var k in trace2calc) {
  59506. if(Array.isArray(trace[k])) {
  59507. pt[trace2calc[k]] = trace[k][i];
  59508. }
  59509. }
  59510. }
  59511. function calcSelection(cd, trace) {
  59512. if(Lib.isArrayOrTypedArray(trace.selectedpoints)) {
  59513. for(var i = 0; i < cd.length; i++) {
  59514. var pts = cd[i].pts || [];
  59515. var ptNumber2cdIndex = {};
  59516. for(var j = 0; j < pts.length; j++) {
  59517. ptNumber2cdIndex[pts[j].i] = j;
  59518. }
  59519. Lib.tagSelected(pts, trace, ptNumber2cdIndex);
  59520. }
  59521. }
  59522. }
  59523. function sortByVal(a, b) { return a.v - b.v; }
  59524. function extractVal(o) { return o.v; }
  59525. },{"../../lib":168,"../../plots/cartesian/axes":212,"fast-isnumeric":18}],284:[function(_dereq_,module,exports){
  59526. /**
  59527. * Copyright 2012-2019, Plotly, Inc.
  59528. * All rights reserved.
  59529. *
  59530. * This source code is licensed under the MIT license found in the
  59531. * LICENSE file in the root directory of this source tree.
  59532. */
  59533. 'use strict';
  59534. var Axes = _dereq_('../../plots/cartesian/axes');
  59535. var Lib = _dereq_('../../lib');
  59536. var orientations = ['v', 'h'];
  59537. function crossTraceCalc(gd, plotinfo) {
  59538. var calcdata = gd.calcdata;
  59539. var xa = plotinfo.xaxis;
  59540. var ya = plotinfo.yaxis;
  59541. for(var i = 0; i < orientations.length; i++) {
  59542. var orientation = orientations[i];
  59543. var posAxis = orientation === 'h' ? ya : xa;
  59544. var boxList = [];
  59545. // make list of boxes / candlesticks
  59546. // For backward compatibility, candlesticks are treated as if they *are* box traces here
  59547. for(var j = 0; j < calcdata.length; j++) {
  59548. var cd = calcdata[j];
  59549. var t = cd[0].t;
  59550. var trace = cd[0].trace;
  59551. if(trace.visible === true &&
  59552. (trace.type === 'box' || trace.type === 'candlestick') &&
  59553. !t.empty &&
  59554. (trace.orientation || 'v') === orientation &&
  59555. trace.xaxis === xa._id &&
  59556. trace.yaxis === ya._id
  59557. ) {
  59558. boxList.push(j);
  59559. }
  59560. }
  59561. setPositionOffset('box', gd, boxList, posAxis);
  59562. }
  59563. }
  59564. function setPositionOffset(traceType, gd, boxList, posAxis) {
  59565. var calcdata = gd.calcdata;
  59566. var fullLayout = gd._fullLayout;
  59567. var axId = posAxis._id;
  59568. var axLetter = axId.charAt(0);
  59569. // N.B. reused in violin
  59570. var numKey = traceType === 'violin' ? '_numViolins' : '_numBoxes';
  59571. var i, j, calcTrace;
  59572. var pointList = [];
  59573. var shownPts = 0;
  59574. // make list of box points
  59575. for(i = 0; i < boxList.length; i++) {
  59576. calcTrace = calcdata[boxList[i]];
  59577. for(j = 0; j < calcTrace.length; j++) {
  59578. pointList.push(calcTrace[j].pos);
  59579. shownPts += (calcTrace[j].pts2 || []).length;
  59580. }
  59581. }
  59582. if(!pointList.length) return;
  59583. // box plots - update dPos based on multiple traces
  59584. var boxdv = Lib.distinctVals(pointList);
  59585. var dPos0 = boxdv.minDiff / 2;
  59586. // check for forced minimum dtick
  59587. Axes.minDtick(posAxis, boxdv.minDiff, boxdv.vals[0], true);
  59588. var num = fullLayout[numKey];
  59589. var group = (fullLayout[traceType + 'mode'] === 'group' && num > 1);
  59590. var groupFraction = 1 - fullLayout[traceType + 'gap'];
  59591. var groupGapFraction = 1 - fullLayout[traceType + 'groupgap'];
  59592. for(i = 0; i < boxList.length; i++) {
  59593. calcTrace = calcdata[boxList[i]];
  59594. var trace = calcTrace[0].trace;
  59595. var t = calcTrace[0].t;
  59596. var width = trace.width;
  59597. var side = trace.side;
  59598. // position coordinate delta
  59599. var dPos;
  59600. // box half width;
  59601. var bdPos;
  59602. // box center offset
  59603. var bPos;
  59604. // half-width within which to accept hover for this box/violin
  59605. // always split the distance to the closest box/violin
  59606. var wHover;
  59607. if(width) {
  59608. dPos = bdPos = wHover = width / 2;
  59609. bPos = 0;
  59610. } else {
  59611. dPos = dPos0;
  59612. bdPos = dPos * groupFraction * groupGapFraction / (group ? num : 1);
  59613. bPos = group ? 2 * dPos * (-0.5 + (t.num + 0.5) / num) * groupFraction : 0;
  59614. wHover = dPos * (group ? groupFraction / num : 1);
  59615. }
  59616. t.dPos = dPos;
  59617. t.bPos = bPos;
  59618. t.bdPos = bdPos;
  59619. t.wHover = wHover;
  59620. // box/violin-only value-space push value
  59621. var pushplus;
  59622. var pushminus;
  59623. // edge of box/violin
  59624. var edge = bPos + bdPos;
  59625. var edgeplus;
  59626. var edgeminus;
  59627. if(side === 'positive') {
  59628. pushplus = dPos * (width ? 1 : 0.5);
  59629. edgeplus = edge;
  59630. pushminus = edgeplus = bPos;
  59631. } else if(side === 'negative') {
  59632. pushplus = edgeplus = bPos;
  59633. pushminus = dPos * (width ? 1 : 0.5);
  59634. edgeminus = edge;
  59635. } else {
  59636. pushplus = pushminus = dPos;
  59637. edgeplus = edgeminus = edge;
  59638. }
  59639. // value-space padding
  59640. var vpadplus;
  59641. var vpadminus;
  59642. // pixel-space padding
  59643. var ppadplus;
  59644. var ppadminus;
  59645. // do we add 5% of both sides (for points beyond box/violin)
  59646. var padded = false;
  59647. // does this trace show points?
  59648. var hasPts = (trace.boxpoints || trace.points) && (shownPts > 0);
  59649. if(hasPts) {
  59650. var pointpos = trace.pointpos;
  59651. var jitter = trace.jitter;
  59652. var ms = trace.marker.size / 2;
  59653. var pp = 0;
  59654. if((pointpos + jitter) >= 0) {
  59655. pp = edge * (pointpos + jitter);
  59656. if(pp > pushplus) {
  59657. // (++) beyond plus-value, use pp
  59658. padded = true;
  59659. ppadplus = ms;
  59660. vpadplus = pp;
  59661. } else if(pp > edgeplus) {
  59662. // (+), use push-value (it's bigger), but add px-pad
  59663. ppadplus = ms;
  59664. vpadplus = pushplus;
  59665. }
  59666. }
  59667. if(pp <= pushplus) {
  59668. // (->) fallback to push value
  59669. vpadplus = pushplus;
  59670. }
  59671. var pm = 0;
  59672. if((pointpos - jitter) <= 0) {
  59673. pm = -edge * (pointpos - jitter);
  59674. if(pm > pushminus) {
  59675. // (--) beyond plus-value, use pp
  59676. padded = true;
  59677. ppadminus = ms;
  59678. vpadminus = pm;
  59679. } else if(pm > edgeminus) {
  59680. // (-), use push-value (it's bigger), but add px-pad
  59681. ppadminus = ms;
  59682. vpadminus = pushminus;
  59683. }
  59684. }
  59685. if(pm <= pushminus) {
  59686. // (<-) fallback to push value
  59687. vpadminus = pushminus;
  59688. }
  59689. } else {
  59690. vpadplus = pushplus;
  59691. vpadminus = pushminus;
  59692. }
  59693. // calcdata[i][j] are in ascending order
  59694. var firstPos = calcTrace[0].pos;
  59695. var lastPos = calcTrace[calcTrace.length - 1].pos;
  59696. trace._extremes[axId] = Axes.findExtremes(posAxis, [firstPos, lastPos], {
  59697. padded: padded,
  59698. vpadminus: vpadminus,
  59699. vpadplus: vpadplus,
  59700. // N.B. SVG px-space positive/negative
  59701. ppadminus: {x: ppadminus, y: ppadplus}[axLetter],
  59702. ppadplus: {x: ppadplus, y: ppadminus}[axLetter],
  59703. });
  59704. }
  59705. }
  59706. module.exports = {
  59707. crossTraceCalc: crossTraceCalc,
  59708. setPositionOffset: setPositionOffset
  59709. };
  59710. },{"../../lib":168,"../../plots/cartesian/axes":212}],285:[function(_dereq_,module,exports){
  59711. /**
  59712. * Copyright 2012-2019, Plotly, Inc.
  59713. * All rights reserved.
  59714. *
  59715. * This source code is licensed under the MIT license found in the
  59716. * LICENSE file in the root directory of this source tree.
  59717. */
  59718. 'use strict';
  59719. var Lib = _dereq_('../../lib');
  59720. var Registry = _dereq_('../../registry');
  59721. var Color = _dereq_('../../components/color');
  59722. var attributes = _dereq_('./attributes');
  59723. function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
  59724. function coerce(attr, dflt) {
  59725. return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
  59726. }
  59727. handleSampleDefaults(traceIn, traceOut, coerce, layout);
  59728. if(traceOut.visible === false) return;
  59729. coerce('line.color', (traceIn.marker || {}).color || defaultColor);
  59730. coerce('line.width');
  59731. coerce('fillcolor', Color.addOpacity(traceOut.line.color, 0.5));
  59732. coerce('whiskerwidth');
  59733. coerce('boxmean');
  59734. coerce('width');
  59735. var notched = coerce('notched', traceIn.notchwidth !== undefined);
  59736. if(notched) coerce('notchwidth');
  59737. handlePointsDefaults(traceIn, traceOut, coerce, {prefix: 'box'});
  59738. }
  59739. function handleSampleDefaults(traceIn, traceOut, coerce, layout) {
  59740. var y = coerce('y');
  59741. var x = coerce('x');
  59742. var hasX = x && x.length;
  59743. var defaultOrientation, len;
  59744. if(y && y.length) {
  59745. defaultOrientation = 'v';
  59746. if(hasX) {
  59747. len = Math.min(Lib.minRowLength(x), Lib.minRowLength(y));
  59748. } else {
  59749. coerce('x0');
  59750. len = Lib.minRowLength(y);
  59751. }
  59752. } else if(hasX) {
  59753. defaultOrientation = 'h';
  59754. coerce('y0');
  59755. len = Lib.minRowLength(x);
  59756. } else {
  59757. traceOut.visible = false;
  59758. return;
  59759. }
  59760. traceOut._length = len;
  59761. var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
  59762. handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout);
  59763. coerce('orientation', defaultOrientation);
  59764. }
  59765. function handlePointsDefaults(traceIn, traceOut, coerce, opts) {
  59766. var prefix = opts.prefix;
  59767. var outlierColorDflt = Lib.coerce2(traceIn, traceOut, attributes, 'marker.outliercolor');
  59768. var lineoutliercolor = coerce('marker.line.outliercolor');
  59769. var points = coerce(
  59770. prefix + 'points',
  59771. (outlierColorDflt || lineoutliercolor) ? 'suspectedoutliers' : undefined
  59772. );
  59773. if(points) {
  59774. coerce('jitter', points === 'all' ? 0.3 : 0);
  59775. coerce('pointpos', points === 'all' ? -1.5 : 0);
  59776. coerce('marker.symbol');
  59777. coerce('marker.opacity');
  59778. coerce('marker.size');
  59779. coerce('marker.color', traceOut.line.color);
  59780. coerce('marker.line.color');
  59781. coerce('marker.line.width');
  59782. if(points === 'suspectedoutliers') {
  59783. coerce('marker.line.outliercolor', traceOut.marker.color);
  59784. coerce('marker.line.outlierwidth');
  59785. }
  59786. coerce('selected.marker.color');
  59787. coerce('unselected.marker.color');
  59788. coerce('selected.marker.size');
  59789. coerce('unselected.marker.size');
  59790. coerce('text');
  59791. } else {
  59792. delete traceOut.marker;
  59793. }
  59794. coerce('hoveron');
  59795. Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
  59796. }
  59797. module.exports = {
  59798. supplyDefaults: supplyDefaults,
  59799. handleSampleDefaults: handleSampleDefaults,
  59800. handlePointsDefaults: handlePointsDefaults
  59801. };
  59802. },{"../../components/color":51,"../../lib":168,"../../registry":257,"./attributes":282}],286:[function(_dereq_,module,exports){
  59803. /**
  59804. * Copyright 2012-2019, Plotly, Inc.
  59805. * All rights reserved.
  59806. *
  59807. * This source code is licensed under the MIT license found in the
  59808. * LICENSE file in the root directory of this source tree.
  59809. */
  59810. 'use strict';
  59811. module.exports = function eventData(out, pt) {
  59812. // Note: hoverOnBox property is needed for click-to-select
  59813. // to ignore when a box was clicked. This is the reason box
  59814. // implements this custom eventData function.
  59815. if(pt.hoverOnBox) out.hoverOnBox = pt.hoverOnBox;
  59816. if('xVal' in pt) out.x = pt.xVal;
  59817. if('yVal' in pt) out.y = pt.yVal;
  59818. if(pt.xa) out.xaxis = pt.xa;
  59819. if(pt.ya) out.yaxis = pt.ya;
  59820. return out;
  59821. };
  59822. },{}],287:[function(_dereq_,module,exports){
  59823. /**
  59824. * Copyright 2012-2019, Plotly, Inc.
  59825. * All rights reserved.
  59826. *
  59827. * This source code is licensed under the MIT license found in the
  59828. * LICENSE file in the root directory of this source tree.
  59829. */
  59830. 'use strict';
  59831. var Axes = _dereq_('../../plots/cartesian/axes');
  59832. var Lib = _dereq_('../../lib');
  59833. var Fx = _dereq_('../../components/fx');
  59834. var Color = _dereq_('../../components/color');
  59835. var fillHoverText = _dereq_('../scatter/fill_hover_text');
  59836. function hoverPoints(pointData, xval, yval, hovermode) {
  59837. var cd = pointData.cd;
  59838. var trace = cd[0].trace;
  59839. var hoveron = trace.hoveron;
  59840. var closeBoxData = [];
  59841. var closePtData;
  59842. if(hoveron.indexOf('boxes') !== -1) {
  59843. closeBoxData = closeBoxData.concat(hoverOnBoxes(pointData, xval, yval, hovermode));
  59844. }
  59845. if(hoveron.indexOf('points') !== -1) {
  59846. closePtData = hoverOnPoints(pointData, xval, yval);
  59847. }
  59848. // If there's a point in range and hoveron has points, show the best single point only.
  59849. // If hoveron has boxes and there's no point in range (or hoveron doesn't have points), show the box stats.
  59850. if(hovermode === 'closest') {
  59851. if(closePtData) return [closePtData];
  59852. return closeBoxData;
  59853. }
  59854. // Otherwise in compare mode, allow a point AND the box stats to be labeled
  59855. // If there are multiple boxes in range (ie boxmode = 'overlay') we'll see stats for all of them.
  59856. if(closePtData) {
  59857. closeBoxData.push(closePtData);
  59858. return closeBoxData;
  59859. }
  59860. return closeBoxData;
  59861. }
  59862. function hoverOnBoxes(pointData, xval, yval, hovermode) {
  59863. var cd = pointData.cd;
  59864. var xa = pointData.xa;
  59865. var ya = pointData.ya;
  59866. var trace = cd[0].trace;
  59867. var t = cd[0].t;
  59868. var isViolin = trace.type === 'violin';
  59869. var closeBoxData = [];
  59870. var pLetter, vLetter, pAxis, vAxis, vVal, pVal, dx, dy, dPos,
  59871. hoverPseudoDistance, spikePseudoDistance;
  59872. var boxDelta = t.bdPos;
  59873. var posAcceptance = t.wHover;
  59874. var shiftPos = function(di) { return di.pos + t.bPos - pVal; };
  59875. if(isViolin && trace.side !== 'both') {
  59876. if(trace.side === 'positive') {
  59877. dPos = function(di) {
  59878. var pos = shiftPos(di);
  59879. return Fx.inbox(pos, pos + posAcceptance, hoverPseudoDistance);
  59880. };
  59881. }
  59882. if(trace.side === 'negative') {
  59883. dPos = function(di) {
  59884. var pos = shiftPos(di);
  59885. return Fx.inbox(pos - posAcceptance, pos, hoverPseudoDistance);
  59886. };
  59887. }
  59888. } else {
  59889. dPos = function(di) {
  59890. var pos = shiftPos(di);
  59891. return Fx.inbox(pos - posAcceptance, pos + posAcceptance, hoverPseudoDistance);
  59892. };
  59893. }
  59894. var dVal;
  59895. if(isViolin) {
  59896. dVal = function(di) {
  59897. return Fx.inbox(di.span[0] - vVal, di.span[1] - vVal, hoverPseudoDistance);
  59898. };
  59899. } else {
  59900. dVal = function(di) {
  59901. return Fx.inbox(di.min - vVal, di.max - vVal, hoverPseudoDistance);
  59902. };
  59903. }
  59904. if(trace.orientation === 'h') {
  59905. vVal = xval;
  59906. pVal = yval;
  59907. dx = dVal;
  59908. dy = dPos;
  59909. pLetter = 'y';
  59910. pAxis = ya;
  59911. vLetter = 'x';
  59912. vAxis = xa;
  59913. } else {
  59914. vVal = yval;
  59915. pVal = xval;
  59916. dx = dPos;
  59917. dy = dVal;
  59918. pLetter = 'x';
  59919. pAxis = xa;
  59920. vLetter = 'y';
  59921. vAxis = ya;
  59922. }
  59923. // if two boxes are overlaying, let the narrowest one win
  59924. var pseudoDistance = Math.min(1, boxDelta / Math.abs(pAxis.r2c(pAxis.range[1]) - pAxis.r2c(pAxis.range[0])));
  59925. hoverPseudoDistance = pointData.maxHoverDistance - pseudoDistance;
  59926. spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance;
  59927. function dxy(di) { return (dx(di) + dy(di)) / 2; }
  59928. var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);
  59929. Fx.getClosest(cd, distfn, pointData);
  59930. // skip the rest (for this trace) if we didn't find a close point
  59931. // and create the item(s) in closedata for this point
  59932. if(pointData.index === false) return [];
  59933. var di = cd[pointData.index];
  59934. var lc = trace.line.color;
  59935. var mc = (trace.marker || {}).color;
  59936. if(Color.opacity(lc) && trace.line.width) pointData.color = lc;
  59937. else if(Color.opacity(mc) && trace.boxpoints) pointData.color = mc;
  59938. else pointData.color = trace.fillcolor;
  59939. pointData[pLetter + '0'] = pAxis.c2p(di.pos + t.bPos - boxDelta, true);
  59940. pointData[pLetter + '1'] = pAxis.c2p(di.pos + t.bPos + boxDelta, true);
  59941. pointData[pLetter + 'LabelVal'] = di.pos;
  59942. var spikePosAttr = pLetter + 'Spike';
  59943. pointData.spikeDistance = dxy(di) * spikePseudoDistance / hoverPseudoDistance;
  59944. pointData[spikePosAttr] = pAxis.c2p(di.pos, true);
  59945. // box plots: each "point" gets many labels
  59946. var usedVals = {};
  59947. var attrs = ['med', 'min', 'q1', 'q3', 'max'];
  59948. if(trace.boxmean || (trace.meanline || {}).visible) {
  59949. attrs.push('mean');
  59950. }
  59951. if(trace.boxpoints || trace.points) {
  59952. attrs.push('lf', 'uf');
  59953. }
  59954. for(var i = 0; i < attrs.length; i++) {
  59955. var attr = attrs[i];
  59956. if(!(attr in di) || (di[attr] in usedVals)) continue;
  59957. usedVals[di[attr]] = true;
  59958. // copy out to a new object for each value to label
  59959. var val = di[attr];
  59960. var valPx = vAxis.c2p(val, true);
  59961. var pointData2 = Lib.extendFlat({}, pointData);
  59962. pointData2[vLetter + '0'] = pointData2[vLetter + '1'] = valPx;
  59963. pointData2[vLetter + 'LabelVal'] = val;
  59964. pointData2[vLetter + 'Label'] = (t.labels ? t.labels[attr] + ' ' : '') + Axes.hoverLabelText(vAxis, val);
  59965. // Note: introduced to be able to distinguish a
  59966. // clicked point from a box during click-to-select
  59967. pointData2.hoverOnBox = true;
  59968. if(attr === 'mean' && ('sd' in di) && trace.boxmean === 'sd') {
  59969. pointData2[vLetter + 'err'] = di.sd;
  59970. }
  59971. // only keep name and spikes on the first item (median)
  59972. pointData.name = '';
  59973. pointData.spikeDistance = undefined;
  59974. pointData[spikePosAttr] = undefined;
  59975. closeBoxData.push(pointData2);
  59976. }
  59977. return closeBoxData;
  59978. }
  59979. function hoverOnPoints(pointData, xval, yval) {
  59980. var cd = pointData.cd;
  59981. var xa = pointData.xa;
  59982. var ya = pointData.ya;
  59983. var trace = cd[0].trace;
  59984. var xPx = xa.c2p(xval);
  59985. var yPx = ya.c2p(yval);
  59986. var closePtData;
  59987. var dx = function(di) {
  59988. var rad = Math.max(3, di.mrc || 0);
  59989. return Math.max(Math.abs(xa.c2p(di.x) - xPx) - rad, 1 - 3 / rad);
  59990. };
  59991. var dy = function(di) {
  59992. var rad = Math.max(3, di.mrc || 0);
  59993. return Math.max(Math.abs(ya.c2p(di.y) - yPx) - rad, 1 - 3 / rad);
  59994. };
  59995. var distfn = Fx.quadrature(dx, dy);
  59996. // show one point per trace
  59997. var ijClosest = false;
  59998. var di, pt;
  59999. for(var i = 0; i < cd.length; i++) {
  60000. di = cd[i];
  60001. for(var j = 0; j < (di.pts || []).length; j++) {
  60002. pt = di.pts[j];
  60003. var newDistance = distfn(pt);
  60004. if(newDistance <= pointData.distance) {
  60005. pointData.distance = newDistance;
  60006. ijClosest = [i, j];
  60007. }
  60008. }
  60009. }
  60010. if(!ijClosest) return false;
  60011. di = cd[ijClosest[0]];
  60012. pt = di.pts[ijClosest[1]];
  60013. var xc = xa.c2p(pt.x, true);
  60014. var yc = ya.c2p(pt.y, true);
  60015. var rad = pt.mrc || 1;
  60016. closePtData = Lib.extendFlat({}, pointData, {
  60017. // corresponds to index in x/y input data array
  60018. index: pt.i,
  60019. color: (trace.marker || {}).color,
  60020. name: trace.name,
  60021. x0: xc - rad,
  60022. x1: xc + rad,
  60023. y0: yc - rad,
  60024. y1: yc + rad,
  60025. spikeDistance: pointData.distance
  60026. });
  60027. var pa;
  60028. if(trace.orientation === 'h') {
  60029. pa = ya;
  60030. closePtData.xLabelVal = pt.x;
  60031. closePtData.yLabelVal = di.pos;
  60032. } else {
  60033. pa = xa;
  60034. closePtData.xLabelVal = di.pos;
  60035. closePtData.yLabelVal = pt.y;
  60036. }
  60037. var pLetter = pa._id.charAt(0);
  60038. closePtData[pLetter + 'Spike'] = pa.c2p(di.pos, true);
  60039. fillHoverText(pt, trace, closePtData);
  60040. return closePtData;
  60041. }
  60042. module.exports = {
  60043. hoverPoints: hoverPoints,
  60044. hoverOnBoxes: hoverOnBoxes,
  60045. hoverOnPoints: hoverOnPoints
  60046. };
  60047. },{"../../components/color":51,"../../components/fx":90,"../../lib":168,"../../plots/cartesian/axes":212,"../scatter/fill_hover_text":375}],288:[function(_dereq_,module,exports){
  60048. /**
  60049. * Copyright 2012-2019, Plotly, Inc.
  60050. * All rights reserved.
  60051. *
  60052. * This source code is licensed under the MIT license found in the
  60053. * LICENSE file in the root directory of this source tree.
  60054. */
  60055. 'use strict';
  60056. var Box = {};
  60057. Box.attributes = _dereq_('./attributes');
  60058. Box.layoutAttributes = _dereq_('./layout_attributes');
  60059. Box.supplyDefaults = _dereq_('./defaults').supplyDefaults;
  60060. Box.supplyLayoutDefaults = _dereq_('./layout_defaults').supplyLayoutDefaults;
  60061. Box.calc = _dereq_('./calc');
  60062. Box.crossTraceCalc = _dereq_('./cross_trace_calc').crossTraceCalc;
  60063. Box.plot = _dereq_('./plot').plot;
  60064. Box.style = _dereq_('./style').style;
  60065. Box.styleOnSelect = _dereq_('./style').styleOnSelect;
  60066. Box.hoverPoints = _dereq_('./hover').hoverPoints;
  60067. Box.eventData = _dereq_('./event_data');
  60068. Box.selectPoints = _dereq_('./select');
  60069. Box.moduleType = 'trace';
  60070. Box.name = 'box';
  60071. Box.basePlotModule = _dereq_('../../plots/cartesian');
  60072. Box.categories = ['cartesian', 'svg', 'symbols', 'oriented', 'box-violin', 'showLegend', 'boxLayout', 'zoomScale'];
  60073. Box.meta = {
  60074. };
  60075. module.exports = Box;
  60076. },{"../../plots/cartesian":224,"./attributes":282,"./calc":283,"./cross_trace_calc":284,"./defaults":285,"./event_data":286,"./hover":287,"./layout_attributes":289,"./layout_defaults":290,"./plot":291,"./select":292,"./style":293}],289:[function(_dereq_,module,exports){
  60077. /**
  60078. * Copyright 2012-2019, Plotly, Inc.
  60079. * All rights reserved.
  60080. *
  60081. * This source code is licensed under the MIT license found in the
  60082. * LICENSE file in the root directory of this source tree.
  60083. */
  60084. 'use strict';
  60085. module.exports = {
  60086. boxmode: {
  60087. valType: 'enumerated',
  60088. values: ['group', 'overlay'],
  60089. dflt: 'overlay',
  60090. editType: 'calc',
  60091. },
  60092. boxgap: {
  60093. valType: 'number',
  60094. min: 0,
  60095. max: 1,
  60096. dflt: 0.3,
  60097. editType: 'calc',
  60098. },
  60099. boxgroupgap: {
  60100. valType: 'number',
  60101. min: 0,
  60102. max: 1,
  60103. dflt: 0.3,
  60104. editType: 'calc',
  60105. }
  60106. };
  60107. },{}],290:[function(_dereq_,module,exports){
  60108. /**
  60109. * Copyright 2012-2019, Plotly, Inc.
  60110. * All rights reserved.
  60111. *
  60112. * This source code is licensed under the MIT license found in the
  60113. * LICENSE file in the root directory of this source tree.
  60114. */
  60115. 'use strict';
  60116. var Registry = _dereq_('../../registry');
  60117. var Lib = _dereq_('../../lib');
  60118. var layoutAttributes = _dereq_('./layout_attributes');
  60119. function _supply(layoutIn, layoutOut, fullData, coerce, traceType) {
  60120. var hasTraceType;
  60121. var category = traceType + 'Layout';
  60122. for(var i = 0; i < fullData.length; i++) {
  60123. if(Registry.traceIs(fullData[i], category)) {
  60124. hasTraceType = true;
  60125. break;
  60126. }
  60127. }
  60128. if(!hasTraceType) return;
  60129. coerce(traceType + 'mode');
  60130. coerce(traceType + 'gap');
  60131. coerce(traceType + 'groupgap');
  60132. }
  60133. function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
  60134. function coerce(attr, dflt) {
  60135. return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
  60136. }
  60137. _supply(layoutIn, layoutOut, fullData, coerce, 'box');
  60138. }
  60139. module.exports = {
  60140. supplyLayoutDefaults: supplyLayoutDefaults,
  60141. _supply: _supply
  60142. };
  60143. },{"../../lib":168,"../../registry":257,"./layout_attributes":289}],291:[function(_dereq_,module,exports){
  60144. /**
  60145. * Copyright 2012-2019, Plotly, Inc.
  60146. * All rights reserved.
  60147. *
  60148. * This source code is licensed under the MIT license found in the
  60149. * LICENSE file in the root directory of this source tree.
  60150. */
  60151. 'use strict';
  60152. var d3 = _dereq_('d3');
  60153. var Lib = _dereq_('../../lib');
  60154. var Drawing = _dereq_('../../components/drawing');
  60155. // constants for dynamic jitter (ie less jitter for sparser points)
  60156. var JITTERCOUNT = 5; // points either side of this to include
  60157. var JITTERSPREAD = 0.01; // fraction of IQR to count as "dense"
  60158. function plot(gd, plotinfo, cdbox, boxLayer) {
  60159. var xa = plotinfo.xaxis;
  60160. var ya = plotinfo.yaxis;
  60161. Lib.makeTraceGroups(boxLayer, cdbox, 'trace boxes').each(function(cd) {
  60162. var plotGroup = d3.select(this);
  60163. var cd0 = cd[0];
  60164. var t = cd0.t;
  60165. var trace = cd0.trace;
  60166. if(!plotinfo.isRangePlot) cd0.node3 = plotGroup;
  60167. // whisker width
  60168. t.wdPos = t.bdPos * trace.whiskerwidth;
  60169. if(trace.visible !== true || t.empty) {
  60170. plotGroup.remove();
  60171. return;
  60172. }
  60173. var posAxis, valAxis;
  60174. if(trace.orientation === 'h') {
  60175. posAxis = ya;
  60176. valAxis = xa;
  60177. } else {
  60178. posAxis = xa;
  60179. valAxis = ya;
  60180. }
  60181. plotBoxAndWhiskers(plotGroup, {pos: posAxis, val: valAxis}, trace, t);
  60182. plotPoints(plotGroup, {x: xa, y: ya}, trace, t);
  60183. plotBoxMean(plotGroup, {pos: posAxis, val: valAxis}, trace, t);
  60184. });
  60185. }
  60186. function plotBoxAndWhiskers(sel, axes, trace, t) {
  60187. var posAxis = axes.pos;
  60188. var valAxis = axes.val;
  60189. var bPos = t.bPos;
  60190. var wdPos = t.wdPos || 0;
  60191. var bPosPxOffset = t.bPosPxOffset || 0;
  60192. var whiskerWidth = trace.whiskerwidth || 0;
  60193. var notched = trace.notched || false;
  60194. var nw = notched ? 1 - 2 * trace.notchwidth : 1;
  60195. // to support for one-sided box
  60196. var bdPos0;
  60197. var bdPos1;
  60198. if(Array.isArray(t.bdPos)) {
  60199. bdPos0 = t.bdPos[0];
  60200. bdPos1 = t.bdPos[1];
  60201. } else {
  60202. bdPos0 = t.bdPos;
  60203. bdPos1 = t.bdPos;
  60204. }
  60205. var paths = sel.selectAll('path.box').data((
  60206. trace.type !== 'violin' ||
  60207. trace.box.visible
  60208. ) ? Lib.identity : []);
  60209. paths.enter().append('path')
  60210. .style('vector-effect', 'non-scaling-stroke')
  60211. .attr('class', 'box');
  60212. paths.exit().remove();
  60213. paths.each(function(d) {
  60214. if(d.empty) return 'M0,0Z';
  60215. var pos = d.pos;
  60216. var posc = posAxis.c2p(pos + bPos, true) + bPosPxOffset;
  60217. var pos0 = posAxis.c2p(pos + bPos - bdPos0, true) + bPosPxOffset;
  60218. var pos1 = posAxis.c2p(pos + bPos + bdPos1, true) + bPosPxOffset;
  60219. var posw0 = posAxis.c2p(pos + bPos - wdPos, true) + bPosPxOffset;
  60220. var posw1 = posAxis.c2p(pos + bPos + wdPos, true) + bPosPxOffset;
  60221. var posm0 = posAxis.c2p(pos + bPos - bdPos0 * nw, true) + bPosPxOffset;
  60222. var posm1 = posAxis.c2p(pos + bPos + bdPos1 * nw, true) + bPosPxOffset;
  60223. var q1 = valAxis.c2p(d.q1, true);
  60224. var q3 = valAxis.c2p(d.q3, true);
  60225. // make sure median isn't identical to either of the
  60226. // quartiles, so we can see it
  60227. var m = Lib.constrain(
  60228. valAxis.c2p(d.med, true),
  60229. Math.min(q1, q3) + 1, Math.max(q1, q3) - 1
  60230. );
  60231. // for compatibility with box, violin, and candlestick
  60232. // perhaps we should put this into cd0.t instead so it's more explicit,
  60233. // but what we have now is:
  60234. // - box always has d.lf, but boxpoints can be anything
  60235. // - violin has d.lf and should always use it (boxpoints is undefined)
  60236. // - candlestick has only min/max
  60237. var useExtremes = (d.lf === undefined) || (trace.boxpoints === false);
  60238. var lf = valAxis.c2p(useExtremes ? d.min : d.lf, true);
  60239. var uf = valAxis.c2p(useExtremes ? d.max : d.uf, true);
  60240. var ln = valAxis.c2p(d.ln, true);
  60241. var un = valAxis.c2p(d.un, true);
  60242. if(trace.orientation === 'h') {
  60243. d3.select(this).attr('d',
  60244. 'M' + m + ',' + posm0 + 'V' + posm1 + // median line
  60245. 'M' + q1 + ',' + pos0 + 'V' + pos1 + // left edge
  60246. (notched ? 'H' + ln + 'L' + m + ',' + posm1 + 'L' + un + ',' + pos1 : '') + // top notched edge
  60247. 'H' + q3 + // end of the top edge
  60248. 'V' + pos0 + // right edge
  60249. (notched ? 'H' + un + 'L' + m + ',' + posm0 + 'L' + ln + ',' + pos0 : '') + // bottom notched edge
  60250. 'Z' + // end of the box
  60251. 'M' + q1 + ',' + posc + 'H' + lf + 'M' + q3 + ',' + posc + 'H' + uf + // whiskers
  60252. ((whiskerWidth === 0) ? '' : // whisker caps
  60253. 'M' + lf + ',' + posw0 + 'V' + posw1 + 'M' + uf + ',' + posw0 + 'V' + posw1));
  60254. } else {
  60255. d3.select(this).attr('d',
  60256. 'M' + posm0 + ',' + m + 'H' + posm1 + // median line
  60257. 'M' + pos0 + ',' + q1 + 'H' + pos1 + // top of the box
  60258. (notched ? 'V' + ln + 'L' + posm1 + ',' + m + 'L' + pos1 + ',' + un : '') + // notched right edge
  60259. 'V' + q3 + // end of the right edge
  60260. 'H' + pos0 + // bottom of the box
  60261. (notched ? 'V' + un + 'L' + posm0 + ',' + m + 'L' + pos0 + ',' + ln : '') + // notched left edge
  60262. 'Z' + // end of the box
  60263. 'M' + posc + ',' + q1 + 'V' + lf + 'M' + posc + ',' + q3 + 'V' + uf + // whiskers
  60264. ((whiskerWidth === 0) ? '' : // whisker caps
  60265. 'M' + posw0 + ',' + lf + 'H' + posw1 + 'M' + posw0 + ',' + uf + 'H' + posw1));
  60266. }
  60267. });
  60268. }
  60269. function plotPoints(sel, axes, trace, t) {
  60270. var xa = axes.x;
  60271. var ya = axes.y;
  60272. var bdPos = t.bdPos;
  60273. var bPos = t.bPos;
  60274. // to support violin points
  60275. var mode = trace.boxpoints || trace.points;
  60276. // repeatable pseudo-random number generator
  60277. Lib.seedPseudoRandom();
  60278. // since box plot points get an extra level of nesting, each
  60279. // box needs the trace styling info
  60280. var fn = function(d) {
  60281. d.forEach(function(v) {
  60282. v.t = t;
  60283. v.trace = trace;
  60284. });
  60285. return d;
  60286. };
  60287. var gPoints = sel.selectAll('g.points')
  60288. .data(mode ? fn : []);
  60289. gPoints.enter().append('g')
  60290. .attr('class', 'points');
  60291. gPoints.exit().remove();
  60292. var paths = gPoints.selectAll('path')
  60293. .data(function(d) {
  60294. var i;
  60295. var pts = d.pts2;
  60296. // normally use IQR, but if this is 0 or too small, use max-min
  60297. var typicalSpread = Math.max((d.max - d.min) / 10, d.q3 - d.q1);
  60298. var minSpread = typicalSpread * 1e-9;
  60299. var spreadLimit = typicalSpread * JITTERSPREAD;
  60300. var jitterFactors = [];
  60301. var maxJitterFactor = 0;
  60302. var newJitter;
  60303. // dynamic jitter
  60304. if(trace.jitter) {
  60305. if(typicalSpread === 0) {
  60306. // edge case of no spread at all: fall back to max jitter
  60307. maxJitterFactor = 1;
  60308. jitterFactors = new Array(pts.length);
  60309. for(i = 0; i < pts.length; i++) {
  60310. jitterFactors[i] = 1;
  60311. }
  60312. } else {
  60313. for(i = 0; i < pts.length; i++) {
  60314. var i0 = Math.max(0, i - JITTERCOUNT);
  60315. var pmin = pts[i0].v;
  60316. var i1 = Math.min(pts.length - 1, i + JITTERCOUNT);
  60317. var pmax = pts[i1].v;
  60318. if(mode !== 'all') {
  60319. if(pts[i].v < d.lf) pmax = Math.min(pmax, d.lf);
  60320. else pmin = Math.max(pmin, d.uf);
  60321. }
  60322. var jitterFactor = Math.sqrt(spreadLimit * (i1 - i0) / (pmax - pmin + minSpread)) || 0;
  60323. jitterFactor = Lib.constrain(Math.abs(jitterFactor), 0, 1);
  60324. jitterFactors.push(jitterFactor);
  60325. maxJitterFactor = Math.max(jitterFactor, maxJitterFactor);
  60326. }
  60327. }
  60328. newJitter = trace.jitter * 2 / (maxJitterFactor || 1);
  60329. }
  60330. // fills in 'x' and 'y' in calcdata 'pts' item
  60331. for(i = 0; i < pts.length; i++) {
  60332. var pt = pts[i];
  60333. var v = pt.v;
  60334. var jitterOffset = trace.jitter ?
  60335. (newJitter * jitterFactors[i] * (Lib.pseudoRandom() - 0.5)) :
  60336. 0;
  60337. var posPx = d.pos + bPos + bdPos * (trace.pointpos + jitterOffset);
  60338. if(trace.orientation === 'h') {
  60339. pt.y = posPx;
  60340. pt.x = v;
  60341. } else {
  60342. pt.x = posPx;
  60343. pt.y = v;
  60344. }
  60345. // tag suspected outliers
  60346. if(mode === 'suspectedoutliers' && v < d.uo && v > d.lo) {
  60347. pt.so = true;
  60348. }
  60349. }
  60350. return pts;
  60351. });
  60352. paths.enter().append('path')
  60353. .classed('point', true);
  60354. paths.exit().remove();
  60355. paths.call(Drawing.translatePoints, xa, ya);
  60356. }
  60357. function plotBoxMean(sel, axes, trace, t) {
  60358. var posAxis = axes.pos;
  60359. var valAxis = axes.val;
  60360. var bPos = t.bPos;
  60361. var bPosPxOffset = t.bPosPxOffset || 0;
  60362. // to support violin mean lines
  60363. var mode = trace.boxmean || (trace.meanline || {}).visible;
  60364. // to support for one-sided box
  60365. var bdPos0;
  60366. var bdPos1;
  60367. if(Array.isArray(t.bdPos)) {
  60368. bdPos0 = t.bdPos[0];
  60369. bdPos1 = t.bdPos[1];
  60370. } else {
  60371. bdPos0 = t.bdPos;
  60372. bdPos1 = t.bdPos;
  60373. }
  60374. var paths = sel.selectAll('path.mean').data((
  60375. (trace.type === 'box' && trace.boxmean) ||
  60376. (trace.type === 'violin' && trace.box.visible && trace.meanline.visible)
  60377. ) ? Lib.identity : []);
  60378. paths.enter().append('path')
  60379. .attr('class', 'mean')
  60380. .style({
  60381. fill: 'none',
  60382. 'vector-effect': 'non-scaling-stroke'
  60383. });
  60384. paths.exit().remove();
  60385. paths.each(function(d) {
  60386. var posc = posAxis.c2p(d.pos + bPos, true) + bPosPxOffset;
  60387. var pos0 = posAxis.c2p(d.pos + bPos - bdPos0, true) + bPosPxOffset;
  60388. var pos1 = posAxis.c2p(d.pos + bPos + bdPos1, true) + bPosPxOffset;
  60389. var m = valAxis.c2p(d.mean, true);
  60390. var sl = valAxis.c2p(d.mean - d.sd, true);
  60391. var sh = valAxis.c2p(d.mean + d.sd, true);
  60392. if(trace.orientation === 'h') {
  60393. d3.select(this).attr('d',
  60394. 'M' + m + ',' + pos0 + 'V' + pos1 +
  60395. (mode === 'sd' ?
  60396. 'm0,0L' + sl + ',' + posc + 'L' + m + ',' + pos0 + 'L' + sh + ',' + posc + 'Z' :
  60397. '')
  60398. );
  60399. } else {
  60400. d3.select(this).attr('d',
  60401. 'M' + pos0 + ',' + m + 'H' + pos1 +
  60402. (mode === 'sd' ?
  60403. 'm0,0L' + posc + ',' + sl + 'L' + pos0 + ',' + m + 'L' + posc + ',' + sh + 'Z' :
  60404. '')
  60405. );
  60406. }
  60407. });
  60408. }
  60409. module.exports = {
  60410. plot: plot,
  60411. plotBoxAndWhiskers: plotBoxAndWhiskers,
  60412. plotPoints: plotPoints,
  60413. plotBoxMean: plotBoxMean
  60414. };
  60415. },{"../../components/drawing":72,"../../lib":168,"d3":16}],292:[function(_dereq_,module,exports){
  60416. /**
  60417. * Copyright 2012-2019, Plotly, Inc.
  60418. * All rights reserved.
  60419. *
  60420. * This source code is licensed under the MIT license found in the
  60421. * LICENSE file in the root directory of this source tree.
  60422. */
  60423. 'use strict';
  60424. module.exports = function selectPoints(searchInfo, selectionTester) {
  60425. var cd = searchInfo.cd;
  60426. var xa = searchInfo.xaxis;
  60427. var ya = searchInfo.yaxis;
  60428. var selection = [];
  60429. var i, j;
  60430. if(selectionTester === false) {
  60431. for(i = 0; i < cd.length; i++) {
  60432. for(j = 0; j < (cd[i].pts || []).length; j++) {
  60433. // clear selection
  60434. cd[i].pts[j].selected = 0;
  60435. }
  60436. }
  60437. } else {
  60438. for(i = 0; i < cd.length; i++) {
  60439. for(j = 0; j < (cd[i].pts || []).length; j++) {
  60440. var pt = cd[i].pts[j];
  60441. var x = xa.c2p(pt.x);
  60442. var y = ya.c2p(pt.y);
  60443. if(selectionTester.contains([x, y], null, pt.i, searchInfo)) {
  60444. selection.push({
  60445. pointNumber: pt.i,
  60446. x: xa.c2d(pt.x),
  60447. y: ya.c2d(pt.y)
  60448. });
  60449. pt.selected = 1;
  60450. } else {
  60451. pt.selected = 0;
  60452. }
  60453. }
  60454. }
  60455. }
  60456. return selection;
  60457. };
  60458. },{}],293:[function(_dereq_,module,exports){
  60459. /**
  60460. * Copyright 2012-2019, Plotly, Inc.
  60461. * All rights reserved.
  60462. *
  60463. * This source code is licensed under the MIT license found in the
  60464. * LICENSE file in the root directory of this source tree.
  60465. */
  60466. 'use strict';
  60467. var d3 = _dereq_('d3');
  60468. var Color = _dereq_('../../components/color');
  60469. var Drawing = _dereq_('../../components/drawing');
  60470. function style(gd, cd) {
  60471. var s = cd ? cd[0].node3 : d3.select(gd).selectAll('g.trace.boxes');
  60472. s.style('opacity', function(d) { return d[0].trace.opacity; });
  60473. s.each(function(d) {
  60474. var el = d3.select(this);
  60475. var trace = d[0].trace;
  60476. var lineWidth = trace.line.width;
  60477. function styleBox(boxSel, lineWidth, lineColor, fillColor) {
  60478. boxSel.style('stroke-width', lineWidth + 'px')
  60479. .call(Color.stroke, lineColor)
  60480. .call(Color.fill, fillColor);
  60481. }
  60482. var allBoxes = el.selectAll('path.box');
  60483. if(trace.type === 'candlestick') {
  60484. allBoxes.each(function(boxData) {
  60485. if(boxData.empty) return;
  60486. var thisBox = d3.select(this);
  60487. var container = trace[boxData.dir]; // dir = 'increasing' or 'decreasing'
  60488. styleBox(thisBox, container.line.width, container.line.color, container.fillcolor);
  60489. // TODO: custom selection style for candlesticks
  60490. thisBox.style('opacity', trace.selectedpoints && !boxData.selected ? 0.3 : 1);
  60491. });
  60492. } else {
  60493. styleBox(allBoxes, lineWidth, trace.line.color, trace.fillcolor);
  60494. el.selectAll('path.mean')
  60495. .style({
  60496. 'stroke-width': lineWidth,
  60497. 'stroke-dasharray': (2 * lineWidth) + 'px,' + lineWidth + 'px'
  60498. })
  60499. .call(Color.stroke, trace.line.color);
  60500. var pts = el.selectAll('path.point');
  60501. Drawing.pointStyle(pts, trace, gd);
  60502. }
  60503. });
  60504. }
  60505. function styleOnSelect(gd, cd) {
  60506. var s = cd[0].node3;
  60507. var trace = cd[0].trace;
  60508. var pts = s.selectAll('path.point');
  60509. if(trace.selectedpoints) {
  60510. Drawing.selectedPointStyle(pts, trace);
  60511. } else {
  60512. Drawing.pointStyle(pts, trace, gd);
  60513. }
  60514. }
  60515. module.exports = {
  60516. style: style,
  60517. styleOnSelect: styleOnSelect
  60518. };
  60519. },{"../../components/color":51,"../../components/drawing":72,"d3":16}],294:[function(_dereq_,module,exports){
  60520. /**
  60521. * Copyright 2012-2019, Plotly, Inc.
  60522. * All rights reserved.
  60523. *
  60524. * This source code is licensed under the MIT license found in the
  60525. * LICENSE file in the root directory of this source tree.
  60526. */
  60527. 'use strict';
  60528. var heatmapAttrs = _dereq_('../heatmap/attributes');
  60529. var scatterAttrs = _dereq_('../scatter/attributes');
  60530. var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
  60531. var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
  60532. var dash = _dereq_('../../components/drawing/attributes').dash;
  60533. var fontAttrs = _dereq_('../../plots/font_attributes');
  60534. var extendFlat = _dereq_('../../lib/extend').extendFlat;
  60535. var filterOps = _dereq_('../../constants/filter_ops');
  60536. var COMPARISON_OPS2 = filterOps.COMPARISON_OPS2;
  60537. var INTERVAL_OPS = filterOps.INTERVAL_OPS;
  60538. var scatterLineAttrs = scatterAttrs.line;
  60539. module.exports = extendFlat({
  60540. z: heatmapAttrs.z,
  60541. x: heatmapAttrs.x,
  60542. x0: heatmapAttrs.x0,
  60543. dx: heatmapAttrs.dx,
  60544. y: heatmapAttrs.y,
  60545. y0: heatmapAttrs.y0,
  60546. dy: heatmapAttrs.dy,
  60547. text: heatmapAttrs.text,
  60548. transpose: heatmapAttrs.transpose,
  60549. xtype: heatmapAttrs.xtype,
  60550. ytype: heatmapAttrs.ytype,
  60551. zhoverformat: heatmapAttrs.zhoverformat,
  60552. connectgaps: heatmapAttrs.connectgaps,
  60553. fillcolor: {
  60554. valType: 'color',
  60555. editType: 'calc',
  60556. },
  60557. autocontour: {
  60558. valType: 'boolean',
  60559. dflt: true,
  60560. editType: 'calc',
  60561. impliedEdits: {
  60562. 'contours.start': undefined,
  60563. 'contours.end': undefined,
  60564. 'contours.size': undefined
  60565. },
  60566. },
  60567. ncontours: {
  60568. valType: 'integer',
  60569. dflt: 15,
  60570. min: 1,
  60571. editType: 'calc',
  60572. },
  60573. contours: {
  60574. type: {
  60575. valType: 'enumerated',
  60576. values: ['levels', 'constraint'],
  60577. dflt: 'levels',
  60578. editType: 'calc',
  60579. },
  60580. start: {
  60581. valType: 'number',
  60582. dflt: null,
  60583. editType: 'plot',
  60584. impliedEdits: {'^autocontour': false},
  60585. },
  60586. end: {
  60587. valType: 'number',
  60588. dflt: null,
  60589. editType: 'plot',
  60590. impliedEdits: {'^autocontour': false},
  60591. },
  60592. size: {
  60593. valType: 'number',
  60594. dflt: null,
  60595. min: 0,
  60596. editType: 'plot',
  60597. impliedEdits: {'^autocontour': false},
  60598. },
  60599. coloring: {
  60600. valType: 'enumerated',
  60601. values: ['fill', 'heatmap', 'lines', 'none'],
  60602. dflt: 'fill',
  60603. editType: 'calc',
  60604. },
  60605. showlines: {
  60606. valType: 'boolean',
  60607. dflt: true,
  60608. editType: 'plot',
  60609. },
  60610. showlabels: {
  60611. valType: 'boolean',
  60612. dflt: false,
  60613. editType: 'plot',
  60614. },
  60615. labelfont: fontAttrs({
  60616. editType: 'plot',
  60617. colorEditType: 'style',
  60618. }),
  60619. labelformat: {
  60620. valType: 'string',
  60621. dflt: '',
  60622. editType: 'plot',
  60623. },
  60624. operation: {
  60625. valType: 'enumerated',
  60626. values: [].concat(COMPARISON_OPS2).concat(INTERVAL_OPS),
  60627. dflt: '=',
  60628. editType: 'calc',
  60629. },
  60630. value: {
  60631. valType: 'any',
  60632. dflt: 0,
  60633. editType: 'calc',
  60634. },
  60635. editType: 'calc',
  60636. impliedEdits: {'autocontour': false}
  60637. },
  60638. line: {
  60639. color: extendFlat({}, scatterLineAttrs.color, {
  60640. editType: 'style+colorbars',
  60641. }),
  60642. width: extendFlat({}, scatterLineAttrs.width, {
  60643. editType: 'style+colorbars'
  60644. }),
  60645. dash: dash,
  60646. smoothing: extendFlat({}, scatterLineAttrs.smoothing, {
  60647. }),
  60648. editType: 'plot'
  60649. }
  60650. },
  60651. colorscaleAttrs('', {
  60652. cLetter: 'z',
  60653. autoColorDflt: false,
  60654. editTypeOverride: 'calc'
  60655. }),
  60656. { colorbar: colorbarAttrs }
  60657. );
  60658. },{"../../components/colorbar/attributes":52,"../../components/colorscale/attributes":58,"../../components/drawing/attributes":71,"../../constants/filter_ops":147,"../../lib/extend":162,"../../plots/font_attributes":239,"../heatmap/attributes":316,"../scatter/attributes":367}],295:[function(_dereq_,module,exports){
  60659. /**
  60660. * Copyright 2012-2019, Plotly, Inc.
  60661. * All rights reserved.
  60662. *
  60663. * This source code is licensed under the MIT license found in the
  60664. * LICENSE file in the root directory of this source tree.
  60665. */
  60666. 'use strict';
  60667. var heatmapCalc = _dereq_('../heatmap/calc');
  60668. var setContours = _dereq_('./set_contours');
  60669. // most is the same as heatmap calc, then adjust it
  60670. // though a few things inside heatmap calc still look for
  60671. // contour maps, because the makeBoundArray calls are too entangled
  60672. module.exports = function calc(gd, trace) {
  60673. var cd = heatmapCalc(gd, trace);
  60674. setContours(trace);
  60675. return cd;
  60676. };
  60677. },{"../heatmap/calc":317,"./set_contours":313}],296:[function(_dereq_,module,exports){
  60678. /**
  60679. * Copyright 2012-2019, Plotly, Inc.
  60680. * All rights reserved.
  60681. *
  60682. * This source code is licensed under the MIT license found in the
  60683. * LICENSE file in the root directory of this source tree.
  60684. */
  60685. 'use strict';
  60686. module.exports = function(pathinfo, operation, perimeter, trace) {
  60687. // Abandon all hope, ye who enter here.
  60688. var i, v1, v2;
  60689. var pi0 = pathinfo[0];
  60690. var na = pi0.x.length;
  60691. var nb = pi0.y.length;
  60692. var z = pi0.z;
  60693. var contours = trace.contours;
  60694. var boundaryMax = -Infinity;
  60695. var boundaryMin = Infinity;
  60696. for(i = 0; i < nb; i++) {
  60697. boundaryMin = Math.min(boundaryMin, z[i][0]);
  60698. boundaryMin = Math.min(boundaryMin, z[i][na - 1]);
  60699. boundaryMax = Math.max(boundaryMax, z[i][0]);
  60700. boundaryMax = Math.max(boundaryMax, z[i][na - 1]);
  60701. }
  60702. for(i = 1; i < na - 1; i++) {
  60703. boundaryMin = Math.min(boundaryMin, z[0][i]);
  60704. boundaryMin = Math.min(boundaryMin, z[nb - 1][i]);
  60705. boundaryMax = Math.max(boundaryMax, z[0][i]);
  60706. boundaryMax = Math.max(boundaryMax, z[nb - 1][i]);
  60707. }
  60708. pi0.prefixBoundary = false;
  60709. switch(operation) {
  60710. case '>':
  60711. if(contours.value > boundaryMax) {
  60712. pi0.prefixBoundary = true;
  60713. }
  60714. break;
  60715. case '<':
  60716. if(contours.value < boundaryMin) {
  60717. pi0.prefixBoundary = true;
  60718. }
  60719. break;
  60720. case '[]':
  60721. v1 = Math.min.apply(null, contours.value);
  60722. v2 = Math.max.apply(null, contours.value);
  60723. if(v2 < boundaryMin || v1 > boundaryMax) {
  60724. pi0.prefixBoundary = true;
  60725. }
  60726. break;
  60727. case '][':
  60728. v1 = Math.min.apply(null, contours.value);
  60729. v2 = Math.max.apply(null, contours.value);
  60730. if(v1 < boundaryMin && v2 > boundaryMax) {
  60731. pi0.prefixBoundary = true;
  60732. }
  60733. break;
  60734. }
  60735. };
  60736. },{}],297:[function(_dereq_,module,exports){
  60737. /**
  60738. * Copyright 2012-2019, Plotly, Inc.
  60739. * All rights reserved.
  60740. *
  60741. * This source code is licensed under the MIT license found in the
  60742. * LICENSE file in the root directory of this source tree.
  60743. */
  60744. 'use strict';
  60745. var drawColorbar = _dereq_('../../components/colorbar/draw');
  60746. var makeColorMap = _dereq_('./make_color_map');
  60747. var endPlus = _dereq_('./end_plus');
  60748. module.exports = function colorbar(gd, cd) {
  60749. var trace = cd[0].trace;
  60750. var cbId = 'cb' + trace.uid;
  60751. gd._fullLayout._infolayer.selectAll('.' + cbId).remove();
  60752. if(!trace.showscale) return;
  60753. var cb = cd[0].t.cb = drawColorbar(gd, cbId);
  60754. var contours = trace.contours;
  60755. var line = trace.line;
  60756. var cs = contours.size || 1;
  60757. var coloring = contours.coloring;
  60758. var colorMap = makeColorMap(trace, {isColorbar: true});
  60759. cb.fillgradient(coloring === 'heatmap' ? trace.colorscale : '')
  60760. .zrange(coloring === 'heatmap' ? [trace.zmin, trace.zmax] : '')
  60761. .fillcolor((coloring === 'fill') ? colorMap : '')
  60762. .line({
  60763. color: coloring === 'lines' ? colorMap : line.color,
  60764. width: contours.showlines !== false ? line.width : 0,
  60765. dash: line.dash
  60766. })
  60767. .levels({
  60768. start: contours.start,
  60769. end: endPlus(contours),
  60770. size: cs
  60771. })
  60772. .options(trace.colorbar)();
  60773. };
  60774. },{"../../components/colorbar/draw":56,"./end_plus":305,"./make_color_map":310}],298:[function(_dereq_,module,exports){
  60775. /**
  60776. * Copyright 2012-2019, Plotly, Inc.
  60777. * All rights reserved.
  60778. *
  60779. * This source code is licensed under the MIT license found in the
  60780. * LICENSE file in the root directory of this source tree.
  60781. */
  60782. 'use strict';
  60783. module.exports = {
  60784. // some constants to help with marching squares algorithm
  60785. // where does the path start for each index?
  60786. BOTTOMSTART: [1, 9, 13, 104, 713],
  60787. TOPSTART: [4, 6, 7, 104, 713],
  60788. LEFTSTART: [8, 12, 14, 208, 1114],
  60789. RIGHTSTART: [2, 3, 11, 208, 1114],
  60790. // which way [dx,dy] do we leave a given index?
  60791. // saddles are already disambiguated
  60792. NEWDELTA: [
  60793. null, [-1, 0], [0, -1], [-1, 0],
  60794. [1, 0], null, [0, -1], [-1, 0],
  60795. [0, 1], [0, 1], null, [0, 1],
  60796. [1, 0], [1, 0], [0, -1]
  60797. ],
  60798. // for each saddle, the first index here is used
  60799. // for dx||dy<0, the second for dx||dy>0
  60800. CHOOSESADDLE: {
  60801. 104: [4, 1],
  60802. 208: [2, 8],
  60803. 713: [7, 13],
  60804. 1114: [11, 14]
  60805. },
  60806. // after one index has been used for a saddle, which do we
  60807. // substitute to be used up later?
  60808. SADDLEREMAINDER: {1: 4, 2: 8, 4: 1, 7: 13, 8: 2, 11: 14, 13: 7, 14: 11},
  60809. // length of a contour, as a multiple of the plot area diagonal, per label
  60810. LABELDISTANCE: 2,
  60811. // number of contour levels after which we start increasing the number of
  60812. // labels we draw. Many contours means they will generally be close
  60813. // together, so it will be harder to follow a long way to find a label
  60814. LABELINCREASE: 10,
  60815. // minimum length of a contour line, as a multiple of the label length,
  60816. // at which we draw *any* labels
  60817. LABELMIN: 3,
  60818. // max number of labels to draw on a single contour path, no matter how long
  60819. LABELMAX: 10,
  60820. // constants for the label position cost function
  60821. LABELOPTIMIZER: {
  60822. // weight given to edge proximity
  60823. EDGECOST: 1,
  60824. // weight given to the angle off horizontal
  60825. ANGLECOST: 1,
  60826. // weight given to distance from already-placed labels
  60827. NEIGHBORCOST: 5,
  60828. // cost multiplier for labels on the same level
  60829. SAMELEVELFACTOR: 10,
  60830. // minimum distance (as a multiple of the label length)
  60831. // for labels on the same level
  60832. SAMELEVELDISTANCE: 5,
  60833. // maximum cost before we won't even place the label
  60834. MAXCOST: 100,
  60835. // number of evenly spaced points to look at in the first
  60836. // iteration of the search
  60837. INITIALSEARCHPOINTS: 10,
  60838. // number of binary search iterations after the initial wide search
  60839. ITERATIONS: 5
  60840. }
  60841. };
  60842. },{}],299:[function(_dereq_,module,exports){
  60843. /**
  60844. * Copyright 2012-2019, Plotly, Inc.
  60845. * All rights reserved.
  60846. *
  60847. * This source code is licensed under the MIT license found in the
  60848. * LICENSE file in the root directory of this source tree.
  60849. */
  60850. 'use strict';
  60851. var isNumeric = _dereq_('fast-isnumeric');
  60852. var handleLabelDefaults = _dereq_('./label_defaults');
  60853. var Color = _dereq_('../../components/color');
  60854. var addOpacity = Color.addOpacity;
  60855. var opacity = Color.opacity;
  60856. var filterOps = _dereq_('../../constants/filter_ops');
  60857. var CONSTRAINT_REDUCTION = filterOps.CONSTRAINT_REDUCTION;
  60858. var COMPARISON_OPS2 = filterOps.COMPARISON_OPS2;
  60859. module.exports = function handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor, opts) {
  60860. var contours = traceOut.contours;
  60861. var showLines, lineColor, fillColor;
  60862. var operation = coerce('contours.operation');
  60863. contours._operation = CONSTRAINT_REDUCTION[operation];
  60864. handleConstraintValueDefaults(coerce, contours);
  60865. if(operation === '=') {
  60866. showLines = contours.showlines = true;
  60867. }
  60868. else {
  60869. showLines = coerce('contours.showlines');
  60870. fillColor = coerce('fillcolor', addOpacity(
  60871. (traceIn.line || {}).color || defaultColor, 0.5
  60872. ));
  60873. }
  60874. if(showLines) {
  60875. var lineDfltColor = fillColor && opacity(fillColor) ?
  60876. addOpacity(traceOut.fillcolor, 1) :
  60877. defaultColor;
  60878. lineColor = coerce('line.color', lineDfltColor);
  60879. coerce('line.width', 2);
  60880. coerce('line.dash');
  60881. }
  60882. coerce('line.smoothing');
  60883. handleLabelDefaults(coerce, layout, lineColor, opts);
  60884. };
  60885. function handleConstraintValueDefaults(coerce, contours) {
  60886. var zvalue;
  60887. if(COMPARISON_OPS2.indexOf(contours.operation) === -1) {
  60888. // Requires an array of two numbers:
  60889. coerce('contours.value', [0, 1]);
  60890. if(!Array.isArray(contours.value)) {
  60891. if(isNumeric(contours.value)) {
  60892. zvalue = parseFloat(contours.value);
  60893. contours.value = [zvalue, zvalue + 1];
  60894. }
  60895. } else if(contours.value.length > 2) {
  60896. contours.value = contours.value.slice(2);
  60897. } else if(contours.length === 0) {
  60898. contours.value = [0, 1];
  60899. } else if(contours.length < 2) {
  60900. zvalue = parseFloat(contours.value[0]);
  60901. contours.value = [zvalue, zvalue + 1];
  60902. } else {
  60903. contours.value = [
  60904. parseFloat(contours.value[0]),
  60905. parseFloat(contours.value[1])
  60906. ];
  60907. }
  60908. } else {
  60909. // Requires a single scalar:
  60910. coerce('contours.value', 0);
  60911. if(!isNumeric(contours.value)) {
  60912. if(Array.isArray(contours.value)) {
  60913. contours.value = parseFloat(contours.value[0]);
  60914. } else {
  60915. contours.value = 0;
  60916. }
  60917. }
  60918. }
  60919. }
  60920. },{"../../components/color":51,"../../constants/filter_ops":147,"./label_defaults":309,"fast-isnumeric":18}],300:[function(_dereq_,module,exports){
  60921. /**
  60922. * Copyright 2012-2019, Plotly, Inc.
  60923. * All rights reserved.
  60924. *
  60925. * This source code is licensed under the MIT license found in the
  60926. * LICENSE file in the root directory of this source tree.
  60927. */
  60928. 'use strict';
  60929. var filterOps = _dereq_('../../constants/filter_ops');
  60930. var isNumeric = _dereq_('fast-isnumeric');
  60931. // This syntax conforms to the existing filter transform syntax, but we don't care
  60932. // about open vs. closed intervals for simply drawing contours constraints:
  60933. module.exports = {
  60934. '[]': makeRangeSettings('[]'),
  60935. '][': makeRangeSettings(']['),
  60936. '>': makeInequalitySettings('>'),
  60937. '<': makeInequalitySettings('<'),
  60938. '=': makeInequalitySettings('=')
  60939. };
  60940. // This does not in any way shape or form support calendars. It's adapted from
  60941. // transforms/filter.js.
  60942. function coerceValue(operation, value) {
  60943. var hasArrayValue = Array.isArray(value);
  60944. var coercedValue;
  60945. function coerce(value) {
  60946. return isNumeric(value) ? (+value) : null;
  60947. }
  60948. if(filterOps.COMPARISON_OPS2.indexOf(operation) !== -1) {
  60949. coercedValue = hasArrayValue ? coerce(value[0]) : coerce(value);
  60950. } else if(filterOps.INTERVAL_OPS.indexOf(operation) !== -1) {
  60951. coercedValue = hasArrayValue ?
  60952. [coerce(value[0]), coerce(value[1])] :
  60953. [coerce(value), coerce(value)];
  60954. } else if(filterOps.SET_OPS.indexOf(operation) !== -1) {
  60955. coercedValue = hasArrayValue ? value.map(coerce) : [coerce(value)];
  60956. }
  60957. return coercedValue;
  60958. }
  60959. // Returns a parabola scaled so that the min/max is either +/- 1 and zero at the two values
  60960. // provided. The data is mapped by this function when constructing intervals so that it's
  60961. // very easy to construct contours as normal.
  60962. function makeRangeSettings(operation) {
  60963. return function(value) {
  60964. value = coerceValue(operation, value);
  60965. // Ensure proper ordering:
  60966. var min = Math.min(value[0], value[1]);
  60967. var max = Math.max(value[0], value[1]);
  60968. return {
  60969. start: min,
  60970. end: max,
  60971. size: max - min
  60972. };
  60973. };
  60974. }
  60975. function makeInequalitySettings(operation) {
  60976. return function(value) {
  60977. value = coerceValue(operation, value);
  60978. return {
  60979. start: value,
  60980. end: Infinity,
  60981. size: Infinity
  60982. };
  60983. };
  60984. }
  60985. },{"../../constants/filter_ops":147,"fast-isnumeric":18}],301:[function(_dereq_,module,exports){
  60986. /**
  60987. * Copyright 2012-2019, Plotly, Inc.
  60988. * All rights reserved.
  60989. *
  60990. * This source code is licensed under the MIT license found in the
  60991. * LICENSE file in the root directory of this source tree.
  60992. */
  60993. 'use strict';
  60994. module.exports = function handleContourDefaults(traceIn, traceOut, coerce, coerce2) {
  60995. var contourStart = coerce2('contours.start');
  60996. var contourEnd = coerce2('contours.end');
  60997. var missingEnd = (contourStart === false) || (contourEnd === false);
  60998. // normally we only need size if autocontour is off. But contour.calc
  60999. // pushes its calculated contour size back to the input trace, so for
  61000. // things like restyle that can call supplyDefaults without calc
  61001. // after the initial draw, we can just reuse the previous calculation
  61002. var contourSize = coerce('contours.size');
  61003. var autoContour;
  61004. if(missingEnd) autoContour = traceOut.autocontour = true;
  61005. else autoContour = coerce('autocontour', false);
  61006. if(autoContour || !contourSize) coerce('ncontours');
  61007. };
  61008. },{}],302:[function(_dereq_,module,exports){
  61009. /**
  61010. * Copyright 2012-2019, Plotly, Inc.
  61011. * All rights reserved.
  61012. *
  61013. * This source code is licensed under the MIT license found in the
  61014. * LICENSE file in the root directory of this source tree.
  61015. */
  61016. 'use strict';
  61017. var Lib = _dereq_('../../lib');
  61018. // The contour extraction is great, except it totally fails for constraints because we
  61019. // need weird range loops and flipped contours instead of the usual format. This function
  61020. // does some weird manipulation of the extracted pathinfo data such that it magically
  61021. // draws contours correctly *as* constraints.
  61022. module.exports = function(pathinfo, operation) {
  61023. var i, pi0, pi1;
  61024. var op0 = function(arr) { return arr.reverse(); };
  61025. var op1 = function(arr) { return arr; };
  61026. switch(operation) {
  61027. case '=':
  61028. case '<':
  61029. return pathinfo;
  61030. case '>':
  61031. if(pathinfo.length !== 1) {
  61032. Lib.warn('Contour data invalid for the specified inequality operation.');
  61033. }
  61034. // In this case there should be exactly two contour levels in pathinfo. We
  61035. // simply concatenate the info into one pathinfo and flip all of the data
  61036. // in one. This will draw the contour as closed.
  61037. pi0 = pathinfo[0];
  61038. for(i = 0; i < pi0.edgepaths.length; i++) {
  61039. pi0.edgepaths[i] = op0(pi0.edgepaths[i]);
  61040. }
  61041. for(i = 0; i < pi0.paths.length; i++) {
  61042. pi0.paths[i] = op0(pi0.paths[i]);
  61043. }
  61044. return pathinfo;
  61045. case '][':
  61046. var tmp = op0;
  61047. op0 = op1;
  61048. op1 = tmp;
  61049. // It's a nice rule, except this definitely *is* what's intended here.
  61050. /* eslint-disable: no-fallthrough */
  61051. case '[]':
  61052. /* eslint-enable: no-fallthrough */
  61053. if(pathinfo.length !== 2) {
  61054. Lib.warn('Contour data invalid for the specified inequality range operation.');
  61055. }
  61056. // In this case there should be exactly two contour levels in pathinfo. We
  61057. // simply concatenate the info into one pathinfo and flip all of the data
  61058. // in one. This will draw the contour as closed.
  61059. pi0 = copyPathinfo(pathinfo[0]);
  61060. pi1 = copyPathinfo(pathinfo[1]);
  61061. for(i = 0; i < pi0.edgepaths.length; i++) {
  61062. pi0.edgepaths[i] = op0(pi0.edgepaths[i]);
  61063. }
  61064. for(i = 0; i < pi0.paths.length; i++) {
  61065. pi0.paths[i] = op0(pi0.paths[i]);
  61066. }
  61067. while(pi1.edgepaths.length) {
  61068. pi0.edgepaths.push(op1(pi1.edgepaths.shift()));
  61069. }
  61070. while(pi1.paths.length) {
  61071. pi0.paths.push(op1(pi1.paths.shift()));
  61072. }
  61073. return [pi0];
  61074. }
  61075. };
  61076. function copyPathinfo(pi) {
  61077. return Lib.extendFlat({}, pi, {
  61078. edgepaths: Lib.extendDeep([], pi.edgepaths),
  61079. paths: Lib.extendDeep([], pi.paths)
  61080. });
  61081. }
  61082. },{"../../lib":168}],303:[function(_dereq_,module,exports){
  61083. /**
  61084. * Copyright 2012-2019, Plotly, Inc.
  61085. * All rights reserved.
  61086. *
  61087. * This source code is licensed under the MIT license found in the
  61088. * LICENSE file in the root directory of this source tree.
  61089. */
  61090. 'use strict';
  61091. var Lib = _dereq_('../../lib');
  61092. var handleXYZDefaults = _dereq_('../heatmap/xyz_defaults');
  61093. var handleConstraintDefaults = _dereq_('./constraint_defaults');
  61094. var handleContoursDefaults = _dereq_('./contours_defaults');
  61095. var handleStyleDefaults = _dereq_('./style_defaults');
  61096. var attributes = _dereq_('./attributes');
  61097. module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
  61098. function coerce(attr, dflt) {
  61099. return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
  61100. }
  61101. function coerce2(attr) {
  61102. return Lib.coerce2(traceIn, traceOut, attributes, attr);
  61103. }
  61104. var len = handleXYZDefaults(traceIn, traceOut, coerce, layout);
  61105. if(!len) {
  61106. traceOut.visible = false;
  61107. return;
  61108. }
  61109. coerce('text');
  61110. var isConstraint = (coerce('contours.type') === 'constraint');
  61111. coerce('connectgaps', Lib.isArray1D(traceOut.z));
  61112. if(isConstraint) {
  61113. handleConstraintDefaults(traceIn, traceOut, coerce, layout, defaultColor);
  61114. }
  61115. else {
  61116. handleContoursDefaults(traceIn, traceOut, coerce, coerce2);
  61117. handleStyleDefaults(traceIn, traceOut, coerce, layout);
  61118. }
  61119. };
  61120. },{"../../lib":168,"../heatmap/xyz_defaults":330,"./attributes":294,"./constraint_defaults":299,"./contours_defaults":301,"./style_defaults":315}],304:[function(_dereq_,module,exports){
  61121. /**
  61122. * Copyright 2012-2019, Plotly, Inc.
  61123. * All rights reserved.
  61124. *
  61125. * This source code is licensed under the MIT license found in the
  61126. * LICENSE file in the root directory of this source tree.
  61127. */
  61128. 'use strict';
  61129. var Lib = _dereq_('../../lib');
  61130. var constraintMapping = _dereq_('./constraint_mapping');
  61131. var endPlus = _dereq_('./end_plus');
  61132. module.exports = function emptyPathinfo(contours, plotinfo, cd0) {
  61133. var contoursFinal = (contours.type === 'constraint') ?
  61134. constraintMapping[contours._operation](contours.value) :
  61135. contours;
  61136. var cs = contoursFinal.size;
  61137. var pathinfo = [];
  61138. var end = endPlus(contoursFinal);
  61139. var carpet = cd0.trace._carpetTrace;
  61140. var basePathinfo = carpet ? {
  61141. // store axes so we can convert to px
  61142. xaxis: carpet.aaxis,
  61143. yaxis: carpet.baxis,
  61144. // full data arrays to use for interpolation
  61145. x: cd0.a,
  61146. y: cd0.b
  61147. } : {
  61148. xaxis: plotinfo.xaxis,
  61149. yaxis: plotinfo.yaxis,
  61150. x: cd0.x,
  61151. y: cd0.y
  61152. };
  61153. for(var ci = contoursFinal.start; ci < end; ci += cs) {
  61154. pathinfo.push(Lib.extendFlat({
  61155. level: ci,
  61156. // all the cells with nontrivial marching index
  61157. crossings: {},
  61158. // starting points on the edges of the lattice for each contour
  61159. starts: [],
  61160. // all unclosed paths (may have less items than starts,
  61161. // if a path is closed by rounding)
  61162. edgepaths: [],
  61163. // all closed paths
  61164. paths: [],
  61165. z: cd0.z,
  61166. smoothing: cd0.trace.line.smoothing
  61167. }, basePathinfo));
  61168. if(pathinfo.length > 1000) {
  61169. Lib.warn('Too many contours, clipping at 1000', contours);
  61170. break;
  61171. }
  61172. }
  61173. return pathinfo;
  61174. };
  61175. },{"../../lib":168,"./constraint_mapping":300,"./end_plus":305}],305:[function(_dereq_,module,exports){
  61176. /**
  61177. * Copyright 2012-2019, Plotly, Inc.
  61178. * All rights reserved.
  61179. *
  61180. * This source code is licensed under the MIT license found in the
  61181. * LICENSE file in the root directory of this source tree.
  61182. */
  61183. 'use strict';
  61184. /*
  61185. * tiny helper to move the end of the contours a little to prevent
  61186. * losing the last contour to rounding errors
  61187. */
  61188. module.exports = function endPlus(contours) {
  61189. return contours.end + contours.size / 1e6;
  61190. };
  61191. },{}],306:[function(_dereq_,module,exports){
  61192. /**
  61193. * Copyright 2012-2019, Plotly, Inc.
  61194. * All rights reserved.
  61195. *
  61196. * This source code is licensed under the MIT license found in the
  61197. * LICENSE file in the root directory of this source tree.
  61198. */
  61199. 'use strict';
  61200. var Lib = _dereq_('../../lib');
  61201. var constants = _dereq_('./constants');
  61202. module.exports = function findAllPaths(pathinfo, xtol, ytol) {
  61203. var cnt,
  61204. startLoc,
  61205. i,
  61206. pi,
  61207. j;
  61208. // Default just passes these values through as they were before:
  61209. xtol = xtol || 0.01;
  61210. ytol = ytol || 0.01;
  61211. for(i = 0; i < pathinfo.length; i++) {
  61212. pi = pathinfo[i];
  61213. for(j = 0; j < pi.starts.length; j++) {
  61214. startLoc = pi.starts[j];
  61215. makePath(pi, startLoc, 'edge', xtol, ytol);
  61216. }
  61217. cnt = 0;
  61218. while(Object.keys(pi.crossings).length && cnt < 10000) {
  61219. cnt++;
  61220. startLoc = Object.keys(pi.crossings)[0].split(',').map(Number);
  61221. makePath(pi, startLoc, undefined, xtol, ytol);
  61222. }
  61223. if(cnt === 10000) Lib.log('Infinite loop in contour?');
  61224. }
  61225. };
  61226. function equalPts(pt1, pt2, xtol, ytol) {
  61227. return Math.abs(pt1[0] - pt2[0]) < xtol &&
  61228. Math.abs(pt1[1] - pt2[1]) < ytol;
  61229. }
  61230. // distance in index units - uses the 3rd and 4th items in points
  61231. function ptDist(pt1, pt2) {
  61232. var dx = pt1[2] - pt2[2];
  61233. var dy = pt1[3] - pt2[3];
  61234. return Math.sqrt(dx * dx + dy * dy);
  61235. }
  61236. function makePath(pi, loc, edgeflag, xtol, ytol) {
  61237. var startLocStr = loc.join(',');
  61238. var locStr = startLocStr;
  61239. var mi = pi.crossings[locStr];
  61240. var marchStep = startStep(mi, edgeflag, loc);
  61241. // start by going backward a half step and finding the crossing point
  61242. var pts = [getInterpPx(pi, loc, [-marchStep[0], -marchStep[1]])];
  61243. var startStepStr = marchStep.join(',');
  61244. var m = pi.z.length;
  61245. var n = pi.z[0].length;
  61246. var cnt;
  61247. // now follow the path
  61248. for(cnt = 0; cnt < 10000; cnt++) { // just to avoid infinite loops
  61249. if(mi > 20) {
  61250. mi = constants.CHOOSESADDLE[mi][(marchStep[0] || marchStep[1]) < 0 ? 0 : 1];
  61251. pi.crossings[locStr] = constants.SADDLEREMAINDER[mi];
  61252. }
  61253. else {
  61254. delete pi.crossings[locStr];
  61255. }
  61256. marchStep = constants.NEWDELTA[mi];
  61257. if(!marchStep) {
  61258. Lib.log('Found bad marching index:', mi, loc, pi.level);
  61259. break;
  61260. }
  61261. // find the crossing a half step forward, and then take the full step
  61262. pts.push(getInterpPx(pi, loc, marchStep));
  61263. loc[0] += marchStep[0];
  61264. loc[1] += marchStep[1];
  61265. // don't include the same point multiple times
  61266. if(equalPts(pts[pts.length - 1], pts[pts.length - 2], xtol, ytol)) pts.pop();
  61267. locStr = loc.join(',');
  61268. var atEdge = (marchStep[0] && (loc[0] < 0 || loc[0] > n - 2)) ||
  61269. (marchStep[1] && (loc[1] < 0 || loc[1] > m - 2));
  61270. var closedLoop = (locStr === startLocStr) && (marchStep.join(',') === startStepStr);
  61271. // have we completed a loop, or reached an edge?
  61272. if((closedLoop) || (edgeflag && atEdge)) break;
  61273. mi = pi.crossings[locStr];
  61274. }
  61275. if(cnt === 10000) {
  61276. Lib.log('Infinite loop in contour?');
  61277. }
  61278. var closedpath = equalPts(pts[0], pts[pts.length - 1], xtol, ytol);
  61279. var totaldist = 0;
  61280. var distThresholdFactor = 0.2 * pi.smoothing;
  61281. var alldists = [];
  61282. var cropstart = 0;
  61283. var distgroup, cnt2, cnt3, newpt, ptcnt, ptavg, thisdist,
  61284. i, j, edgepathi, edgepathj;
  61285. /*
  61286. * Check for points that are too close together (<1/5 the average dist
  61287. * *in grid index units* (important for log axes and nonuniform grids),
  61288. * less if less smoothed) and just take the center (or avg of center 2).
  61289. * This cuts down on funny behavior when a point is very close to a
  61290. * contour level.
  61291. */
  61292. for(cnt = 1; cnt < pts.length; cnt++) {
  61293. thisdist = ptDist(pts[cnt], pts[cnt - 1]);
  61294. totaldist += thisdist;
  61295. alldists.push(thisdist);
  61296. }
  61297. var distThreshold = totaldist / alldists.length * distThresholdFactor;
  61298. function getpt(i) { return pts[i % pts.length]; }
  61299. for(cnt = pts.length - 2; cnt >= cropstart; cnt--) {
  61300. distgroup = alldists[cnt];
  61301. if(distgroup < distThreshold) {
  61302. cnt3 = 0;
  61303. for(cnt2 = cnt - 1; cnt2 >= cropstart; cnt2--) {
  61304. if(distgroup + alldists[cnt2] < distThreshold) {
  61305. distgroup += alldists[cnt2];
  61306. }
  61307. else break;
  61308. }
  61309. // closed path with close points wrapping around the boundary?
  61310. if(closedpath && cnt === pts.length - 2) {
  61311. for(cnt3 = 0; cnt3 < cnt2; cnt3++) {
  61312. if(distgroup + alldists[cnt3] < distThreshold) {
  61313. distgroup += alldists[cnt3];
  61314. }
  61315. else break;
  61316. }
  61317. }
  61318. ptcnt = cnt - cnt2 + cnt3 + 1;
  61319. ptavg = Math.floor((cnt + cnt2 + cnt3 + 2) / 2);
  61320. // either endpoint included: keep the endpoint
  61321. if(!closedpath && cnt === pts.length - 2) newpt = pts[pts.length - 1];
  61322. else if(!closedpath && cnt2 === -1) newpt = pts[0];
  61323. // odd # of points - just take the central one
  61324. else if(ptcnt % 2) newpt = getpt(ptavg);
  61325. // even # of pts - average central two
  61326. else {
  61327. newpt = [(getpt(ptavg)[0] + getpt(ptavg + 1)[0]) / 2,
  61328. (getpt(ptavg)[1] + getpt(ptavg + 1)[1]) / 2];
  61329. }
  61330. pts.splice(cnt2 + 1, cnt - cnt2 + 1, newpt);
  61331. cnt = cnt2 + 1;
  61332. if(cnt3) cropstart = cnt3;
  61333. if(closedpath) {
  61334. if(cnt === pts.length - 2) pts[cnt3] = pts[pts.length - 1];
  61335. else if(cnt === 0) pts[pts.length - 1] = pts[0];
  61336. }
  61337. }
  61338. }
  61339. pts.splice(0, cropstart);
  61340. // done with the index parts - remove them so path generation works right
  61341. // because it depends on only having [xpx, ypx]
  61342. for(cnt = 0; cnt < pts.length; cnt++) pts[cnt].length = 2;
  61343. // don't return single-point paths (ie all points were the same
  61344. // so they got deleted?)
  61345. if(pts.length < 2) return;
  61346. else if(closedpath) {
  61347. pts.pop();
  61348. pi.paths.push(pts);
  61349. }
  61350. else {
  61351. if(!edgeflag) {
  61352. Lib.log('Unclosed interior contour?',
  61353. pi.level, startLocStr, pts.join('L'));
  61354. }
  61355. // edge path - does it start where an existing edge path ends, or vice versa?
  61356. var merged = false;
  61357. for(i = 0; i < pi.edgepaths.length; i++) {
  61358. edgepathi = pi.edgepaths[i];
  61359. if(!merged && equalPts(edgepathi[0], pts[pts.length - 1], xtol, ytol)) {
  61360. pts.pop();
  61361. merged = true;
  61362. // now does it ALSO meet the end of another (or the same) path?
  61363. var doublemerged = false;
  61364. for(j = 0; j < pi.edgepaths.length; j++) {
  61365. edgepathj = pi.edgepaths[j];
  61366. if(equalPts(edgepathj[edgepathj.length - 1], pts[0], xtol, ytol)) {
  61367. doublemerged = true;
  61368. pts.shift();
  61369. pi.edgepaths.splice(i, 1);
  61370. if(j === i) {
  61371. // the path is now closed
  61372. pi.paths.push(pts.concat(edgepathj));
  61373. }
  61374. else {
  61375. if(j > i) j--;
  61376. pi.edgepaths[j] = edgepathj.concat(pts, edgepathi);
  61377. }
  61378. break;
  61379. }
  61380. }
  61381. if(!doublemerged) {
  61382. pi.edgepaths[i] = pts.concat(edgepathi);
  61383. }
  61384. }
  61385. }
  61386. for(i = 0; i < pi.edgepaths.length; i++) {
  61387. if(merged) break;
  61388. edgepathi = pi.edgepaths[i];
  61389. if(equalPts(edgepathi[edgepathi.length - 1], pts[0], xtol, ytol)) {
  61390. pts.shift();
  61391. pi.edgepaths[i] = edgepathi.concat(pts);
  61392. merged = true;
  61393. }
  61394. }
  61395. if(!merged) pi.edgepaths.push(pts);
  61396. }
  61397. }
  61398. // special function to get the marching step of the
  61399. // first point in the path (leading to loc)
  61400. function startStep(mi, edgeflag, loc) {
  61401. var dx = 0;
  61402. var dy = 0;
  61403. if(mi > 20 && edgeflag) {
  61404. // these saddles start at +/- x
  61405. if(mi === 208 || mi === 1114) {
  61406. // if we're starting at the left side, we must be going right
  61407. dx = loc[0] === 0 ? 1 : -1;
  61408. }
  61409. else {
  61410. // if we're starting at the bottom, we must be going up
  61411. dy = loc[1] === 0 ? 1 : -1;
  61412. }
  61413. }
  61414. else if(constants.BOTTOMSTART.indexOf(mi) !== -1) dy = 1;
  61415. else if(constants.LEFTSTART.indexOf(mi) !== -1) dx = 1;
  61416. else if(constants.TOPSTART.indexOf(mi) !== -1) dy = -1;
  61417. else dx = -1;
  61418. return [dx, dy];
  61419. }
  61420. /*
  61421. * Find the pixel coordinates of a particular crossing
  61422. *
  61423. * @param {object} pi: the pathinfo object at this level
  61424. * @param {array} loc: the grid index [x, y] of the crossing
  61425. * @param {array} step: the direction [dx, dy] we're moving on the grid
  61426. *
  61427. * @return {array} [xpx, ypx, xi, yi]: the first two are the pixel location,
  61428. * the next two are the interpolated grid indices, which we use for
  61429. * distance calculations to delete points that are too close together.
  61430. * This is important when the grid is nonuniform (and most dramatically when
  61431. * we're on log axes and include invalid (0 or negative) values.
  61432. * It's crucial to delete these extra two before turning an array of these
  61433. * points into a path, because those routines require length-2 points.
  61434. */
  61435. function getInterpPx(pi, loc, step) {
  61436. var locx = loc[0] + Math.max(step[0], 0);
  61437. var locy = loc[1] + Math.max(step[1], 0);
  61438. var zxy = pi.z[locy][locx];
  61439. var xa = pi.xaxis;
  61440. var ya = pi.yaxis;
  61441. if(step[1]) {
  61442. var dx = (pi.level - zxy) / (pi.z[locy][locx + 1] - zxy);
  61443. return [xa.c2p((1 - dx) * pi.x[locx] + dx * pi.x[locx + 1], true),
  61444. ya.c2p(pi.y[locy], true),
  61445. locx + dx, locy];
  61446. }
  61447. else {
  61448. var dy = (pi.level - zxy) / (pi.z[locy + 1][locx] - zxy);
  61449. return [xa.c2p(pi.x[locx], true),
  61450. ya.c2p((1 - dy) * pi.y[locy] + dy * pi.y[locy + 1], true),
  61451. locx, locy + dy];
  61452. }
  61453. }
  61454. },{"../../lib":168,"./constants":298}],307:[function(_dereq_,module,exports){
  61455. /**
  61456. * Copyright 2012-2019, Plotly, Inc.
  61457. * All rights reserved.
  61458. *
  61459. * This source code is licensed under the MIT license found in the
  61460. * LICENSE file in the root directory of this source tree.
  61461. */
  61462. 'use strict';
  61463. var Color = _dereq_('../../components/color');
  61464. var heatmapHoverPoints = _dereq_('../heatmap/hover');
  61465. module.exports = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) {
  61466. var hoverData = heatmapHoverPoints(pointData, xval, yval, hovermode, hoverLayer, true);
  61467. if(hoverData) {
  61468. hoverData.forEach(function(hoverPt) {
  61469. var trace = hoverPt.trace;
  61470. if(trace.contours.type === 'constraint') {
  61471. if(trace.fillcolor && Color.opacity(trace.fillcolor)) {
  61472. hoverPt.color = Color.addOpacity(trace.fillcolor, 1);
  61473. }
  61474. else if(trace.contours.showlines && Color.opacity(trace.line.color)) {
  61475. hoverPt.color = Color.addOpacity(trace.line.color, 1);
  61476. }
  61477. }
  61478. });
  61479. }
  61480. return hoverData;
  61481. };
  61482. },{"../../components/color":51,"../heatmap/hover":323}],308:[function(_dereq_,module,exports){
  61483. /**
  61484. * Copyright 2012-2019, Plotly, Inc.
  61485. * All rights reserved.
  61486. *
  61487. * This source code is licensed under the MIT license found in the
  61488. * LICENSE file in the root directory of this source tree.
  61489. */
  61490. 'use strict';
  61491. var Contour = {};
  61492. Contour.attributes = _dereq_('./attributes');
  61493. Contour.supplyDefaults = _dereq_('./defaults');
  61494. Contour.calc = _dereq_('./calc');
  61495. Contour.plot = _dereq_('./plot').plot;
  61496. Contour.style = _dereq_('./style');
  61497. Contour.colorbar = _dereq_('./colorbar');
  61498. Contour.hoverPoints = _dereq_('./hover');
  61499. Contour.moduleType = 'trace';
  61500. Contour.name = 'contour';
  61501. Contour.basePlotModule = _dereq_('../../plots/cartesian');
  61502. Contour.categories = ['cartesian', 'svg', '2dMap', 'contour', 'showLegend'];
  61503. Contour.meta = {
  61504. };
  61505. module.exports = Contour;
  61506. },{"../../plots/cartesian":224,"./attributes":294,"./calc":295,"./colorbar":297,"./defaults":303,"./hover":307,"./plot":312,"./style":314}],309:[function(_dereq_,module,exports){
  61507. /**
  61508. * Copyright 2012-2019, Plotly, Inc.
  61509. * All rights reserved.
  61510. *
  61511. * This source code is licensed under the MIT license found in the
  61512. * LICENSE file in the root directory of this source tree.
  61513. */
  61514. 'use strict';
  61515. var Lib = _dereq_('../../lib');
  61516. module.exports = function handleLabelDefaults(coerce, layout, lineColor, opts) {
  61517. if(!opts) opts = {};
  61518. var showLabels = coerce('contours.showlabels');
  61519. if(showLabels) {
  61520. var globalFont = layout.font;
  61521. Lib.coerceFont(coerce, 'contours.labelfont', {
  61522. family: globalFont.family,
  61523. size: globalFont.size,
  61524. color: lineColor
  61525. });
  61526. coerce('contours.labelformat');
  61527. }
  61528. if(opts.hasHover !== false) coerce('zhoverformat');
  61529. };
  61530. },{"../../lib":168}],310:[function(_dereq_,module,exports){
  61531. /**
  61532. * Copyright 2012-2019, Plotly, Inc.
  61533. * All rights reserved.
  61534. *
  61535. * This source code is licensed under the MIT license found in the
  61536. * LICENSE file in the root directory of this source tree.
  61537. */
  61538. 'use strict';
  61539. var d3 = _dereq_('d3');
  61540. var Colorscale = _dereq_('../../components/colorscale');
  61541. var endPlus = _dereq_('./end_plus');
  61542. module.exports = function makeColorMap(trace) {
  61543. var contours = trace.contours;
  61544. var start = contours.start;
  61545. var end = endPlus(contours);
  61546. var cs = contours.size || 1;
  61547. var nc = Math.floor((end - start) / cs) + 1;
  61548. var extra = contours.coloring === 'lines' ? 0 : 1;
  61549. if(!isFinite(cs)) {
  61550. cs = 1;
  61551. nc = 1;
  61552. }
  61553. var scl = trace.reversescale ?
  61554. Colorscale.flipScale(trace.colorscale) :
  61555. trace.colorscale;
  61556. var len = scl.length;
  61557. var domain = new Array(len);
  61558. var range = new Array(len);
  61559. var si, i;
  61560. if(contours.coloring === 'heatmap') {
  61561. if(trace.zauto && trace.autocontour === false) {
  61562. trace.zmin = start - cs / 2;
  61563. trace.zmax = trace.zmin + nc * cs;
  61564. }
  61565. for(i = 0; i < len; i++) {
  61566. si = scl[i];
  61567. domain[i] = si[0] * (trace.zmax - trace.zmin) + trace.zmin;
  61568. range[i] = si[1];
  61569. }
  61570. // do the contours extend beyond the colorscale?
  61571. // if so, extend the colorscale with constants
  61572. var zRange = d3.extent([
  61573. trace.zmin,
  61574. trace.zmax,
  61575. contours.start,
  61576. contours.start + cs * (nc - 1)
  61577. ]);
  61578. var zmin = zRange[trace.zmin < trace.zmax ? 0 : 1];
  61579. var zmax = zRange[trace.zmin < trace.zmax ? 1 : 0];
  61580. if(zmin !== trace.zmin) {
  61581. domain.splice(0, 0, zmin);
  61582. range.splice(0, 0, Range[0]);
  61583. }
  61584. if(zmax !== trace.zmax) {
  61585. domain.push(zmax);
  61586. range.push(range[range.length - 1]);
  61587. }
  61588. }
  61589. else {
  61590. for(i = 0; i < len; i++) {
  61591. si = scl[i];
  61592. domain[i] = (si[0] * (nc + extra - 1) - (extra / 2)) * cs + start;
  61593. range[i] = si[1];
  61594. }
  61595. }
  61596. return Colorscale.makeColorScaleFunc({
  61597. domain: domain,
  61598. range: range,
  61599. }, {
  61600. noNumericCheck: true
  61601. });
  61602. };
  61603. },{"../../components/colorscale":63,"./end_plus":305,"d3":16}],311:[function(_dereq_,module,exports){
  61604. /**
  61605. * Copyright 2012-2019, Plotly, Inc.
  61606. * All rights reserved.
  61607. *
  61608. * This source code is licensed under the MIT license found in the
  61609. * LICENSE file in the root directory of this source tree.
  61610. */
  61611. 'use strict';
  61612. var constants = _dereq_('./constants');
  61613. // Calculate all the marching indices, for ALL levels at once.
  61614. // since we want to be exhaustive we'll check for contour crossings
  61615. // at every intersection, rather than just following a path
  61616. // TODO: shorten the inner loop to only the relevant levels
  61617. module.exports = function makeCrossings(pathinfo) {
  61618. var z = pathinfo[0].z;
  61619. var m = z.length;
  61620. var n = z[0].length; // we already made sure z isn't ragged in interp2d
  61621. var twoWide = m === 2 || n === 2;
  61622. var xi;
  61623. var yi;
  61624. var startIndices;
  61625. var ystartIndices;
  61626. var label;
  61627. var corners;
  61628. var mi;
  61629. var pi;
  61630. var i;
  61631. for(yi = 0; yi < m - 1; yi++) {
  61632. ystartIndices = [];
  61633. if(yi === 0) ystartIndices = ystartIndices.concat(constants.BOTTOMSTART);
  61634. if(yi === m - 2) ystartIndices = ystartIndices.concat(constants.TOPSTART);
  61635. for(xi = 0; xi < n - 1; xi++) {
  61636. startIndices = ystartIndices.slice();
  61637. if(xi === 0) startIndices = startIndices.concat(constants.LEFTSTART);
  61638. if(xi === n - 2) startIndices = startIndices.concat(constants.RIGHTSTART);
  61639. label = xi + ',' + yi;
  61640. corners = [[z[yi][xi], z[yi][xi + 1]],
  61641. [z[yi + 1][xi], z[yi + 1][xi + 1]]];
  61642. for(i = 0; i < pathinfo.length; i++) {
  61643. pi = pathinfo[i];
  61644. mi = getMarchingIndex(pi.level, corners);
  61645. if(!mi) continue;
  61646. pi.crossings[label] = mi;
  61647. if(startIndices.indexOf(mi) !== -1) {
  61648. pi.starts.push([xi, yi]);
  61649. if(twoWide && startIndices.indexOf(mi,
  61650. startIndices.indexOf(mi) + 1) !== -1) {
  61651. // the same square has starts from opposite sides
  61652. // it's not possible to have starts on opposite edges
  61653. // of a corner, only a start and an end...
  61654. // but if the array is only two points wide (either way)
  61655. // you can have starts on opposite sides.
  61656. pi.starts.push([xi, yi]);
  61657. }
  61658. }
  61659. }
  61660. }
  61661. }
  61662. };
  61663. // modified marching squares algorithm,
  61664. // so we disambiguate the saddle points from the start
  61665. // and we ignore the cases with no crossings
  61666. // the index I'm using is based on:
  61667. // http://en.wikipedia.org/wiki/Marching_squares
  61668. // except that the saddles bifurcate and I represent them
  61669. // as the decimal combination of the two appropriate
  61670. // non-saddle indices
  61671. function getMarchingIndex(val, corners) {
  61672. var mi = (corners[0][0] > val ? 0 : 1) +
  61673. (corners[0][1] > val ? 0 : 2) +
  61674. (corners[1][1] > val ? 0 : 4) +
  61675. (corners[1][0] > val ? 0 : 8);
  61676. if(mi === 5 || mi === 10) {
  61677. var avg = (corners[0][0] + corners[0][1] +
  61678. corners[1][0] + corners[1][1]) / 4;
  61679. // two peaks with a big valley
  61680. if(val > avg) return (mi === 5) ? 713 : 1114;
  61681. // two valleys with a big ridge
  61682. return (mi === 5) ? 104 : 208;
  61683. }
  61684. return (mi === 15) ? 0 : mi;
  61685. }
  61686. },{"./constants":298}],312:[function(_dereq_,module,exports){
  61687. /**
  61688. * Copyright 2012-2019, Plotly, Inc.
  61689. * All rights reserved.
  61690. *
  61691. * This source code is licensed under the MIT license found in the
  61692. * LICENSE file in the root directory of this source tree.
  61693. */
  61694. 'use strict';
  61695. var d3 = _dereq_('d3');
  61696. var Lib = _dereq_('../../lib');
  61697. var Drawing = _dereq_('../../components/drawing');
  61698. var svgTextUtils = _dereq_('../../lib/svg_text_utils');
  61699. var Axes = _dereq_('../../plots/cartesian/axes');
  61700. var setConvert = _dereq_('../../plots/cartesian/set_convert');
  61701. var heatmapPlot = _dereq_('../heatmap/plot');
  61702. var makeCrossings = _dereq_('./make_crossings');
  61703. var findAllPaths = _dereq_('./find_all_paths');
  61704. var emptyPathinfo = _dereq_('./empty_pathinfo');
  61705. var convertToConstraints = _dereq_('./convert_to_constraints');
  61706. var closeBoundaries = _dereq_('./close_boundaries');
  61707. var constants = _dereq_('./constants');
  61708. var costConstants = constants.LABELOPTIMIZER;
  61709. exports.plot = function plot(gd, plotinfo, cdcontours, contourLayer) {
  61710. var xa = plotinfo.xaxis;
  61711. var ya = plotinfo.yaxis;
  61712. Lib.makeTraceGroups(contourLayer, cdcontours, 'contour').each(function(cd) {
  61713. var plotGroup = d3.select(this);
  61714. var cd0 = cd[0];
  61715. var trace = cd0.trace;
  61716. var x = cd0.x;
  61717. var y = cd0.y;
  61718. var contours = trace.contours;
  61719. var pathinfo = emptyPathinfo(contours, plotinfo, cd0);
  61720. // use a heatmap to fill - draw it behind the lines
  61721. var heatmapColoringLayer = Lib.ensureSingle(plotGroup, 'g', 'heatmapcoloring');
  61722. var cdheatmaps = [];
  61723. if(contours.coloring === 'heatmap') {
  61724. if(trace.zauto && (trace.autocontour === false)) {
  61725. trace._input.zmin = trace.zmin =
  61726. contours.start - contours.size / 2;
  61727. trace._input.zmax = trace.zmax =
  61728. trace.zmin + pathinfo.length * contours.size;
  61729. }
  61730. cdheatmaps = [cd];
  61731. }
  61732. heatmapPlot(gd, plotinfo, cdheatmaps, heatmapColoringLayer);
  61733. makeCrossings(pathinfo);
  61734. findAllPaths(pathinfo);
  61735. var leftedge = xa.c2p(x[0], true);
  61736. var rightedge = xa.c2p(x[x.length - 1], true);
  61737. var bottomedge = ya.c2p(y[0], true);
  61738. var topedge = ya.c2p(y[y.length - 1], true);
  61739. var perimeter = [
  61740. [leftedge, topedge],
  61741. [rightedge, topedge],
  61742. [rightedge, bottomedge],
  61743. [leftedge, bottomedge]
  61744. ];
  61745. var fillPathinfo = pathinfo;
  61746. if(contours.type === 'constraint') {
  61747. fillPathinfo = convertToConstraints(pathinfo, contours._operation);
  61748. closeBoundaries(fillPathinfo, contours._operation, perimeter, trace);
  61749. }
  61750. // draw everything
  61751. makeBackground(plotGroup, perimeter, contours);
  61752. makeFills(plotGroup, fillPathinfo, perimeter, contours);
  61753. makeLinesAndLabels(plotGroup, pathinfo, gd, cd0, contours, perimeter);
  61754. clipGaps(plotGroup, plotinfo, gd, cd0, perimeter);
  61755. });
  61756. };
  61757. function makeBackground(plotgroup, perimeter, contours) {
  61758. var bggroup = Lib.ensureSingle(plotgroup, 'g', 'contourbg');
  61759. var bgfill = bggroup.selectAll('path')
  61760. .data(contours.coloring === 'fill' ? [0] : []);
  61761. bgfill.enter().append('path');
  61762. bgfill.exit().remove();
  61763. bgfill
  61764. .attr('d', 'M' + perimeter.join('L') + 'Z')
  61765. .style('stroke', 'none');
  61766. }
  61767. function makeFills(plotgroup, pathinfo, perimeter, contours) {
  61768. var fillgroup = Lib.ensureSingle(plotgroup, 'g', 'contourfill');
  61769. var fillitems = fillgroup.selectAll('path')
  61770. .data(contours.coloring === 'fill' || (contours.type === 'constraint' && contours._operation !== '=') ? pathinfo : []);
  61771. fillitems.enter().append('path');
  61772. fillitems.exit().remove();
  61773. fillitems.each(function(pi) {
  61774. // join all paths for this level together into a single path
  61775. // first follow clockwise around the perimeter to close any open paths
  61776. // if the whole perimeter is above this level, start with a path
  61777. // enclosing the whole thing. With all that, the parity should mean
  61778. // that we always fill everything above the contour, nothing below
  61779. var fullpath = joinAllPaths(pi, perimeter);
  61780. if(!fullpath) d3.select(this).remove();
  61781. else d3.select(this).attr('d', fullpath).style('stroke', 'none');
  61782. });
  61783. }
  61784. function initFullPath(pi, perimeter) {
  61785. var prefixBoundary = pi.prefixBoundary;
  61786. if(prefixBoundary === undefined) {
  61787. var edgeVal2 = Math.min(pi.z[0][0], pi.z[0][1]);
  61788. prefixBoundary = (!pi.edgepaths.length && edgeVal2 > pi.level);
  61789. }
  61790. if(prefixBoundary) {
  61791. // TODO: why does ^^ not work for constraints?
  61792. // pi.prefixBoundary gets set by closeBoundaries
  61793. return 'M' + perimeter.join('L') + 'Z';
  61794. }
  61795. return '';
  61796. }
  61797. function joinAllPaths(pi, perimeter) {
  61798. var fullpath = initFullPath(pi, perimeter);
  61799. var i = 0;
  61800. var startsleft = pi.edgepaths.map(function(v, i) { return i; });
  61801. var newloop = true;
  61802. var endpt;
  61803. var newendpt;
  61804. var cnt;
  61805. var nexti;
  61806. var possiblei;
  61807. var addpath;
  61808. function istop(pt) { return Math.abs(pt[1] - perimeter[0][1]) < 0.01; }
  61809. function isbottom(pt) { return Math.abs(pt[1] - perimeter[2][1]) < 0.01; }
  61810. function isleft(pt) { return Math.abs(pt[0] - perimeter[0][0]) < 0.01; }
  61811. function isright(pt) { return Math.abs(pt[0] - perimeter[2][0]) < 0.01; }
  61812. while(startsleft.length) {
  61813. addpath = Drawing.smoothopen(pi.edgepaths[i], pi.smoothing);
  61814. fullpath += newloop ? addpath : addpath.replace(/^M/, 'L');
  61815. startsleft.splice(startsleft.indexOf(i), 1);
  61816. endpt = pi.edgepaths[i][pi.edgepaths[i].length - 1];
  61817. nexti = -1;
  61818. // now loop through sides, moving our endpoint until we find a new start
  61819. for(cnt = 0; cnt < 4; cnt++) { // just to prevent infinite loops
  61820. if(!endpt) {
  61821. Lib.log('Missing end?', i, pi);
  61822. break;
  61823. }
  61824. if(istop(endpt) && !isright(endpt)) newendpt = perimeter[1]; // right top
  61825. else if(isleft(endpt)) newendpt = perimeter[0]; // left top
  61826. else if(isbottom(endpt)) newendpt = perimeter[3]; // right bottom
  61827. else if(isright(endpt)) newendpt = perimeter[2]; // left bottom
  61828. for(possiblei = 0; possiblei < pi.edgepaths.length; possiblei++) {
  61829. var ptNew = pi.edgepaths[possiblei][0];
  61830. // is ptNew on the (horz. or vert.) segment from endpt to newendpt?
  61831. if(Math.abs(endpt[0] - newendpt[0]) < 0.01) {
  61832. if(Math.abs(endpt[0] - ptNew[0]) < 0.01 &&
  61833. (ptNew[1] - endpt[1]) * (newendpt[1] - ptNew[1]) >= 0) {
  61834. newendpt = ptNew;
  61835. nexti = possiblei;
  61836. }
  61837. }
  61838. else if(Math.abs(endpt[1] - newendpt[1]) < 0.01) {
  61839. if(Math.abs(endpt[1] - ptNew[1]) < 0.01 &&
  61840. (ptNew[0] - endpt[0]) * (newendpt[0] - ptNew[0]) >= 0) {
  61841. newendpt = ptNew;
  61842. nexti = possiblei;
  61843. }
  61844. }
  61845. else {
  61846. Lib.log('endpt to newendpt is not vert. or horz.',
  61847. endpt, newendpt, ptNew);
  61848. }
  61849. }
  61850. endpt = newendpt;
  61851. if(nexti >= 0) break;
  61852. fullpath += 'L' + newendpt;
  61853. }
  61854. if(nexti === pi.edgepaths.length) {
  61855. Lib.log('unclosed perimeter path');
  61856. break;
  61857. }
  61858. i = nexti;
  61859. // if we closed back on a loop we already included,
  61860. // close it and start a new loop
  61861. newloop = (startsleft.indexOf(i) === -1);
  61862. if(newloop) {
  61863. i = startsleft[0];
  61864. fullpath += 'Z';
  61865. }
  61866. }
  61867. // finally add the interior paths
  61868. for(i = 0; i < pi.paths.length; i++) {
  61869. fullpath += Drawing.smoothclosed(pi.paths[i], pi.smoothing);
  61870. }
  61871. return fullpath;
  61872. }
  61873. function makeLinesAndLabels(plotgroup, pathinfo, gd, cd0, contours, perimeter) {
  61874. var lineContainer = Lib.ensureSingle(plotgroup, 'g', 'contourlines');
  61875. var showLines = contours.showlines !== false;
  61876. var showLabels = contours.showlabels;
  61877. var clipLinesForLabels = showLines && showLabels;
  61878. // Even if we're not going to show lines, we need to create them
  61879. // if we're showing labels, because the fill paths include the perimeter
  61880. // so can't be used to position the labels correctly.
  61881. // In this case we'll remove the lines after making the labels.
  61882. var linegroup = exports.createLines(lineContainer, showLines || showLabels, pathinfo);
  61883. var lineClip = exports.createLineClip(lineContainer, clipLinesForLabels, gd, cd0.trace.uid);
  61884. var labelGroup = plotgroup.selectAll('g.contourlabels')
  61885. .data(showLabels ? [0] : []);
  61886. labelGroup.exit().remove();
  61887. labelGroup.enter().append('g')
  61888. .classed('contourlabels', true);
  61889. if(showLabels) {
  61890. var labelClipPathData = [];
  61891. var labelData = [];
  61892. // invalidate the getTextLocation cache in case paths changed
  61893. Lib.clearLocationCache();
  61894. var contourFormat = exports.labelFormatter(contours, cd0.t.cb, gd._fullLayout);
  61895. var dummyText = Drawing.tester.append('text')
  61896. .attr('data-notex', 1)
  61897. .call(Drawing.font, contours.labelfont);
  61898. var xa = pathinfo[0].xaxis;
  61899. var ya = pathinfo[0].yaxis;
  61900. var xLen = xa._length;
  61901. var yLen = ya._length;
  61902. var xRng = xa.range;
  61903. var yRng = ya.range;
  61904. var x0 = Math.max(perimeter[0][0], 0);
  61905. var x1 = Math.min(perimeter[2][0], xLen);
  61906. var y0 = Math.max(perimeter[0][1], 0);
  61907. var y1 = Math.min(perimeter[2][1], yLen);
  61908. // visible bounds of the contour trace (and the midpoints, to
  61909. // help with cost calculations)
  61910. var bounds = {};
  61911. if(xRng[0] < xRng[1]) {
  61912. bounds.left = x0;
  61913. bounds.right = x1;
  61914. } else {
  61915. bounds.left = x1;
  61916. bounds.right = x0;
  61917. }
  61918. if(yRng[0] < yRng[1]) {
  61919. bounds.top = y0;
  61920. bounds.bottom = y1;
  61921. } else {
  61922. bounds.top = y1;
  61923. bounds.bottom = y0;
  61924. }
  61925. bounds.middle = (bounds.top + bounds.bottom) / 2;
  61926. bounds.center = (bounds.left + bounds.right) / 2;
  61927. labelClipPathData.push([
  61928. [bounds.left, bounds.top],
  61929. [bounds.right, bounds.top],
  61930. [bounds.right, bounds.bottom],
  61931. [bounds.left, bounds.bottom]
  61932. ]);
  61933. var plotDiagonal = Math.sqrt(xLen * xLen + yLen * yLen);
  61934. // the path length to use to scale the number of labels to draw:
  61935. var normLength = constants.LABELDISTANCE * plotDiagonal /
  61936. Math.max(1, pathinfo.length / constants.LABELINCREASE);
  61937. linegroup.each(function(d) {
  61938. var textOpts = exports.calcTextOpts(d.level, contourFormat, dummyText, gd);
  61939. d3.select(this).selectAll('path').each(function() {
  61940. var path = this;
  61941. var pathBounds = Lib.getVisibleSegment(path, bounds, textOpts.height / 2);
  61942. if(!pathBounds) return;
  61943. if(pathBounds.len < (textOpts.width + textOpts.height) * constants.LABELMIN) return;
  61944. var maxLabels = Math.min(Math.ceil(pathBounds.len / normLength),
  61945. constants.LABELMAX);
  61946. for(var i = 0; i < maxLabels; i++) {
  61947. var loc = exports.findBestTextLocation(path, pathBounds, textOpts,
  61948. labelData, bounds);
  61949. if(!loc) break;
  61950. exports.addLabelData(loc, textOpts, labelData, labelClipPathData);
  61951. }
  61952. });
  61953. });
  61954. dummyText.remove();
  61955. exports.drawLabels(labelGroup, labelData, gd, lineClip,
  61956. clipLinesForLabels ? labelClipPathData : null);
  61957. }
  61958. if(showLabels && !showLines) linegroup.remove();
  61959. }
  61960. exports.createLines = function(lineContainer, makeLines, pathinfo) {
  61961. var smoothing = pathinfo[0].smoothing;
  61962. var linegroup = lineContainer.selectAll('g.contourlevel')
  61963. .data(makeLines ? pathinfo : []);
  61964. linegroup.exit().remove();
  61965. linegroup.enter().append('g')
  61966. .classed('contourlevel', true);
  61967. if(makeLines) {
  61968. // pedgepaths / ppaths are used by contourcarpet, for the paths transformed from a/b to x/y
  61969. // edgepaths / paths are used by contour since it's in x/y from the start
  61970. var opencontourlines = linegroup.selectAll('path.openline')
  61971. .data(function(d) { return d.pedgepaths || d.edgepaths; });
  61972. opencontourlines.exit().remove();
  61973. opencontourlines.enter().append('path')
  61974. .classed('openline', true);
  61975. opencontourlines
  61976. .attr('d', function(d) {
  61977. return Drawing.smoothopen(d, smoothing);
  61978. })
  61979. .style('stroke-miterlimit', 1)
  61980. .style('vector-effect', 'non-scaling-stroke');
  61981. var closedcontourlines = linegroup.selectAll('path.closedline')
  61982. .data(function(d) { return d.ppaths || d.paths; });
  61983. closedcontourlines.exit().remove();
  61984. closedcontourlines.enter().append('path')
  61985. .classed('closedline', true);
  61986. closedcontourlines
  61987. .attr('d', function(d) {
  61988. return Drawing.smoothclosed(d, smoothing);
  61989. })
  61990. .style('stroke-miterlimit', 1)
  61991. .style('vector-effect', 'non-scaling-stroke');
  61992. }
  61993. return linegroup;
  61994. };
  61995. exports.createLineClip = function(lineContainer, clipLinesForLabels, gd, uid) {
  61996. var clips = gd._fullLayout._clips;
  61997. var clipId = clipLinesForLabels ? ('clipline' + uid) : null;
  61998. var lineClip = clips.selectAll('#' + clipId)
  61999. .data(clipLinesForLabels ? [0] : []);
  62000. lineClip.exit().remove();
  62001. lineClip.enter().append('clipPath')
  62002. .classed('contourlineclip', true)
  62003. .attr('id', clipId);
  62004. Drawing.setClipUrl(lineContainer, clipId, gd);
  62005. return lineClip;
  62006. };
  62007. exports.labelFormatter = function(contours, colorbar, fullLayout) {
  62008. if(contours.labelformat) {
  62009. return fullLayout._d3locale.numberFormat(contours.labelformat);
  62010. }
  62011. else {
  62012. var formatAxis;
  62013. if(colorbar) {
  62014. formatAxis = colorbar.axis;
  62015. }
  62016. else {
  62017. formatAxis = {
  62018. type: 'linear',
  62019. _id: 'ycontour',
  62020. showexponent: 'all',
  62021. exponentformat: 'B'
  62022. };
  62023. if(contours.type === 'constraint') {
  62024. var value = contours.value;
  62025. if(Array.isArray(value)) {
  62026. formatAxis.range = [value[0], value[value.length - 1]];
  62027. }
  62028. else formatAxis.range = [value, value];
  62029. }
  62030. else {
  62031. formatAxis.range = [contours.start, contours.end];
  62032. formatAxis.nticks = (contours.end - contours.start) / contours.size;
  62033. }
  62034. if(formatAxis.range[0] === formatAxis.range[1]) {
  62035. formatAxis.range[1] += formatAxis.range[0] || 1;
  62036. }
  62037. if(!formatAxis.nticks) formatAxis.nticks = 1000;
  62038. setConvert(formatAxis, fullLayout);
  62039. Axes.prepTicks(formatAxis);
  62040. formatAxis._tmin = null;
  62041. formatAxis._tmax = null;
  62042. }
  62043. return function(v) {
  62044. return Axes.tickText(formatAxis, v).text;
  62045. };
  62046. }
  62047. };
  62048. exports.calcTextOpts = function(level, contourFormat, dummyText, gd) {
  62049. var text = contourFormat(level);
  62050. dummyText.text(text)
  62051. .call(svgTextUtils.convertToTspans, gd);
  62052. var bBox = Drawing.bBox(dummyText.node(), true);
  62053. return {
  62054. text: text,
  62055. width: bBox.width,
  62056. height: bBox.height,
  62057. level: level,
  62058. dy: (bBox.top + bBox.bottom) / 2
  62059. };
  62060. };
  62061. exports.findBestTextLocation = function(path, pathBounds, textOpts, labelData, plotBounds) {
  62062. var textWidth = textOpts.width;
  62063. var p0, dp, pMax, pMin, loc;
  62064. if(pathBounds.isClosed) {
  62065. dp = pathBounds.len / costConstants.INITIALSEARCHPOINTS;
  62066. p0 = pathBounds.min + dp / 2;
  62067. pMax = pathBounds.max;
  62068. }
  62069. else {
  62070. dp = (pathBounds.len - textWidth) / (costConstants.INITIALSEARCHPOINTS + 1);
  62071. p0 = pathBounds.min + dp + textWidth / 2;
  62072. pMax = pathBounds.max - (dp + textWidth) / 2;
  62073. }
  62074. var cost = Infinity;
  62075. for(var j = 0; j < costConstants.ITERATIONS; j++) {
  62076. for(var p = p0; p < pMax; p += dp) {
  62077. var newLocation = Lib.getTextLocation(path, pathBounds.total, p, textWidth);
  62078. var newCost = locationCost(newLocation, textOpts, labelData, plotBounds);
  62079. if(newCost < cost) {
  62080. cost = newCost;
  62081. loc = newLocation;
  62082. pMin = p;
  62083. }
  62084. }
  62085. if(cost > costConstants.MAXCOST * 2) break;
  62086. // subsequent iterations just look half steps away from the
  62087. // best we found in the previous iteration
  62088. if(j) dp /= 2;
  62089. p0 = pMin - dp / 2;
  62090. pMax = p0 + dp * 1.5;
  62091. }
  62092. if(cost <= costConstants.MAXCOST) return loc;
  62093. };
  62094. /*
  62095. * locationCost: a cost function for label locations
  62096. * composed of three kinds of penalty:
  62097. * - for open paths, being close to the end of the path
  62098. * - the angle away from horizontal
  62099. * - being too close to already placed neighbors
  62100. */
  62101. function locationCost(loc, textOpts, labelData, bounds) {
  62102. var halfWidth = textOpts.width / 2;
  62103. var halfHeight = textOpts.height / 2;
  62104. var x = loc.x;
  62105. var y = loc.y;
  62106. var theta = loc.theta;
  62107. var dx = Math.cos(theta) * halfWidth;
  62108. var dy = Math.sin(theta) * halfWidth;
  62109. // cost for being near an edge
  62110. var normX = ((x > bounds.center) ? (bounds.right - x) : (x - bounds.left)) /
  62111. (dx + Math.abs(Math.sin(theta) * halfHeight));
  62112. var normY = ((y > bounds.middle) ? (bounds.bottom - y) : (y - bounds.top)) /
  62113. (Math.abs(dy) + Math.cos(theta) * halfHeight);
  62114. if(normX < 1 || normY < 1) return Infinity;
  62115. var cost = costConstants.EDGECOST * (1 / (normX - 1) + 1 / (normY - 1));
  62116. // cost for not being horizontal
  62117. cost += costConstants.ANGLECOST * theta * theta;
  62118. // cost for being close to other labels
  62119. var x1 = x - dx;
  62120. var y1 = y - dy;
  62121. var x2 = x + dx;
  62122. var y2 = y + dy;
  62123. for(var i = 0; i < labelData.length; i++) {
  62124. var labeli = labelData[i];
  62125. var dxd = Math.cos(labeli.theta) * labeli.width / 2;
  62126. var dyd = Math.sin(labeli.theta) * labeli.width / 2;
  62127. var dist = Lib.segmentDistance(
  62128. x1, y1,
  62129. x2, y2,
  62130. labeli.x - dxd, labeli.y - dyd,
  62131. labeli.x + dxd, labeli.y + dyd
  62132. ) * 2 / (textOpts.height + labeli.height);
  62133. var sameLevel = labeli.level === textOpts.level;
  62134. var distOffset = sameLevel ? costConstants.SAMELEVELDISTANCE : 1;
  62135. if(dist <= distOffset) return Infinity;
  62136. var distFactor = costConstants.NEIGHBORCOST *
  62137. (sameLevel ? costConstants.SAMELEVELFACTOR : 1);
  62138. cost += distFactor / (dist - distOffset);
  62139. }
  62140. return cost;
  62141. }
  62142. exports.addLabelData = function(loc, textOpts, labelData, labelClipPathData) {
  62143. var halfWidth = textOpts.width / 2;
  62144. var halfHeight = textOpts.height / 2;
  62145. var x = loc.x;
  62146. var y = loc.y;
  62147. var theta = loc.theta;
  62148. var sin = Math.sin(theta);
  62149. var cos = Math.cos(theta);
  62150. var dxw = halfWidth * cos;
  62151. var dxh = halfHeight * sin;
  62152. var dyw = halfWidth * sin;
  62153. var dyh = -halfHeight * cos;
  62154. var bBoxPts = [
  62155. [x - dxw - dxh, y - dyw - dyh],
  62156. [x + dxw - dxh, y + dyw - dyh],
  62157. [x + dxw + dxh, y + dyw + dyh],
  62158. [x - dxw + dxh, y - dyw + dyh],
  62159. ];
  62160. labelData.push({
  62161. text: textOpts.text,
  62162. x: x,
  62163. y: y,
  62164. dy: textOpts.dy,
  62165. theta: theta,
  62166. level: textOpts.level,
  62167. width: textOpts.width,
  62168. height: textOpts.height
  62169. });
  62170. labelClipPathData.push(bBoxPts);
  62171. };
  62172. exports.drawLabels = function(labelGroup, labelData, gd, lineClip, labelClipPathData) {
  62173. var labels = labelGroup.selectAll('text')
  62174. .data(labelData, function(d) {
  62175. return d.text + ',' + d.x + ',' + d.y + ',' + d.theta;
  62176. });
  62177. labels.exit().remove();
  62178. labels.enter().append('text')
  62179. .attr({
  62180. 'data-notex': 1,
  62181. 'text-anchor': 'middle'
  62182. })
  62183. .each(function(d) {
  62184. var x = d.x + Math.sin(d.theta) * d.dy;
  62185. var y = d.y - Math.cos(d.theta) * d.dy;
  62186. d3.select(this)
  62187. .text(d.text)
  62188. .attr({
  62189. x: x,
  62190. y: y,
  62191. transform: 'rotate(' + (180 * d.theta / Math.PI) + ' ' + x + ' ' + y + ')'
  62192. })
  62193. .call(svgTextUtils.convertToTspans, gd);
  62194. });
  62195. if(labelClipPathData) {
  62196. var clipPath = '';
  62197. for(var i = 0; i < labelClipPathData.length; i++) {
  62198. clipPath += 'M' + labelClipPathData[i].join('L') + 'Z';
  62199. }
  62200. var lineClipPath = Lib.ensureSingle(lineClip, 'path', '');
  62201. lineClipPath.attr('d', clipPath);
  62202. }
  62203. };
  62204. function clipGaps(plotGroup, plotinfo, gd, cd0, perimeter) {
  62205. var clips = gd._fullLayout._clips;
  62206. var clipId = 'clip' + cd0.trace.uid;
  62207. var clipPath = clips.selectAll('#' + clipId)
  62208. .data(cd0.trace.connectgaps ? [] : [0]);
  62209. clipPath.enter().append('clipPath')
  62210. .classed('contourclip', true)
  62211. .attr('id', clipId);
  62212. clipPath.exit().remove();
  62213. if(cd0.trace.connectgaps === false) {
  62214. var clipPathInfo = {
  62215. // fraction of the way from missing to present point
  62216. // to draw the boundary.
  62217. // if you make this 1 (or 1-epsilon) then a point in
  62218. // a sea of missing data will disappear entirely.
  62219. level: 0.9,
  62220. crossings: {},
  62221. starts: [],
  62222. edgepaths: [],
  62223. paths: [],
  62224. xaxis: plotinfo.xaxis,
  62225. yaxis: plotinfo.yaxis,
  62226. x: cd0.x,
  62227. y: cd0.y,
  62228. // 0 = no data, 1 = data
  62229. z: makeClipMask(cd0),
  62230. smoothing: 0
  62231. };
  62232. makeCrossings([clipPathInfo]);
  62233. findAllPaths([clipPathInfo]);
  62234. var fullpath = joinAllPaths(clipPathInfo, perimeter);
  62235. var path = Lib.ensureSingle(clipPath, 'path', '');
  62236. path.attr('d', fullpath);
  62237. }
  62238. else clipId = null;
  62239. Drawing.setClipUrl(plotGroup, clipId, gd);
  62240. }
  62241. function makeClipMask(cd0) {
  62242. var empties = cd0.trace._emptypoints;
  62243. var z = [];
  62244. var m = cd0.z.length;
  62245. var n = cd0.z[0].length;
  62246. var i;
  62247. var row = [];
  62248. var emptyPoint;
  62249. for(i = 0; i < n; i++) row.push(1);
  62250. for(i = 0; i < m; i++) z.push(row.slice());
  62251. for(i = 0; i < empties.length; i++) {
  62252. emptyPoint = empties[i];
  62253. z[emptyPoint[0]][emptyPoint[1]] = 0;
  62254. }
  62255. // save this mask to determine whether to show this data in hover
  62256. cd0.zmask = z;
  62257. return z;
  62258. }
  62259. },{"../../components/drawing":72,"../../lib":168,"../../lib/svg_text_utils":189,"../../plots/cartesian/axes":212,"../../plots/cartesian/set_convert":231,"../heatmap/plot":327,"./close_boundaries":296,"./constants":298,"./convert_to_constraints":302,"./empty_pathinfo":304,"./find_all_paths":306,"./make_crossings":311,"d3":16}],313:[function(_dereq_,module,exports){
  62260. /**
  62261. * Copyright 2012-2019, Plotly, Inc.
  62262. * All rights reserved.
  62263. *
  62264. * This source code is licensed under the MIT license found in the
  62265. * LICENSE file in the root directory of this source tree.
  62266. */
  62267. 'use strict';
  62268. var Axes = _dereq_('../../plots/cartesian/axes');
  62269. var Lib = _dereq_('../../lib');
  62270. module.exports = function setContours(trace) {
  62271. var contours = trace.contours;
  62272. // check if we need to auto-choose contour levels
  62273. if(trace.autocontour) {
  62274. var zmin = trace.zmin;
  62275. var zmax = trace.zmax;
  62276. if(zmin === undefined || zmax === undefined) {
  62277. zmin = Lib.aggNums(Math.min, null, trace._z);
  62278. zmax = Lib.aggNums(Math.max, null, trace._z);
  62279. }
  62280. var dummyAx = autoContours(zmin, zmax, trace.ncontours);
  62281. contours.size = dummyAx.dtick;
  62282. contours.start = Axes.tickFirst(dummyAx);
  62283. dummyAx.range.reverse();
  62284. contours.end = Axes.tickFirst(dummyAx);
  62285. if(contours.start === zmin) contours.start += contours.size;
  62286. if(contours.end === zmax) contours.end -= contours.size;
  62287. // if you set a small ncontours, *and* the ends are exactly on zmin/zmax
  62288. // there's an edge case where start > end now. Make sure there's at least
  62289. // one meaningful contour, put it midway between the crossed values
  62290. if(contours.start > contours.end) {
  62291. contours.start = contours.end = (contours.start + contours.end) / 2;
  62292. }
  62293. // copy auto-contour info back to the source data.
  62294. // previously we copied the whole contours object back, but that had
  62295. // other info (coloring, showlines) that should be left to supplyDefaults
  62296. if(!trace._input.contours) trace._input.contours = {};
  62297. Lib.extendFlat(trace._input.contours, {
  62298. start: contours.start,
  62299. end: contours.end,
  62300. size: contours.size
  62301. });
  62302. trace._input.autocontour = true;
  62303. }
  62304. else if(contours.type !== 'constraint') {
  62305. // sanity checks on manually-supplied start/end/size
  62306. var start = contours.start;
  62307. var end = contours.end;
  62308. var inputContours = trace._input.contours;
  62309. if(start > end) {
  62310. contours.start = inputContours.start = end;
  62311. end = contours.end = inputContours.end = start;
  62312. start = contours.start;
  62313. }
  62314. if(!(contours.size > 0)) {
  62315. var sizeOut;
  62316. if(start === end) sizeOut = 1;
  62317. else sizeOut = autoContours(start, end, trace.ncontours).dtick;
  62318. inputContours.size = contours.size = sizeOut;
  62319. }
  62320. }
  62321. };
  62322. /*
  62323. * autoContours: make a dummy axis object with dtick we can use
  62324. * as contours.size, and if needed we can use Axes.tickFirst
  62325. * with this axis object to calculate the start and end too
  62326. *
  62327. * start: the value to start the contours at
  62328. * end: the value to end at (must be > start)
  62329. * ncontours: max number of contours to make, like roughDTick
  62330. *
  62331. * returns: an axis object
  62332. */
  62333. function autoContours(start, end, ncontours) {
  62334. var dummyAx = {
  62335. type: 'linear',
  62336. range: [start, end]
  62337. };
  62338. Axes.autoTicks(
  62339. dummyAx,
  62340. (end - start) / (ncontours || 15)
  62341. );
  62342. return dummyAx;
  62343. }
  62344. },{"../../lib":168,"../../plots/cartesian/axes":212}],314:[function(_dereq_,module,exports){
  62345. /**
  62346. * Copyright 2012-2019, Plotly, Inc.
  62347. * All rights reserved.
  62348. *
  62349. * This source code is licensed under the MIT license found in the
  62350. * LICENSE file in the root directory of this source tree.
  62351. */
  62352. 'use strict';
  62353. var d3 = _dereq_('d3');
  62354. var Drawing = _dereq_('../../components/drawing');
  62355. var heatmapStyle = _dereq_('../heatmap/style');
  62356. var makeColorMap = _dereq_('./make_color_map');
  62357. module.exports = function style(gd) {
  62358. var contours = d3.select(gd).selectAll('g.contour');
  62359. contours.style('opacity', function(d) {
  62360. return d[0].trace.opacity;
  62361. });
  62362. contours.each(function(d) {
  62363. var c = d3.select(this);
  62364. var trace = d[0].trace;
  62365. var contours = trace.contours;
  62366. var line = trace.line;
  62367. var cs = contours.size || 1;
  62368. var start = contours.start;
  62369. // for contourcarpet only - is this a constraint-type contour trace?
  62370. var isConstraintType = contours.type === 'constraint';
  62371. var colorLines = !isConstraintType && contours.coloring === 'lines';
  62372. var colorFills = !isConstraintType && contours.coloring === 'fill';
  62373. var colorMap = (colorLines || colorFills) ? makeColorMap(trace) : null;
  62374. c.selectAll('g.contourlevel').each(function(d) {
  62375. d3.select(this).selectAll('path')
  62376. .call(Drawing.lineGroupStyle,
  62377. line.width,
  62378. colorLines ? colorMap(d.level) : line.color,
  62379. line.dash);
  62380. });
  62381. var labelFont = contours.labelfont;
  62382. c.selectAll('g.contourlabels text').each(function(d) {
  62383. Drawing.font(d3.select(this), {
  62384. family: labelFont.family,
  62385. size: labelFont.size,
  62386. color: labelFont.color || (colorLines ? colorMap(d.level) : line.color)
  62387. });
  62388. });
  62389. if(isConstraintType) {
  62390. c.selectAll('g.contourfill path')
  62391. .style('fill', trace.fillcolor);
  62392. }
  62393. else if(colorFills) {
  62394. var firstFill;
  62395. c.selectAll('g.contourfill path')
  62396. .style('fill', function(d) {
  62397. if(firstFill === undefined) firstFill = d.level;
  62398. return colorMap(d.level + 0.5 * cs);
  62399. });
  62400. if(firstFill === undefined) firstFill = start;
  62401. c.selectAll('g.contourbg path')
  62402. .style('fill', colorMap(firstFill - 0.5 * cs));
  62403. }
  62404. });
  62405. heatmapStyle(gd);
  62406. };
  62407. },{"../../components/drawing":72,"../heatmap/style":328,"./make_color_map":310,"d3":16}],315:[function(_dereq_,module,exports){
  62408. /**
  62409. * Copyright 2012-2019, Plotly, Inc.
  62410. * All rights reserved.
  62411. *
  62412. * This source code is licensed under the MIT license found in the
  62413. * LICENSE file in the root directory of this source tree.
  62414. */
  62415. 'use strict';
  62416. var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
  62417. var handleLabelDefaults = _dereq_('./label_defaults');
  62418. module.exports = function handleStyleDefaults(traceIn, traceOut, coerce, layout, opts) {
  62419. var coloring = coerce('contours.coloring');
  62420. var showLines;
  62421. var lineColor = '';
  62422. if(coloring === 'fill') showLines = coerce('contours.showlines');
  62423. if(showLines !== false) {
  62424. if(coloring !== 'lines') lineColor = coerce('line.color', '#000');
  62425. coerce('line.width', 0.5);
  62426. coerce('line.dash');
  62427. }
  62428. if(coloring !== 'none') {
  62429. // plots/plots always coerces showlegend to true, but in this case
  62430. // we default to false and (by default) show a colorbar instead
  62431. if(traceIn.showlegend !== true) traceOut.showlegend = false;
  62432. traceOut._dfltShowLegend = false;
  62433. colorscaleDefaults(
  62434. traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}
  62435. );
  62436. }
  62437. coerce('line.smoothing');
  62438. handleLabelDefaults(coerce, layout, lineColor, opts);
  62439. };
  62440. },{"../../components/colorscale/defaults":61,"./label_defaults":309}],316:[function(_dereq_,module,exports){
  62441. /**
  62442. * Copyright 2012-2019, Plotly, Inc.
  62443. * All rights reserved.
  62444. *
  62445. * This source code is licensed under the MIT license found in the
  62446. * LICENSE file in the root directory of this source tree.
  62447. */
  62448. 'use strict';
  62449. var scatterAttrs = _dereq_('../scatter/attributes');
  62450. var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
  62451. var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
  62452. var extendFlat = _dereq_('../../lib/extend').extendFlat;
  62453. module.exports = extendFlat({
  62454. z: {
  62455. valType: 'data_array',
  62456. editType: 'calc',
  62457. },
  62458. x: extendFlat({}, scatterAttrs.x, {impliedEdits: {xtype: 'array'}}),
  62459. x0: extendFlat({}, scatterAttrs.x0, {impliedEdits: {xtype: 'scaled'}}),
  62460. dx: extendFlat({}, scatterAttrs.dx, {impliedEdits: {xtype: 'scaled'}}),
  62461. y: extendFlat({}, scatterAttrs.y, {impliedEdits: {ytype: 'array'}}),
  62462. y0: extendFlat({}, scatterAttrs.y0, {impliedEdits: {ytype: 'scaled'}}),
  62463. dy: extendFlat({}, scatterAttrs.dy, {impliedEdits: {ytype: 'scaled'}}),
  62464. text: {
  62465. valType: 'data_array',
  62466. editType: 'calc',
  62467. },
  62468. transpose: {
  62469. valType: 'boolean',
  62470. dflt: false,
  62471. editType: 'calc',
  62472. },
  62473. xtype: {
  62474. valType: 'enumerated',
  62475. values: ['array', 'scaled'],
  62476. editType: 'calc+clearAxisTypes',
  62477. },
  62478. ytype: {
  62479. valType: 'enumerated',
  62480. values: ['array', 'scaled'],
  62481. editType: 'calc+clearAxisTypes',
  62482. },
  62483. zsmooth: {
  62484. valType: 'enumerated',
  62485. values: ['fast', 'best', false],
  62486. dflt: false,
  62487. editType: 'calc',
  62488. },
  62489. connectgaps: {
  62490. valType: 'boolean',
  62491. dflt: false,
  62492. editType: 'calc',
  62493. },
  62494. xgap: {
  62495. valType: 'number',
  62496. dflt: 0,
  62497. min: 0,
  62498. editType: 'plot',
  62499. },
  62500. ygap: {
  62501. valType: 'number',
  62502. dflt: 0,
  62503. min: 0,
  62504. editType: 'plot',
  62505. },
  62506. zhoverformat: {
  62507. valType: 'string',
  62508. dflt: '',
  62509. editType: 'none',
  62510. },
  62511. transforms: undefined
  62512. },
  62513. colorscaleAttrs('', {
  62514. cLetter: 'z',
  62515. autoColorDflt: false
  62516. }),
  62517. { colorbar: colorbarAttrs }
  62518. );
  62519. },{"../../components/colorbar/attributes":52,"../../components/colorscale/attributes":58,"../../lib/extend":162,"../scatter/attributes":367}],317:[function(_dereq_,module,exports){
  62520. /**
  62521. * Copyright 2012-2019, Plotly, Inc.
  62522. * All rights reserved.
  62523. *
  62524. * This source code is licensed under the MIT license found in the
  62525. * LICENSE file in the root directory of this source tree.
  62526. */
  62527. 'use strict';
  62528. var Registry = _dereq_('../../registry');
  62529. var Lib = _dereq_('../../lib');
  62530. var Axes = _dereq_('../../plots/cartesian/axes');
  62531. var histogram2dCalc = _dereq_('../histogram2d/calc');
  62532. var colorscaleCalc = _dereq_('../../components/colorscale/calc');
  62533. var convertColumnData = _dereq_('./convert_column_xyz');
  62534. var clean2dArray = _dereq_('./clean_2d_array');
  62535. var interp2d = _dereq_('./interp2d');
  62536. var findEmpties = _dereq_('./find_empties');
  62537. var makeBoundArray = _dereq_('./make_bound_array');
  62538. module.exports = function calc(gd, trace) {
  62539. // prepare the raw data
  62540. // run makeCalcdata on x and y even for heatmaps, in case of category mappings
  62541. var xa = Axes.getFromId(gd, trace.xaxis || 'x');
  62542. var ya = Axes.getFromId(gd, trace.yaxis || 'y');
  62543. var isContour = Registry.traceIs(trace, 'contour');
  62544. var isHist = Registry.traceIs(trace, 'histogram');
  62545. var isGL2D = Registry.traceIs(trace, 'gl2d');
  62546. var zsmooth = isContour ? 'best' : trace.zsmooth;
  62547. var x;
  62548. var x0;
  62549. var dx;
  62550. var y;
  62551. var y0;
  62552. var dy;
  62553. var z;
  62554. var i;
  62555. var binned;
  62556. // cancel minimum tick spacings (only applies to bars and boxes)
  62557. xa._minDtick = 0;
  62558. ya._minDtick = 0;
  62559. if(isHist) {
  62560. binned = histogram2dCalc(gd, trace);
  62561. x = binned.x;
  62562. x0 = binned.x0;
  62563. dx = binned.dx;
  62564. y = binned.y;
  62565. y0 = binned.y0;
  62566. dy = binned.dy;
  62567. z = binned.z;
  62568. }
  62569. else {
  62570. var zIn = trace.z;
  62571. if(Lib.isArray1D(zIn)) {
  62572. convertColumnData(trace, xa, ya, 'x', 'y', ['z']);
  62573. x = trace._x;
  62574. y = trace._y;
  62575. zIn = trace._z;
  62576. } else {
  62577. x = trace.x ? xa.makeCalcdata(trace, 'x') : [];
  62578. y = trace.y ? ya.makeCalcdata(trace, 'y') : [];
  62579. }
  62580. x0 = trace.x0 || 0;
  62581. dx = trace.dx || 1;
  62582. y0 = trace.y0 || 0;
  62583. dy = trace.dy || 1;
  62584. z = clean2dArray(zIn, trace.transpose);
  62585. if(isContour || trace.connectgaps) {
  62586. trace._emptypoints = findEmpties(z);
  62587. interp2d(z, trace._emptypoints);
  62588. }
  62589. }
  62590. function noZsmooth(msg) {
  62591. zsmooth = trace._input.zsmooth = trace.zsmooth = false;
  62592. Lib.warn('cannot use zsmooth: "fast": ' + msg);
  62593. }
  62594. // check whether we really can smooth (ie all boxes are about the same size)
  62595. if(zsmooth === 'fast') {
  62596. if(xa.type === 'log' || ya.type === 'log') {
  62597. noZsmooth('log axis found');
  62598. }
  62599. else if(!isHist) {
  62600. if(x.length) {
  62601. var avgdx = (x[x.length - 1] - x[0]) / (x.length - 1);
  62602. var maxErrX = Math.abs(avgdx / 100);
  62603. for(i = 0; i < x.length - 1; i++) {
  62604. if(Math.abs(x[i + 1] - x[i] - avgdx) > maxErrX) {
  62605. noZsmooth('x scale is not linear');
  62606. break;
  62607. }
  62608. }
  62609. }
  62610. if(y.length && zsmooth === 'fast') {
  62611. var avgdy = (y[y.length - 1] - y[0]) / (y.length - 1);
  62612. var maxErrY = Math.abs(avgdy / 100);
  62613. for(i = 0; i < y.length - 1; i++) {
  62614. if(Math.abs(y[i + 1] - y[i] - avgdy) > maxErrY) {
  62615. noZsmooth('y scale is not linear');
  62616. break;
  62617. }
  62618. }
  62619. }
  62620. }
  62621. }
  62622. // create arrays of brick boundaries, to be used by autorange and heatmap.plot
  62623. var xlen = Lib.maxRowLength(z);
  62624. var xIn = trace.xtype === 'scaled' ? '' : x;
  62625. var xArray = makeBoundArray(trace, xIn, x0, dx, xlen, xa);
  62626. var yIn = trace.ytype === 'scaled' ? '' : y;
  62627. var yArray = makeBoundArray(trace, yIn, y0, dy, z.length, ya);
  62628. // handled in gl2d convert step
  62629. if(!isGL2D) {
  62630. trace._extremes[xa._id] = Axes.findExtremes(xa, xArray);
  62631. trace._extremes[ya._id] = Axes.findExtremes(ya, yArray);
  62632. }
  62633. var cd0 = {
  62634. x: xArray,
  62635. y: yArray,
  62636. z: z,
  62637. text: trace._text || trace.text
  62638. };
  62639. if(xIn && xIn.length === xArray.length - 1) cd0.xCenter = xIn;
  62640. if(yIn && yIn.length === yArray.length - 1) cd0.yCenter = yIn;
  62641. if(isHist) {
  62642. cd0.xRanges = binned.xRanges;
  62643. cd0.yRanges = binned.yRanges;
  62644. cd0.pts = binned.pts;
  62645. }
  62646. // auto-z and autocolorscale if applicable
  62647. if(!isContour || trace.contours.type !== 'constraint') {
  62648. colorscaleCalc(gd, trace, {
  62649. vals: z,
  62650. containerStr: '',
  62651. cLetter: 'z'
  62652. });
  62653. }
  62654. if(isContour && trace.contours && trace.contours.coloring === 'heatmap') {
  62655. var dummyTrace = {
  62656. type: trace.type === 'contour' ? 'heatmap' : 'histogram2d',
  62657. xcalendar: trace.xcalendar,
  62658. ycalendar: trace.ycalendar
  62659. };
  62660. cd0.xfill = makeBoundArray(dummyTrace, xIn, x0, dx, xlen, xa);
  62661. cd0.yfill = makeBoundArray(dummyTrace, yIn, y0, dy, z.length, ya);
  62662. }
  62663. return [cd0];
  62664. };
  62665. },{"../../components/colorscale/calc":59,"../../lib":168,"../../plots/cartesian/axes":212,"../../registry":257,"../histogram2d/calc":345,"./clean_2d_array":318,"./convert_column_xyz":320,"./find_empties":322,"./interp2d":325,"./make_bound_array":326}],318:[function(_dereq_,module,exports){
  62666. /**
  62667. * Copyright 2012-2019, Plotly, Inc.
  62668. * All rights reserved.
  62669. *
  62670. * This source code is licensed under the MIT license found in the
  62671. * LICENSE file in the root directory of this source tree.
  62672. */
  62673. 'use strict';
  62674. var isNumeric = _dereq_('fast-isnumeric');
  62675. module.exports = function clean2dArray(zOld, transpose) {
  62676. var rowlen, collen, getCollen, old2new, i, j;
  62677. function cleanZvalue(v) {
  62678. if(!isNumeric(v)) return undefined;
  62679. return +v;
  62680. }
  62681. if(transpose) {
  62682. rowlen = 0;
  62683. for(i = 0; i < zOld.length; i++) rowlen = Math.max(rowlen, zOld[i].length);
  62684. if(rowlen === 0) return false;
  62685. getCollen = function(zOld) { return zOld.length; };
  62686. old2new = function(zOld, i, j) { return zOld[j][i]; };
  62687. }
  62688. else {
  62689. rowlen = zOld.length;
  62690. getCollen = function(zOld, i) { return zOld[i].length; };
  62691. old2new = function(zOld, i, j) { return zOld[i][j]; };
  62692. }
  62693. var zNew = new Array(rowlen);
  62694. for(i = 0; i < rowlen; i++) {
  62695. collen = getCollen(zOld, i);
  62696. zNew[i] = new Array(collen);
  62697. for(j = 0; j < collen; j++) zNew[i][j] = cleanZvalue(old2new(zOld, i, j));
  62698. }
  62699. return zNew;
  62700. };
  62701. },{"fast-isnumeric":18}],319:[function(_dereq_,module,exports){
  62702. /**
  62703. * Copyright 2012-2019, Plotly, Inc.
  62704. * All rights reserved.
  62705. *
  62706. * This source code is licensed under the MIT license found in the
  62707. * LICENSE file in the root directory of this source tree.
  62708. */
  62709. 'use strict';
  62710. module.exports = {
  62711. min: 'zmin',
  62712. max: 'zmax'
  62713. };
  62714. },{}],320:[function(_dereq_,module,exports){
  62715. /**
  62716. * Copyright 2012-2019, Plotly, Inc.
  62717. * All rights reserved.
  62718. *
  62719. * This source code is licensed under the MIT license found in the
  62720. * LICENSE file in the root directory of this source tree.
  62721. */
  62722. 'use strict';
  62723. var Lib = _dereq_('../../lib');
  62724. var BADNUM = _dereq_('../../constants/numerical').BADNUM;
  62725. module.exports = function convertColumnData(trace, ax1, ax2, var1Name, var2Name, arrayVarNames) {
  62726. var colLen = trace._length;
  62727. var col1 = ax1.makeCalcdata(trace, var1Name);
  62728. var col2 = ax2.makeCalcdata(trace, var2Name);
  62729. var textCol = trace.text;
  62730. var hasColumnText = (textCol !== undefined && Lib.isArray1D(textCol));
  62731. var i, j;
  62732. var col1dv = Lib.distinctVals(col1);
  62733. var col1vals = col1dv.vals;
  62734. var col2dv = Lib.distinctVals(col2);
  62735. var col2vals = col2dv.vals;
  62736. var newArrays = [];
  62737. var text;
  62738. for(i = 0; i < arrayVarNames.length; i++) {
  62739. newArrays[i] = Lib.init2dArray(col2vals.length, col1vals.length);
  62740. }
  62741. if(hasColumnText) {
  62742. text = Lib.init2dArray(col2vals.length, col1vals.length);
  62743. }
  62744. for(i = 0; i < colLen; i++) {
  62745. if(col1[i] !== BADNUM && col2[i] !== BADNUM) {
  62746. var i1 = Lib.findBin(col1[i] + col1dv.minDiff / 2, col1vals);
  62747. var i2 = Lib.findBin(col2[i] + col2dv.minDiff / 2, col2vals);
  62748. for(j = 0; j < arrayVarNames.length; j++) {
  62749. var arrayVarName = arrayVarNames[j];
  62750. var arrayVar = trace[arrayVarName];
  62751. var newArray = newArrays[j];
  62752. newArray[i2][i1] = arrayVar[i];
  62753. }
  62754. if(hasColumnText) text[i2][i1] = textCol[i];
  62755. }
  62756. }
  62757. trace['_' + var1Name] = col1vals;
  62758. trace['_' + var2Name] = col2vals;
  62759. for(j = 0; j < arrayVarNames.length; j++) {
  62760. trace['_' + arrayVarNames[j]] = newArrays[j];
  62761. }
  62762. if(hasColumnText) trace._text = text;
  62763. };
  62764. },{"../../constants/numerical":149,"../../lib":168}],321:[function(_dereq_,module,exports){
  62765. /**
  62766. * Copyright 2012-2019, Plotly, Inc.
  62767. * All rights reserved.
  62768. *
  62769. * This source code is licensed under the MIT license found in the
  62770. * LICENSE file in the root directory of this source tree.
  62771. */
  62772. 'use strict';
  62773. var Lib = _dereq_('../../lib');
  62774. var handleXYZDefaults = _dereq_('./xyz_defaults');
  62775. var handleStyleDefaults = _dereq_('./style_defaults');
  62776. var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
  62777. var attributes = _dereq_('./attributes');
  62778. module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
  62779. function coerce(attr, dflt) {
  62780. return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
  62781. }
  62782. var validData = handleXYZDefaults(traceIn, traceOut, coerce, layout);
  62783. if(!validData) {
  62784. traceOut.visible = false;
  62785. return;
  62786. }
  62787. coerce('text');
  62788. handleStyleDefaults(traceIn, traceOut, coerce, layout);
  62789. coerce('connectgaps', Lib.isArray1D(traceOut.z) && (traceOut.zsmooth !== false));
  62790. colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'});
  62791. };
  62792. },{"../../components/colorscale/defaults":61,"../../lib":168,"./attributes":316,"./style_defaults":329,"./xyz_defaults":330}],322:[function(_dereq_,module,exports){
  62793. /**
  62794. * Copyright 2012-2019, Plotly, Inc.
  62795. * All rights reserved.
  62796. *
  62797. * This source code is licensed under the MIT license found in the
  62798. * LICENSE file in the root directory of this source tree.
  62799. */
  62800. 'use strict';
  62801. var maxRowLength = _dereq_('../../lib').maxRowLength;
  62802. /* Return a list of empty points in 2D array z
  62803. * each empty point z[i][j] gives an array [i, j, neighborCount]
  62804. * neighborCount is the count of 4 nearest neighbors that DO exist
  62805. * this is to give us an order of points to evaluate for interpolation.
  62806. * if no neighbors exist, we iteratively look for neighbors that HAVE
  62807. * neighbors, and add a fractional neighborCount
  62808. */
  62809. module.exports = function findEmpties(z) {
  62810. var empties = [];
  62811. var neighborHash = {};
  62812. var noNeighborList = [];
  62813. var nextRow = z[0];
  62814. var row = [];
  62815. var blank = [0, 0, 0];
  62816. var rowLength = maxRowLength(z);
  62817. var prevRow;
  62818. var i;
  62819. var j;
  62820. var thisPt;
  62821. var p;
  62822. var neighborCount;
  62823. var newNeighborHash;
  62824. var foundNewNeighbors;
  62825. for(i = 0; i < z.length; i++) {
  62826. prevRow = row;
  62827. row = nextRow;
  62828. nextRow = z[i + 1] || [];
  62829. for(j = 0; j < rowLength; j++) {
  62830. if(row[j] === undefined) {
  62831. neighborCount = (row[j - 1] !== undefined ? 1 : 0) +
  62832. (row[j + 1] !== undefined ? 1 : 0) +
  62833. (prevRow[j] !== undefined ? 1 : 0) +
  62834. (nextRow[j] !== undefined ? 1 : 0);
  62835. if(neighborCount) {
  62836. // for this purpose, don't count off-the-edge points
  62837. // as undefined neighbors
  62838. if(i === 0) neighborCount++;
  62839. if(j === 0) neighborCount++;
  62840. if(i === z.length - 1) neighborCount++;
  62841. if(j === row.length - 1) neighborCount++;
  62842. // if all neighbors that could exist do, we don't
  62843. // need this for finding farther neighbors
  62844. if(neighborCount < 4) {
  62845. neighborHash[[i, j]] = [i, j, neighborCount];
  62846. }
  62847. empties.push([i, j, neighborCount]);
  62848. }
  62849. else noNeighborList.push([i, j]);
  62850. }
  62851. }
  62852. }
  62853. while(noNeighborList.length) {
  62854. newNeighborHash = {};
  62855. foundNewNeighbors = false;
  62856. // look for cells that now have neighbors but didn't before
  62857. for(p = noNeighborList.length - 1; p >= 0; p--) {
  62858. thisPt = noNeighborList[p];
  62859. i = thisPt[0];
  62860. j = thisPt[1];
  62861. neighborCount = ((neighborHash[[i - 1, j]] || blank)[2] +
  62862. (neighborHash[[i + 1, j]] || blank)[2] +
  62863. (neighborHash[[i, j - 1]] || blank)[2] +
  62864. (neighborHash[[i, j + 1]] || blank)[2]) / 20;
  62865. if(neighborCount) {
  62866. newNeighborHash[thisPt] = [i, j, neighborCount];
  62867. noNeighborList.splice(p, 1);
  62868. foundNewNeighbors = true;
  62869. }
  62870. }
  62871. if(!foundNewNeighbors) {
  62872. throw 'findEmpties iterated with no new neighbors';
  62873. }
  62874. // put these new cells into the main neighbor list
  62875. for(thisPt in newNeighborHash) {
  62876. neighborHash[thisPt] = newNeighborHash[thisPt];
  62877. empties.push(newNeighborHash[thisPt]);
  62878. }
  62879. }
  62880. // sort the full list in descending order of neighbor count
  62881. return empties.sort(function(a, b) { return b[2] - a[2]; });
  62882. };
  62883. },{"../../lib":168}],323:[function(_dereq_,module,exports){
  62884. /**
  62885. * Copyright 2012-2019, Plotly, Inc.
  62886. * All rights reserved.
  62887. *
  62888. * This source code is licensed under the MIT license found in the
  62889. * LICENSE file in the root directory of this source tree.
  62890. */
  62891. 'use strict';
  62892. var Fx = _dereq_('../../components/fx');
  62893. var Lib = _dereq_('../../lib');
  62894. var Axes = _dereq_('../../plots/cartesian/axes');
  62895. module.exports = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer, contour) {
  62896. var cd0 = pointData.cd[0];
  62897. var trace = cd0.trace;
  62898. var xa = pointData.xa;
  62899. var ya = pointData.ya;
  62900. var x = cd0.x;
  62901. var y = cd0.y;
  62902. var z = cd0.z;
  62903. var xc = cd0.xCenter;
  62904. var yc = cd0.yCenter;
  62905. var zmask = cd0.zmask;
  62906. var range = [trace.zmin, trace.zmax];
  62907. var zhoverformat = trace.zhoverformat;
  62908. var x2 = x;
  62909. var y2 = y;
  62910. var xl, yl, nx, ny;
  62911. if(pointData.index !== false) {
  62912. try {
  62913. nx = Math.round(pointData.index[1]);
  62914. ny = Math.round(pointData.index[0]);
  62915. }
  62916. catch(e) {
  62917. Lib.error('Error hovering on heatmap, ' +
  62918. 'pointNumber must be [row,col], found:', pointData.index);
  62919. return;
  62920. }
  62921. if(nx < 0 || nx >= z[0].length || ny < 0 || ny > z.length) {
  62922. return;
  62923. }
  62924. }
  62925. else if(Fx.inbox(xval - x[0], xval - x[x.length - 1], 0) > 0 ||
  62926. Fx.inbox(yval - y[0], yval - y[y.length - 1], 0) > 0) {
  62927. return;
  62928. }
  62929. else {
  62930. if(contour) {
  62931. var i2;
  62932. x2 = [2 * x[0] - x[1]];
  62933. for(i2 = 1; i2 < x.length; i2++) {
  62934. x2.push((x[i2] + x[i2 - 1]) / 2);
  62935. }
  62936. x2.push([2 * x[x.length - 1] - x[x.length - 2]]);
  62937. y2 = [2 * y[0] - y[1]];
  62938. for(i2 = 1; i2 < y.length; i2++) {
  62939. y2.push((y[i2] + y[i2 - 1]) / 2);
  62940. }
  62941. y2.push([2 * y[y.length - 1] - y[y.length - 2]]);
  62942. }
  62943. nx = Math.max(0, Math.min(x2.length - 2, Lib.findBin(xval, x2)));
  62944. ny = Math.max(0, Math.min(y2.length - 2, Lib.findBin(yval, y2)));
  62945. }
  62946. var x0 = xa.c2p(x[nx]);
  62947. var x1 = xa.c2p(x[nx + 1]);
  62948. var y0 = ya.c2p(y[ny]);
  62949. var y1 = ya.c2p(y[ny + 1]);
  62950. if(contour) {
  62951. x1 = x0;
  62952. xl = x[nx];
  62953. y1 = y0;
  62954. yl = y[ny];
  62955. }
  62956. else {
  62957. xl = xc ? xc[nx] : ((x[nx] + x[nx + 1]) / 2);
  62958. yl = yc ? yc[ny] : ((y[ny] + y[ny + 1]) / 2);
  62959. if(trace.zsmooth) {
  62960. x0 = x1 = xa.c2p(xl);
  62961. y0 = y1 = ya.c2p(yl);
  62962. }
  62963. }
  62964. var zVal = z[ny][nx];
  62965. if(zmask && !zmask[ny][nx]) zVal = undefined;
  62966. var text;
  62967. if(Array.isArray(cd0.text) && Array.isArray(cd0.text[ny])) {
  62968. text = cd0.text[ny][nx];
  62969. }
  62970. var zLabel;
  62971. // dummy axis for formatting the z value
  62972. var dummyAx = {
  62973. type: 'linear',
  62974. range: range,
  62975. hoverformat: zhoverformat,
  62976. _separators: xa._separators,
  62977. _numFormat: xa._numFormat
  62978. };
  62979. var zLabelObj = Axes.tickText(dummyAx, zVal, 'hover');
  62980. zLabel = zLabelObj.text;
  62981. return [Lib.extendFlat(pointData, {
  62982. index: [ny, nx],
  62983. // never let a 2D override 1D type as closest point
  62984. distance: pointData.maxHoverDistance,
  62985. spikeDistance: pointData.maxSpikeDistance,
  62986. x0: x0,
  62987. x1: x1,
  62988. y0: y0,
  62989. y1: y1,
  62990. xLabelVal: xl,
  62991. yLabelVal: yl,
  62992. zLabelVal: zVal,
  62993. zLabel: zLabel,
  62994. text: text
  62995. })];
  62996. };
  62997. },{"../../components/fx":90,"../../lib":168,"../../plots/cartesian/axes":212}],324:[function(_dereq_,module,exports){
  62998. /**
  62999. * Copyright 2012-2019, Plotly, Inc.
  63000. * All rights reserved.
  63001. *
  63002. * This source code is licensed under the MIT license found in the
  63003. * LICENSE file in the root directory of this source tree.
  63004. */
  63005. 'use strict';
  63006. var Heatmap = {};
  63007. Heatmap.attributes = _dereq_('./attributes');
  63008. Heatmap.supplyDefaults = _dereq_('./defaults');
  63009. Heatmap.calc = _dereq_('./calc');
  63010. Heatmap.plot = _dereq_('./plot');
  63011. Heatmap.colorbar = _dereq_('./colorbar');
  63012. Heatmap.style = _dereq_('./style');
  63013. Heatmap.hoverPoints = _dereq_('./hover');
  63014. Heatmap.moduleType = 'trace';
  63015. Heatmap.name = 'heatmap';
  63016. Heatmap.basePlotModule = _dereq_('../../plots/cartesian');
  63017. Heatmap.categories = ['cartesian', 'svg', '2dMap'];
  63018. Heatmap.meta = {
  63019. };
  63020. module.exports = Heatmap;
  63021. },{"../../plots/cartesian":224,"./attributes":316,"./calc":317,"./colorbar":319,"./defaults":321,"./hover":323,"./plot":327,"./style":328}],325:[function(_dereq_,module,exports){
  63022. /**
  63023. * Copyright 2012-2019, Plotly, Inc.
  63024. * All rights reserved.
  63025. *
  63026. * This source code is licensed under the MIT license found in the
  63027. * LICENSE file in the root directory of this source tree.
  63028. */
  63029. 'use strict';
  63030. var Lib = _dereq_('../../lib');
  63031. var INTERPTHRESHOLD = 1e-2;
  63032. var NEIGHBORSHIFTS = [[-1, 0], [1, 0], [0, -1], [0, 1]];
  63033. function correctionOvershoot(maxFractionalChange) {
  63034. // start with less overshoot, until we know it's converging,
  63035. // then ramp up the overshoot for faster convergence
  63036. return 0.5 - 0.25 * Math.min(1, maxFractionalChange * 0.5);
  63037. }
  63038. /*
  63039. * interp2d: Fill in missing data from a 2D array using an iterative
  63040. * poisson equation solver with zero-derivative BC at edges.
  63041. * Amazingly, this just amounts to repeatedly averaging all the existing
  63042. * nearest neighbors, at least if we don't take x/y scaling into account,
  63043. * which is the right approach here where x and y may not even have the
  63044. * same units.
  63045. *
  63046. * @param {array of arrays} z
  63047. * The 2D array to fill in. Will be mutated here. Assumed to already be
  63048. * cleaned, so all entries are numbers except gaps, which are `undefined`.
  63049. * @param {array of arrays} emptyPoints
  63050. * Each entry [i, j, neighborCount] for empty points z[i][j] and the number
  63051. * of neighbors that are *not* missing. Assumed to be sorted from most to
  63052. * least neighbors, as produced by heatmap/find_empties.
  63053. */
  63054. module.exports = function interp2d(z, emptyPoints) {
  63055. var maxFractionalChange = 1;
  63056. var i;
  63057. // one pass to fill in a starting value for all the empties
  63058. iterateInterp2d(z, emptyPoints);
  63059. // we're don't need to iterate lone empties - remove them
  63060. for(i = 0; i < emptyPoints.length; i++) {
  63061. if(emptyPoints[i][2] < 4) break;
  63062. }
  63063. // but don't remove these points from the original array,
  63064. // we'll use them for masking, so make a copy.
  63065. emptyPoints = emptyPoints.slice(i);
  63066. for(i = 0; i < 100 && maxFractionalChange > INTERPTHRESHOLD; i++) {
  63067. maxFractionalChange = iterateInterp2d(z, emptyPoints,
  63068. correctionOvershoot(maxFractionalChange));
  63069. }
  63070. if(maxFractionalChange > INTERPTHRESHOLD) {
  63071. Lib.log('interp2d didn\'t converge quickly', maxFractionalChange);
  63072. }
  63073. return z;
  63074. };
  63075. function iterateInterp2d(z, emptyPoints, overshoot) {
  63076. var maxFractionalChange = 0;
  63077. var thisPt;
  63078. var i;
  63079. var j;
  63080. var p;
  63081. var q;
  63082. var neighborShift;
  63083. var neighborRow;
  63084. var neighborVal;
  63085. var neighborCount;
  63086. var neighborSum;
  63087. var initialVal;
  63088. var minNeighbor;
  63089. var maxNeighbor;
  63090. for(p = 0; p < emptyPoints.length; p++) {
  63091. thisPt = emptyPoints[p];
  63092. i = thisPt[0];
  63093. j = thisPt[1];
  63094. initialVal = z[i][j];
  63095. neighborSum = 0;
  63096. neighborCount = 0;
  63097. for(q = 0; q < 4; q++) {
  63098. neighborShift = NEIGHBORSHIFTS[q];
  63099. neighborRow = z[i + neighborShift[0]];
  63100. if(!neighborRow) continue;
  63101. neighborVal = neighborRow[j + neighborShift[1]];
  63102. if(neighborVal !== undefined) {
  63103. if(neighborSum === 0) {
  63104. minNeighbor = maxNeighbor = neighborVal;
  63105. }
  63106. else {
  63107. minNeighbor = Math.min(minNeighbor, neighborVal);
  63108. maxNeighbor = Math.max(maxNeighbor, neighborVal);
  63109. }
  63110. neighborCount++;
  63111. neighborSum += neighborVal;
  63112. }
  63113. }
  63114. if(neighborCount === 0) {
  63115. throw 'iterateInterp2d order is wrong: no defined neighbors';
  63116. }
  63117. // this is the laplace equation interpolation:
  63118. // each point is just the average of its neighbors
  63119. // note that this ignores differential x/y scaling
  63120. // which I think is the right approach, since we
  63121. // don't know what that scaling means
  63122. z[i][j] = neighborSum / neighborCount;
  63123. if(initialVal === undefined) {
  63124. if(neighborCount < 4) maxFractionalChange = 1;
  63125. }
  63126. else {
  63127. // we can make large empty regions converge faster
  63128. // if we overshoot the change vs the previous value
  63129. z[i][j] = (1 + overshoot) * z[i][j] - overshoot * initialVal;
  63130. if(maxNeighbor > minNeighbor) {
  63131. maxFractionalChange = Math.max(maxFractionalChange,
  63132. Math.abs(z[i][j] - initialVal) / (maxNeighbor - minNeighbor));
  63133. }
  63134. }
  63135. }
  63136. return maxFractionalChange;
  63137. }
  63138. },{"../../lib":168}],326:[function(_dereq_,module,exports){
  63139. /**
  63140. * Copyright 2012-2019, Plotly, Inc.
  63141. * All rights reserved.
  63142. *
  63143. * This source code is licensed under the MIT license found in the
  63144. * LICENSE file in the root directory of this source tree.
  63145. */
  63146. 'use strict';
  63147. var Registry = _dereq_('../../registry');
  63148. var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;
  63149. module.exports = function makeBoundArray(trace, arrayIn, v0In, dvIn, numbricks, ax) {
  63150. var arrayOut = [];
  63151. var isContour = Registry.traceIs(trace, 'contour');
  63152. var isHist = Registry.traceIs(trace, 'histogram');
  63153. var isGL2D = Registry.traceIs(trace, 'gl2d');
  63154. var v0;
  63155. var dv;
  63156. var i;
  63157. var isArrayOfTwoItemsOrMore = isArrayOrTypedArray(arrayIn) && arrayIn.length > 1;
  63158. if(isArrayOfTwoItemsOrMore && !isHist && (ax.type !== 'category')) {
  63159. var len = arrayIn.length;
  63160. // given vals are brick centers
  63161. // hopefully length === numbricks, but use this method even if too few are supplied
  63162. // and extend it linearly based on the last two points
  63163. if(len <= numbricks) {
  63164. // contour plots only want the centers
  63165. if(isContour || isGL2D) arrayOut = arrayIn.slice(0, numbricks);
  63166. else if(numbricks === 1) {
  63167. arrayOut = [arrayIn[0] - 0.5, arrayIn[0] + 0.5];
  63168. }
  63169. else {
  63170. arrayOut = [1.5 * arrayIn[0] - 0.5 * arrayIn[1]];
  63171. for(i = 1; i < len; i++) {
  63172. arrayOut.push((arrayIn[i - 1] + arrayIn[i]) * 0.5);
  63173. }
  63174. arrayOut.push(1.5 * arrayIn[len - 1] - 0.5 * arrayIn[len - 2]);
  63175. }
  63176. if(len < numbricks) {
  63177. var lastPt = arrayOut[arrayOut.length - 1];
  63178. var delta = lastPt - arrayOut[arrayOut.length - 2];
  63179. for(i = len; i < numbricks; i++) {
  63180. lastPt += delta;
  63181. arrayOut.push(lastPt);
  63182. }
  63183. }
  63184. }
  63185. else {
  63186. // hopefully length === numbricks+1, but do something regardless:
  63187. // given vals are brick boundaries
  63188. return isContour ?
  63189. arrayIn.slice(0, numbricks) : // we must be strict for contours
  63190. arrayIn.slice(0, numbricks + 1);
  63191. }
  63192. }
  63193. else {
  63194. dv = dvIn || 1;
  63195. var calendar = trace[ax._id.charAt(0) + 'calendar'];
  63196. if(isHist || ax.type === 'category' || ax.type === 'multicategory') {
  63197. v0 = ax.r2c(v0In, 0, calendar) || 0;
  63198. } else if(isArrayOrTypedArray(arrayIn) && arrayIn.length === 1) {
  63199. v0 = arrayIn[0];
  63200. } else if(v0In === undefined) {
  63201. v0 = 0;
  63202. } else {
  63203. v0 = ax.d2c(v0In, 0, calendar);
  63204. }
  63205. for(i = (isContour || isGL2D) ? 0 : -0.5; i < numbricks; i++) {
  63206. arrayOut.push(v0 + dv * i);
  63207. }
  63208. }
  63209. return arrayOut;
  63210. };
  63211. },{"../../lib":168,"../../registry":257}],327:[function(_dereq_,module,exports){
  63212. /**
  63213. * Copyright 2012-2019, Plotly, Inc.
  63214. * All rights reserved.
  63215. *
  63216. * This source code is licensed under the MIT license found in the
  63217. * LICENSE file in the root directory of this source tree.
  63218. */
  63219. 'use strict';
  63220. var d3 = _dereq_('d3');
  63221. var tinycolor = _dereq_('tinycolor2');
  63222. var Registry = _dereq_('../../registry');
  63223. var Lib = _dereq_('../../lib');
  63224. var Colorscale = _dereq_('../../components/colorscale');
  63225. var xmlnsNamespaces = _dereq_('../../constants/xmlns_namespaces');
  63226. module.exports = function(gd, plotinfo, cdheatmaps, heatmapLayer) {
  63227. var xa = plotinfo.xaxis;
  63228. var ya = plotinfo.yaxis;
  63229. Lib.makeTraceGroups(heatmapLayer, cdheatmaps, 'hm').each(function(cd) {
  63230. var plotGroup = d3.select(this);
  63231. var cd0 = cd[0];
  63232. var trace = cd0.trace;
  63233. var z = cd0.z;
  63234. var x = cd0.x;
  63235. var y = cd0.y;
  63236. var xc = cd0.xCenter;
  63237. var yc = cd0.yCenter;
  63238. var isContour = Registry.traceIs(trace, 'contour');
  63239. var zsmooth = isContour ? 'best' : trace.zsmooth;
  63240. // get z dims
  63241. var m = z.length;
  63242. var n = Lib.maxRowLength(z);
  63243. var xrev = false;
  63244. var yrev = false;
  63245. var left, right, temp, top, bottom, i;
  63246. // TODO: if there are multiple overlapping categorical heatmaps,
  63247. // or if we allow category sorting, then the categories may not be
  63248. // sequential... may need to reorder and/or expand z
  63249. // Get edges of png in pixels (xa.c2p() maps axes coordinates to pixel coordinates)
  63250. // figure out if either axis is reversed (y is usually reversed, in pixel coords)
  63251. // also clip the image to maximum 50% outside the visible plot area
  63252. // bigger image lets you pan more naturally, but slows performance.
  63253. // TODO: use low-resolution images outside the visible plot for panning
  63254. // these while loops find the first and last brick bounds that are defined
  63255. // (in case of log of a negative)
  63256. i = 0;
  63257. while(left === undefined && i < x.length - 1) {
  63258. left = xa.c2p(x[i]);
  63259. i++;
  63260. }
  63261. i = x.length - 1;
  63262. while(right === undefined && i > 0) {
  63263. right = xa.c2p(x[i]);
  63264. i--;
  63265. }
  63266. if(right < left) {
  63267. temp = right;
  63268. right = left;
  63269. left = temp;
  63270. xrev = true;
  63271. }
  63272. i = 0;
  63273. while(top === undefined && i < y.length - 1) {
  63274. top = ya.c2p(y[i]);
  63275. i++;
  63276. }
  63277. i = y.length - 1;
  63278. while(bottom === undefined && i > 0) {
  63279. bottom = ya.c2p(y[i]);
  63280. i--;
  63281. }
  63282. if(bottom < top) {
  63283. temp = top;
  63284. top = bottom;
  63285. bottom = temp;
  63286. yrev = true;
  63287. }
  63288. // for contours with heatmap fill, we generate the boundaries based on
  63289. // brick centers but then use the brick edges for drawing the bricks
  63290. if(isContour) {
  63291. xc = x;
  63292. yc = y;
  63293. x = cd0.xfill;
  63294. y = cd0.yfill;
  63295. }
  63296. // make an image that goes at most half a screen off either side, to keep
  63297. // time reasonable when you zoom in. if zsmooth is true/fast, don't worry
  63298. // about this, because zooming doesn't increase number of pixels
  63299. // if zsmooth is best, don't include anything off screen because it takes too long
  63300. if(zsmooth !== 'fast') {
  63301. var extra = zsmooth === 'best' ? 0 : 0.5;
  63302. left = Math.max(-extra * xa._length, left);
  63303. right = Math.min((1 + extra) * xa._length, right);
  63304. top = Math.max(-extra * ya._length, top);
  63305. bottom = Math.min((1 + extra) * ya._length, bottom);
  63306. }
  63307. var imageWidth = Math.round(right - left);
  63308. var imageHeight = Math.round(bottom - top);
  63309. // setup image nodes
  63310. // if image is entirely off-screen, don't even draw it
  63311. var isOffScreen = (imageWidth <= 0 || imageHeight <= 0);
  63312. if(isOffScreen) {
  63313. var noImage = plotGroup.selectAll('image').data([]);
  63314. noImage.exit().remove();
  63315. return;
  63316. }
  63317. // generate image data
  63318. var canvasW, canvasH;
  63319. if(zsmooth === 'fast') {
  63320. canvasW = n;
  63321. canvasH = m;
  63322. } else {
  63323. canvasW = imageWidth;
  63324. canvasH = imageHeight;
  63325. }
  63326. var canvas = document.createElement('canvas');
  63327. canvas.width = canvasW;
  63328. canvas.height = canvasH;
  63329. var context = canvas.getContext('2d');
  63330. var sclFunc = Colorscale.makeColorScaleFunc(
  63331. Colorscale.extractScale(trace, {cLetter: 'z'}),
  63332. { noNumericCheck: true, returnArray: true }
  63333. );
  63334. // map brick boundaries to image pixels
  63335. var xpx,
  63336. ypx;
  63337. if(zsmooth === 'fast') {
  63338. xpx = xrev ?
  63339. function(index) { return n - 1 - index; } :
  63340. Lib.identity;
  63341. ypx = yrev ?
  63342. function(index) { return m - 1 - index; } :
  63343. Lib.identity;
  63344. }
  63345. else {
  63346. xpx = function(index) {
  63347. return Lib.constrain(Math.round(xa.c2p(x[index]) - left),
  63348. 0, imageWidth);
  63349. };
  63350. ypx = function(index) {
  63351. return Lib.constrain(Math.round(ya.c2p(y[index]) - top),
  63352. 0, imageHeight);
  63353. };
  63354. }
  63355. // build the pixel map brick-by-brick
  63356. // cruise through z-matrix row-by-row
  63357. // build a brick at each z-matrix value
  63358. var yi = ypx(0);
  63359. var yb = [yi, yi];
  63360. var xbi = xrev ? 0 : 1;
  63361. var ybi = yrev ? 0 : 1;
  63362. // for collecting an average luminosity of the heatmap
  63363. var pixcount = 0;
  63364. var rcount = 0;
  63365. var gcount = 0;
  63366. var bcount = 0;
  63367. var xb, j, xi, v, row, c;
  63368. function setColor(v, pixsize) {
  63369. if(v !== undefined) {
  63370. var c = sclFunc(v);
  63371. c[0] = Math.round(c[0]);
  63372. c[1] = Math.round(c[1]);
  63373. c[2] = Math.round(c[2]);
  63374. pixcount += pixsize;
  63375. rcount += c[0] * pixsize;
  63376. gcount += c[1] * pixsize;
  63377. bcount += c[2] * pixsize;
  63378. return c;
  63379. }
  63380. return [0, 0, 0, 0];
  63381. }
  63382. function interpColor(r0, r1, xinterp, yinterp) {
  63383. var z00 = r0[xinterp.bin0];
  63384. if(z00 === undefined) return setColor(undefined, 1);
  63385. var z01 = r0[xinterp.bin1];
  63386. var z10 = r1[xinterp.bin0];
  63387. var z11 = r1[xinterp.bin1];
  63388. var dx = (z01 - z00) || 0;
  63389. var dy = (z10 - z00) || 0;
  63390. var dxy;
  63391. // the bilinear interpolation term needs different calculations
  63392. // for all the different permutations of missing data
  63393. // among the neighbors of the main point, to ensure
  63394. // continuity across brick boundaries.
  63395. if(z01 === undefined) {
  63396. if(z11 === undefined) dxy = 0;
  63397. else if(z10 === undefined) dxy = 2 * (z11 - z00);
  63398. else dxy = (2 * z11 - z10 - z00) * 2 / 3;
  63399. }
  63400. else if(z11 === undefined) {
  63401. if(z10 === undefined) dxy = 0;
  63402. else dxy = (2 * z00 - z01 - z10) * 2 / 3;
  63403. }
  63404. else if(z10 === undefined) dxy = (2 * z11 - z01 - z00) * 2 / 3;
  63405. else dxy = (z11 + z00 - z01 - z10);
  63406. return setColor(z00 + xinterp.frac * dx + yinterp.frac * (dy + xinterp.frac * dxy));
  63407. }
  63408. if(zsmooth) { // best or fast, works fastest with imageData
  63409. var pxIndex = 0;
  63410. var pixels;
  63411. try {
  63412. pixels = new Uint8Array(imageWidth * imageHeight * 4);
  63413. } catch(e) {
  63414. pixels = new Array(imageWidth * imageHeight * 4);
  63415. }
  63416. if(zsmooth === 'best') {
  63417. var xForPx = xc || x;
  63418. var yForPx = yc || y;
  63419. var xPixArray = new Array(xForPx.length);
  63420. var yPixArray = new Array(yForPx.length);
  63421. var xinterpArray = new Array(imageWidth);
  63422. var findInterpX = xc ? findInterpFromCenters : findInterp;
  63423. var findInterpY = yc ? findInterpFromCenters : findInterp;
  63424. var yinterp, r0, r1;
  63425. // first make arrays of x and y pixel locations of brick boundaries
  63426. for(i = 0; i < xForPx.length; i++) xPixArray[i] = Math.round(xa.c2p(xForPx[i]) - left);
  63427. for(i = 0; i < yForPx.length; i++) yPixArray[i] = Math.round(ya.c2p(yForPx[i]) - top);
  63428. // then make arrays of interpolations
  63429. // (bin0=closest, bin1=next, frac=fractional dist.)
  63430. for(i = 0; i < imageWidth; i++) xinterpArray[i] = findInterpX(i, xPixArray);
  63431. // now do the interpolations and fill the png
  63432. for(j = 0; j < imageHeight; j++) {
  63433. yinterp = findInterpY(j, yPixArray);
  63434. r0 = z[yinterp.bin0];
  63435. r1 = z[yinterp.bin1];
  63436. for(i = 0; i < imageWidth; i++, pxIndex += 4) {
  63437. c = interpColor(r0, r1, xinterpArray[i], yinterp);
  63438. putColor(pixels, pxIndex, c);
  63439. }
  63440. }
  63441. }
  63442. else { // zsmooth = fast
  63443. for(j = 0; j < m; j++) {
  63444. row = z[j];
  63445. yb = ypx(j);
  63446. for(i = 0; i < imageWidth; i++) {
  63447. c = setColor(row[i], 1);
  63448. pxIndex = (yb * imageWidth + xpx(i)) * 4;
  63449. putColor(pixels, pxIndex, c);
  63450. }
  63451. }
  63452. }
  63453. var imageData = context.createImageData(imageWidth, imageHeight);
  63454. try {
  63455. imageData.data.set(pixels);
  63456. } catch(e) {
  63457. var pxArray = imageData.data;
  63458. var dlen = pxArray.length;
  63459. for(j = 0; j < dlen; j ++) {
  63460. pxArray[j] = pixels[j];
  63461. }
  63462. }
  63463. context.putImageData(imageData, 0, 0);
  63464. } else { // zsmooth = false -> filling potentially large bricks works fastest with fillRect
  63465. // gaps do not need to be exact integers, but if they *are* we will get
  63466. // cleaner edges by rounding at least one edge
  63467. var xGap = trace.xgap;
  63468. var yGap = trace.ygap;
  63469. var xGapLeft = Math.floor(xGap / 2);
  63470. var yGapTop = Math.floor(yGap / 2);
  63471. for(j = 0; j < m; j++) {
  63472. row = z[j];
  63473. yb.reverse();
  63474. yb[ybi] = ypx(j + 1);
  63475. if(yb[0] === yb[1] || yb[0] === undefined || yb[1] === undefined) {
  63476. continue;
  63477. }
  63478. xi = xpx(0);
  63479. xb = [xi, xi];
  63480. for(i = 0; i < n; i++) {
  63481. // build one color brick!
  63482. xb.reverse();
  63483. xb[xbi] = xpx(i + 1);
  63484. if(xb[0] === xb[1] || xb[0] === undefined || xb[1] === undefined) {
  63485. continue;
  63486. }
  63487. v = row[i];
  63488. c = setColor(v, (xb[1] - xb[0]) * (yb[1] - yb[0]));
  63489. context.fillStyle = 'rgba(' + c.join(',') + ')';
  63490. context.fillRect(xb[0] + xGapLeft, yb[0] + yGapTop,
  63491. xb[1] - xb[0] - xGap, yb[1] - yb[0] - yGap);
  63492. }
  63493. }
  63494. }
  63495. rcount = Math.round(rcount / pixcount);
  63496. gcount = Math.round(gcount / pixcount);
  63497. bcount = Math.round(bcount / pixcount);
  63498. var avgColor = tinycolor('rgb(' + rcount + ',' + gcount + ',' + bcount + ')');
  63499. gd._hmpixcount = (gd._hmpixcount||0) + pixcount;
  63500. gd._hmlumcount = (gd._hmlumcount||0) + pixcount * avgColor.getLuminance();
  63501. var image3 = plotGroup.selectAll('image')
  63502. .data(cd);
  63503. image3.enter().append('svg:image').attr({
  63504. xmlns: xmlnsNamespaces.svg,
  63505. preserveAspectRatio: 'none'
  63506. });
  63507. image3.attr({
  63508. height: imageHeight,
  63509. width: imageWidth,
  63510. x: left,
  63511. y: top,
  63512. 'xlink:href': canvas.toDataURL('image/png')
  63513. });
  63514. });
  63515. };
  63516. // get interpolated bin value. Returns {bin0:closest bin, frac:fractional dist to next, bin1:next bin}
  63517. function findInterp(pixel, pixArray) {
  63518. var maxBin = pixArray.length - 2;
  63519. var bin = Lib.constrain(Lib.findBin(pixel, pixArray), 0, maxBin);
  63520. var pix0 = pixArray[bin];
  63521. var pix1 = pixArray[bin + 1];
  63522. var interp = Lib.constrain(bin + (pixel - pix0) / (pix1 - pix0) - 0.5, 0, maxBin);
  63523. var bin0 = Math.round(interp);
  63524. var frac = Math.abs(interp - bin0);
  63525. if(!interp || interp === maxBin || !frac) {
  63526. return {
  63527. bin0: bin0,
  63528. bin1: bin0,
  63529. frac: 0
  63530. };
  63531. }
  63532. return {
  63533. bin0: bin0,
  63534. frac: frac,
  63535. bin1: Math.round(bin0 + frac / (interp - bin0))
  63536. };
  63537. }
  63538. function findInterpFromCenters(pixel, centerPixArray) {
  63539. var maxBin = centerPixArray.length - 1;
  63540. var bin = Lib.constrain(Lib.findBin(pixel, centerPixArray), 0, maxBin);
  63541. var pix0 = centerPixArray[bin];
  63542. var pix1 = centerPixArray[bin + 1];
  63543. var frac = ((pixel - pix0) / (pix1 - pix0)) || 0;
  63544. if(frac <= 0) {
  63545. return {
  63546. bin0: bin,
  63547. bin1: bin,
  63548. frac: 0
  63549. };
  63550. }
  63551. if(frac < 0.5) {
  63552. return {
  63553. bin0: bin,
  63554. bin1: bin + 1,
  63555. frac: frac
  63556. };
  63557. }
  63558. return {
  63559. bin0: bin + 1,
  63560. bin1: bin,
  63561. frac: 1 - frac
  63562. };
  63563. }
  63564. function putColor(pixels, pxIndex, c) {
  63565. pixels[pxIndex] = c[0];
  63566. pixels[pxIndex + 1] = c[1];
  63567. pixels[pxIndex + 2] = c[2];
  63568. pixels[pxIndex + 3] = Math.round(c[3] * 255);
  63569. }
  63570. },{"../../components/colorscale":63,"../../constants/xmlns_namespaces":150,"../../lib":168,"../../registry":257,"d3":16,"tinycolor2":34}],328:[function(_dereq_,module,exports){
  63571. /**
  63572. * Copyright 2012-2019, Plotly, Inc.
  63573. * All rights reserved.
  63574. *
  63575. * This source code is licensed under the MIT license found in the
  63576. * LICENSE file in the root directory of this source tree.
  63577. */
  63578. 'use strict';
  63579. var d3 = _dereq_('d3');
  63580. module.exports = function style(gd) {
  63581. d3.select(gd).selectAll('.hm image')
  63582. .style('opacity', function(d) {
  63583. return d.trace.opacity;
  63584. });
  63585. };
  63586. },{"d3":16}],329:[function(_dereq_,module,exports){
  63587. /**
  63588. * Copyright 2012-2019, Plotly, Inc.
  63589. * All rights reserved.
  63590. *
  63591. * This source code is licensed under the MIT license found in the
  63592. * LICENSE file in the root directory of this source tree.
  63593. */
  63594. 'use strict';
  63595. module.exports = function handleStyleDefaults(traceIn, traceOut, coerce) {
  63596. var zsmooth = coerce('zsmooth');
  63597. if(zsmooth === false) {
  63598. // ensure that xgap and ygap are coerced only when zsmooth allows them to have an effect.
  63599. coerce('xgap');
  63600. coerce('ygap');
  63601. }
  63602. coerce('zhoverformat');
  63603. };
  63604. },{}],330:[function(_dereq_,module,exports){
  63605. /**
  63606. * Copyright 2012-2019, Plotly, Inc.
  63607. * All rights reserved.
  63608. *
  63609. * This source code is licensed under the MIT license found in the
  63610. * LICENSE file in the root directory of this source tree.
  63611. */
  63612. 'use strict';
  63613. var isNumeric = _dereq_('fast-isnumeric');
  63614. var Lib = _dereq_('../../lib');
  63615. var Registry = _dereq_('../../registry');
  63616. module.exports = function handleXYZDefaults(traceIn, traceOut, coerce, layout, xName, yName) {
  63617. var z = coerce('z');
  63618. xName = xName || 'x';
  63619. yName = yName || 'y';
  63620. var x, y;
  63621. if(z === undefined || !z.length) return 0;
  63622. if(Lib.isArray1D(traceIn.z)) {
  63623. x = coerce(xName);
  63624. y = coerce(yName);
  63625. var xlen = Lib.minRowLength(x);
  63626. var ylen = Lib.minRowLength(y);
  63627. // column z must be accompanied by xName and yName arrays
  63628. if(xlen === 0 || ylen === 0) return 0;
  63629. traceOut._length = Math.min(xlen, ylen, z.length);
  63630. }
  63631. else {
  63632. x = coordDefaults(xName, coerce);
  63633. y = coordDefaults(yName, coerce);
  63634. // TODO put z validation elsewhere
  63635. if(!isValidZ(z)) return 0;
  63636. coerce('transpose');
  63637. traceOut._length = null;
  63638. }
  63639. var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
  63640. handleCalendarDefaults(traceIn, traceOut, [xName, yName], layout);
  63641. return true;
  63642. };
  63643. function coordDefaults(coordStr, coerce) {
  63644. var coord = coerce(coordStr);
  63645. var coordType = coord ? coerce(coordStr + 'type', 'array') : 'scaled';
  63646. if(coordType === 'scaled') {
  63647. coerce(coordStr + '0');
  63648. coerce('d' + coordStr);
  63649. }
  63650. return coord;
  63651. }
  63652. function isValidZ(z) {
  63653. var allRowsAreArrays = true;
  63654. var oneRowIsFilled = false;
  63655. var hasOneNumber = false;
  63656. var zi;
  63657. /*
  63658. * Without this step:
  63659. *
  63660. * hasOneNumber = false breaks contour but not heatmap
  63661. * allRowsAreArrays = false breaks contour but not heatmap
  63662. * oneRowIsFilled = false breaks both
  63663. */
  63664. for(var i = 0; i < z.length; i++) {
  63665. zi = z[i];
  63666. if(!Lib.isArrayOrTypedArray(zi)) {
  63667. allRowsAreArrays = false;
  63668. break;
  63669. }
  63670. if(zi.length > 0) oneRowIsFilled = true;
  63671. for(var j = 0; j < zi.length; j++) {
  63672. if(isNumeric(zi[j])) {
  63673. hasOneNumber = true;
  63674. break;
  63675. }
  63676. }
  63677. }
  63678. return (allRowsAreArrays && oneRowIsFilled && hasOneNumber);
  63679. }
  63680. },{"../../lib":168,"../../registry":257,"fast-isnumeric":18}],331:[function(_dereq_,module,exports){
  63681. /**
  63682. * Copyright 2012-2019, Plotly, Inc.
  63683. * All rights reserved.
  63684. *
  63685. * This source code is licensed under the MIT license found in the
  63686. * LICENSE file in the root directory of this source tree.
  63687. */
  63688. 'use strict';
  63689. var barAttrs = _dereq_('../bar/attributes');
  63690. var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
  63691. var makeBinAttrs = _dereq_('./bin_attributes');
  63692. var constants = _dereq_('./constants');
  63693. module.exports = {
  63694. x: {
  63695. valType: 'data_array',
  63696. editType: 'calc+clearAxisTypes',
  63697. },
  63698. y: {
  63699. valType: 'data_array',
  63700. editType: 'calc+clearAxisTypes',
  63701. },
  63702. text: barAttrs.text,
  63703. orientation: barAttrs.orientation,
  63704. histfunc: {
  63705. valType: 'enumerated',
  63706. values: ['count', 'sum', 'avg', 'min', 'max'],
  63707. dflt: 'count',
  63708. editType: 'calc',
  63709. },
  63710. histnorm: {
  63711. valType: 'enumerated',
  63712. values: ['', 'percent', 'probability', 'density', 'probability density'],
  63713. dflt: '',
  63714. editType: 'calc',
  63715. },
  63716. cumulative: {
  63717. enabled: {
  63718. valType: 'boolean',
  63719. dflt: false,
  63720. editType: 'calc',
  63721. },
  63722. direction: {
  63723. valType: 'enumerated',
  63724. values: ['increasing', 'decreasing'],
  63725. dflt: 'increasing',
  63726. editType: 'calc',
  63727. },
  63728. currentbin: {
  63729. valType: 'enumerated',
  63730. values: ['include', 'exclude', 'half'],
  63731. dflt: 'include',
  63732. editType: 'calc',
  63733. },
  63734. editType: 'calc'
  63735. },
  63736. nbinsx: {
  63737. valType: 'integer',
  63738. min: 0,
  63739. dflt: 0,
  63740. editType: 'calc',
  63741. },
  63742. xbins: makeBinAttrs('x', true),
  63743. nbinsy: {
  63744. valType: 'integer',
  63745. min: 0,
  63746. dflt: 0,
  63747. editType: 'calc',
  63748. },
  63749. ybins: makeBinAttrs('y', true),
  63750. autobinx: {
  63751. valType: 'boolean',
  63752. dflt: null,
  63753. editType: 'calc',
  63754. },
  63755. autobiny: {
  63756. valType: 'boolean',
  63757. dflt: null,
  63758. editType: 'calc',
  63759. },
  63760. hovertemplate: hovertemplateAttrs({}, {
  63761. keys: constants.eventDataKeys
  63762. }),
  63763. marker: barAttrs.marker,
  63764. selected: barAttrs.selected,
  63765. unselected: barAttrs.unselected,
  63766. _deprecated: {
  63767. bardir: barAttrs._deprecated.bardir
  63768. }
  63769. };
  63770. },{"../../components/fx/hovertemplate_attributes":89,"../bar/attributes":267,"./bin_attributes":333,"./constants":337}],332:[function(_dereq_,module,exports){
  63771. /**
  63772. * Copyright 2012-2019, Plotly, Inc.
  63773. * All rights reserved.
  63774. *
  63775. * This source code is licensed under the MIT license found in the
  63776. * LICENSE file in the root directory of this source tree.
  63777. */
  63778. 'use strict';
  63779. module.exports = function doAvg(size, counts) {
  63780. var nMax = size.length;
  63781. var total = 0;
  63782. for(var i = 0; i < nMax; i++) {
  63783. if(counts[i]) {
  63784. size[i] /= counts[i];
  63785. total += size[i];
  63786. }
  63787. else size[i] = null;
  63788. }
  63789. return total;
  63790. };
  63791. },{}],333:[function(_dereq_,module,exports){
  63792. /**
  63793. * Copyright 2012-2019, Plotly, Inc.
  63794. * All rights reserved.
  63795. *
  63796. * This source code is licensed under the MIT license found in the
  63797. * LICENSE file in the root directory of this source tree.
  63798. */
  63799. 'use strict';
  63800. module.exports = function makeBinAttrs(axLetter, match) {
  63801. return {
  63802. start: {
  63803. valType: 'any', // for date axes
  63804. editType: 'calc',
  63805. },
  63806. end: {
  63807. valType: 'any', // for date axes
  63808. editType: 'calc',
  63809. },
  63810. size: {
  63811. valType: 'any', // for date axes
  63812. editType: 'calc',
  63813. },
  63814. editType: 'calc'
  63815. };
  63816. };
  63817. },{}],334:[function(_dereq_,module,exports){
  63818. /**
  63819. * Copyright 2012-2019, Plotly, Inc.
  63820. * All rights reserved.
  63821. *
  63822. * This source code is licensed under the MIT license found in the
  63823. * LICENSE file in the root directory of this source tree.
  63824. */
  63825. 'use strict';
  63826. var isNumeric = _dereq_('fast-isnumeric');
  63827. module.exports = {
  63828. count: function(n, i, size) {
  63829. size[n]++;
  63830. return 1;
  63831. },
  63832. sum: function(n, i, size, counterData) {
  63833. var v = counterData[i];
  63834. if(isNumeric(v)) {
  63835. v = Number(v);
  63836. size[n] += v;
  63837. return v;
  63838. }
  63839. return 0;
  63840. },
  63841. avg: function(n, i, size, counterData, counts) {
  63842. var v = counterData[i];
  63843. if(isNumeric(v)) {
  63844. v = Number(v);
  63845. size[n] += v;
  63846. counts[n]++;
  63847. }
  63848. return 0;
  63849. },
  63850. min: function(n, i, size, counterData) {
  63851. var v = counterData[i];
  63852. if(isNumeric(v)) {
  63853. v = Number(v);
  63854. if(!isNumeric(size[n])) {
  63855. size[n] = v;
  63856. return v;
  63857. }
  63858. else if(size[n] > v) {
  63859. var delta = v - size[n];
  63860. size[n] = v;
  63861. return delta;
  63862. }
  63863. }
  63864. return 0;
  63865. },
  63866. max: function(n, i, size, counterData) {
  63867. var v = counterData[i];
  63868. if(isNumeric(v)) {
  63869. v = Number(v);
  63870. if(!isNumeric(size[n])) {
  63871. size[n] = v;
  63872. return v;
  63873. }
  63874. else if(size[n] < v) {
  63875. var delta = v - size[n];
  63876. size[n] = v;
  63877. return delta;
  63878. }
  63879. }
  63880. return 0;
  63881. }
  63882. };
  63883. },{"fast-isnumeric":18}],335:[function(_dereq_,module,exports){
  63884. /**
  63885. * Copyright 2012-2019, Plotly, Inc.
  63886. * All rights reserved.
  63887. *
  63888. * This source code is licensed under the MIT license found in the
  63889. * LICENSE file in the root directory of this source tree.
  63890. */
  63891. 'use strict';
  63892. var numConstants = _dereq_('../../constants/numerical');
  63893. var oneYear = numConstants.ONEAVGYEAR;
  63894. var oneMonth = numConstants.ONEAVGMONTH;
  63895. var oneDay = numConstants.ONEDAY;
  63896. var oneHour = numConstants.ONEHOUR;
  63897. var oneMin = numConstants.ONEMIN;
  63898. var oneSec = numConstants.ONESEC;
  63899. var tickIncrement = _dereq_('../../plots/cartesian/axes').tickIncrement;
  63900. /*
  63901. * make a function that will find rounded bin edges
  63902. * @param {number} leftGap: how far from the left edge of any bin is the closest data value?
  63903. * @param {number} rightGap: how far from the right edge of any bin is the closest data value?
  63904. * @param {Array[number]} binEdges: the actual edge values used in binning
  63905. * @param {object} pa: the position axis
  63906. * @param {string} calendar: the data calendar
  63907. *
  63908. * @return {function(v, isRightEdge)}:
  63909. * find the start (isRightEdge is falsy) or end (truthy) label value for a bin edge `v`
  63910. */
  63911. module.exports = function getBinSpanLabelRound(leftGap, rightGap, binEdges, pa, calendar) {
  63912. // the rounding digit is the largest digit that changes in *all* of 4 regions:
  63913. // - inside the rightGap before binEdges[0] (shifted 10% to the left)
  63914. // - inside the leftGap after binEdges[0] (expanded by 10% of rightGap on each end)
  63915. // - same for binEdges[1]
  63916. var dv0 = -1.1 * rightGap;
  63917. var dv1 = -0.1 * rightGap;
  63918. var dv2 = leftGap - dv1;
  63919. var edge0 = binEdges[0];
  63920. var edge1 = binEdges[1];
  63921. var leftDigit = Math.min(
  63922. biggestDigitChanged(edge0 + dv1, edge0 + dv2, pa, calendar),
  63923. biggestDigitChanged(edge1 + dv1, edge1 + dv2, pa, calendar)
  63924. );
  63925. var rightDigit = Math.min(
  63926. biggestDigitChanged(edge0 + dv0, edge0 + dv1, pa, calendar),
  63927. biggestDigitChanged(edge1 + dv0, edge1 + dv1, pa, calendar)
  63928. );
  63929. // normally we try to make the label for the right edge different from
  63930. // the left edge label, so it's unambiguous which bin gets data on the edge.
  63931. // but if this results in more than 3 extra digits (or for dates, more than
  63932. // 2 fields ie hr&min or min&sec, which is 3600x), it'll be more clutter than
  63933. // useful so keep the label cleaner instead
  63934. var digit, disambiguateEdges;
  63935. if(leftDigit > rightDigit && rightDigit < Math.abs(edge1 - edge0) / 4000) {
  63936. digit = leftDigit;
  63937. disambiguateEdges = false;
  63938. }
  63939. else {
  63940. digit = Math.min(leftDigit, rightDigit);
  63941. disambiguateEdges = true;
  63942. }
  63943. if(pa.type === 'date' && digit > oneDay) {
  63944. var dashExclude = (digit === oneYear) ? 1 : 6;
  63945. var increment = (digit === oneYear) ? 'M12' : 'M1';
  63946. return function(v, isRightEdge) {
  63947. var dateStr = pa.c2d(v, oneYear, calendar);
  63948. var dashPos = dateStr.indexOf('-', dashExclude);
  63949. if(dashPos > 0) dateStr = dateStr.substr(0, dashPos);
  63950. var roundedV = pa.d2c(dateStr, 0, calendar);
  63951. if(roundedV < v) {
  63952. var nextV = tickIncrement(roundedV, increment, false, calendar);
  63953. if((roundedV + nextV) / 2 < v + leftGap) roundedV = nextV;
  63954. }
  63955. if(isRightEdge && disambiguateEdges) {
  63956. return tickIncrement(roundedV, increment, true, calendar);
  63957. }
  63958. return roundedV;
  63959. };
  63960. }
  63961. return function(v, isRightEdge) {
  63962. var roundedV = digit * Math.round(v / digit);
  63963. // if we rounded down and we could round up and still be < leftGap
  63964. // (or what leftGap values round to), do that
  63965. if(roundedV + (digit / 10) < v && roundedV + (digit * 0.9) < v + leftGap) {
  63966. roundedV += digit;
  63967. }
  63968. // finally for the right edge back off one digit - but only if we can do that
  63969. // and not clip off any data that's potentially in the bin
  63970. if(isRightEdge && disambiguateEdges) {
  63971. roundedV -= digit;
  63972. }
  63973. return roundedV;
  63974. };
  63975. };
  63976. /*
  63977. * Find the largest digit that changes within a (calcdata) region [v1, v2]
  63978. * if dates, "digit" means date/time part when it's bigger than a second
  63979. * returns the unit value to round to this digit, eg 0.01 to round to hundredths, or
  63980. * 100 to round to hundreds. returns oneMonth or oneYear for month or year rounding,
  63981. * so that Math.min will work, rather than 'M1' and 'M12'
  63982. */
  63983. function biggestDigitChanged(v1, v2, pa, calendar) {
  63984. // are we crossing zero? can't say anything.
  63985. // in principle this doesn't apply to dates but turns out this doesn't matter.
  63986. if(v1 * v2 <= 0) return Infinity;
  63987. var dv = Math.abs(v2 - v1);
  63988. var isDate = pa.type === 'date';
  63989. var digit = biggestGuaranteedDigitChanged(dv, isDate);
  63990. // see if a larger digit also changed
  63991. for(var i = 0; i < 10; i++) {
  63992. // numbers: next digit needs to be >10x but <100x then gets rounded down.
  63993. // dates: next digit can be as much as 60x (then rounded down)
  63994. var nextDigit = biggestGuaranteedDigitChanged(digit * 80, isDate);
  63995. // if we get to years, the chain stops
  63996. if(digit === nextDigit) break;
  63997. if(didDigitChange(nextDigit, v1, v2, isDate, pa, calendar)) digit = nextDigit;
  63998. else break;
  63999. }
  64000. return digit;
  64001. }
  64002. /*
  64003. * Find the largest digit that *definitely* changes in a region [v, v + dv] for any v
  64004. * for nonuniform date regions (months/years) pick the largest
  64005. */
  64006. function biggestGuaranteedDigitChanged(dv, isDate) {
  64007. if(isDate && dv > oneSec) {
  64008. // this is supposed to be the biggest *guaranteed* change
  64009. // so compare to the longest month and year across any calendar,
  64010. // and we'll iterate back up later
  64011. // note: does not support rounding larger than one year. We could add
  64012. // that if anyone wants it, but seems unusual and not strictly necessary.
  64013. if(dv > oneDay) {
  64014. if(dv > oneYear * 1.1) return oneYear;
  64015. if(dv > oneMonth * 1.1) return oneMonth;
  64016. return oneDay;
  64017. }
  64018. if(dv > oneHour) return oneHour;
  64019. if(dv > oneMin) return oneMin;
  64020. return oneSec;
  64021. }
  64022. return Math.pow(10, Math.floor(Math.log(dv) / Math.LN10));
  64023. }
  64024. function didDigitChange(digit, v1, v2, isDate, pa, calendar) {
  64025. if(isDate && digit > oneDay) {
  64026. var dateParts1 = dateParts(v1, pa, calendar);
  64027. var dateParts2 = dateParts(v2, pa, calendar);
  64028. var parti = (digit === oneYear) ? 0 : 1;
  64029. return dateParts1[parti] !== dateParts2[parti];
  64030. }
  64031. return Math.floor(v2 / digit) - Math.floor(v1 / digit) > 0.1;
  64032. }
  64033. function dateParts(v, pa, calendar) {
  64034. var parts = pa.c2d(v, oneYear, calendar).split('-');
  64035. if(parts[0] === '') {
  64036. parts.unshift();
  64037. parts[0] = '-' + parts[0];
  64038. }
  64039. return parts;
  64040. }
  64041. },{"../../constants/numerical":149,"../../plots/cartesian/axes":212}],336:[function(_dereq_,module,exports){
  64042. /**
  64043. * Copyright 2012-2019, Plotly, Inc.
  64044. * All rights reserved.
  64045. *
  64046. * This source code is licensed under the MIT license found in the
  64047. * LICENSE file in the root directory of this source tree.
  64048. */
  64049. 'use strict';
  64050. var isNumeric = _dereq_('fast-isnumeric');
  64051. var Lib = _dereq_('../../lib');
  64052. var Axes = _dereq_('../../plots/cartesian/axes');
  64053. var arraysToCalcdata = _dereq_('../bar/arrays_to_calcdata');
  64054. var binFunctions = _dereq_('./bin_functions');
  64055. var normFunctions = _dereq_('./norm_functions');
  64056. var doAvg = _dereq_('./average');
  64057. var getBinSpanLabelRound = _dereq_('./bin_label_vals');
  64058. module.exports = function calc(gd, trace) {
  64059. // ignore as much processing as possible (and including in autorange) if not visible
  64060. if(trace.visible !== true) return;
  64061. // depending on orientation, set position and size axes and data ranges
  64062. // note: this logic for choosing orientation is duplicated in graph_obj->setstyles
  64063. var pos = [];
  64064. var size = [];
  64065. var pa = Axes.getFromId(gd, trace.orientation === 'h' ?
  64066. (trace.yaxis || 'y') : (trace.xaxis || 'x'));
  64067. var mainData = trace.orientation === 'h' ? 'y' : 'x';
  64068. var counterData = {x: 'y', y: 'x'}[mainData];
  64069. var calendar = trace[mainData + 'calendar'];
  64070. var cumulativeSpec = trace.cumulative;
  64071. var i;
  64072. var binsAndPos = calcAllAutoBins(gd, trace, pa, mainData);
  64073. var binSpec = binsAndPos[0];
  64074. var pos0 = binsAndPos[1];
  64075. var nonuniformBins = typeof binSpec.size === 'string';
  64076. var binEdges = [];
  64077. var bins = nonuniformBins ? binEdges : binSpec;
  64078. // make the empty bin array
  64079. var inc = [];
  64080. var counts = [];
  64081. var inputPoints = [];
  64082. var total = 0;
  64083. var norm = trace.histnorm;
  64084. var func = trace.histfunc;
  64085. var densityNorm = norm.indexOf('density') !== -1;
  64086. var i2, binEnd, n;
  64087. if(cumulativeSpec.enabled && densityNorm) {
  64088. // we treat "cumulative" like it means "integral" if you use a density norm,
  64089. // which in the end means it's the same as without "density"
  64090. norm = norm.replace(/ ?density$/, '');
  64091. densityNorm = false;
  64092. }
  64093. var extremeFunc = func === 'max' || func === 'min';
  64094. var sizeInit = extremeFunc ? null : 0;
  64095. var binFunc = binFunctions.count;
  64096. var normFunc = normFunctions[norm];
  64097. var isAvg = false;
  64098. var pr2c = function(v) { return pa.r2c(v, 0, calendar); };
  64099. var rawCounterData;
  64100. if(Lib.isArrayOrTypedArray(trace[counterData]) && func !== 'count') {
  64101. rawCounterData = trace[counterData];
  64102. isAvg = func === 'avg';
  64103. binFunc = binFunctions[func];
  64104. }
  64105. // create the bins (and any extra arrays needed)
  64106. // assume more than 1e6 bins is an error, so we don't crash the browser
  64107. i = pr2c(binSpec.start);
  64108. // decrease end a little in case of rounding errors
  64109. binEnd = pr2c(binSpec.end) + (i - Axes.tickIncrement(i, binSpec.size, false, calendar)) / 1e6;
  64110. while(i < binEnd && pos.length < 1e6) {
  64111. i2 = Axes.tickIncrement(i, binSpec.size, false, calendar);
  64112. pos.push((i + i2) / 2);
  64113. size.push(sizeInit);
  64114. inputPoints.push([]);
  64115. // nonuniform bins (like months) we need to search,
  64116. // rather than straight calculate the bin we're in
  64117. binEdges.push(i);
  64118. // nonuniform bins also need nonuniform normalization factors
  64119. if(densityNorm) inc.push(1 / (i2 - i));
  64120. if(isAvg) counts.push(0);
  64121. // break to avoid infinite loops
  64122. if(i2 <= i) break;
  64123. i = i2;
  64124. }
  64125. binEdges.push(i);
  64126. // for date axes we need bin bounds to be calcdata. For nonuniform bins
  64127. // we already have this, but uniform with start/end/size they're still strings.
  64128. if(!nonuniformBins && pa.type === 'date') {
  64129. bins = {
  64130. start: pr2c(bins.start),
  64131. end: pr2c(bins.end),
  64132. size: bins.size
  64133. };
  64134. }
  64135. // bin the data
  64136. // and make histogram-specific pt-number-to-cd-index map object
  64137. var nMax = size.length;
  64138. var uniqueValsPerBin = true;
  64139. var leftGap = Infinity;
  64140. var rightGap = Infinity;
  64141. var ptNumber2cdIndex = {};
  64142. for(i = 0; i < pos0.length; i++) {
  64143. var posi = pos0[i];
  64144. n = Lib.findBin(posi, bins);
  64145. if(n >= 0 && n < nMax) {
  64146. total += binFunc(n, i, size, rawCounterData, counts);
  64147. if(uniqueValsPerBin && inputPoints[n].length && posi !== pos0[inputPoints[n][0]]) {
  64148. uniqueValsPerBin = false;
  64149. }
  64150. inputPoints[n].push(i);
  64151. ptNumber2cdIndex[i] = n;
  64152. leftGap = Math.min(leftGap, posi - binEdges[n]);
  64153. rightGap = Math.min(rightGap, binEdges[n + 1] - posi);
  64154. }
  64155. }
  64156. var roundFn;
  64157. if(!uniqueValsPerBin) {
  64158. roundFn = getBinSpanLabelRound(leftGap, rightGap, binEdges, pa, calendar);
  64159. }
  64160. // average and/or normalize the data, if needed
  64161. if(isAvg) total = doAvg(size, counts);
  64162. if(normFunc) normFunc(size, total, inc);
  64163. // after all normalization etc, now we can accumulate if desired
  64164. if(cumulativeSpec.enabled) cdf(size, cumulativeSpec.direction, cumulativeSpec.currentbin);
  64165. var seriesLen = Math.min(pos.length, size.length);
  64166. var cd = [];
  64167. var firstNonzero = 0;
  64168. var lastNonzero = seriesLen - 1;
  64169. // look for empty bins at the ends to remove, so autoscale omits them
  64170. for(i = 0; i < seriesLen; i++) {
  64171. if(size[i]) {
  64172. firstNonzero = i;
  64173. break;
  64174. }
  64175. }
  64176. for(i = seriesLen - 1; i >= firstNonzero; i--) {
  64177. if(size[i]) {
  64178. lastNonzero = i;
  64179. break;
  64180. }
  64181. }
  64182. // create the "calculated data" to plot
  64183. for(i = firstNonzero; i <= lastNonzero; i++) {
  64184. if((isNumeric(pos[i]) && isNumeric(size[i]))) {
  64185. var cdi = {
  64186. p: pos[i],
  64187. s: size[i],
  64188. b: 0
  64189. };
  64190. // setup hover and event data fields,
  64191. // N.B. pts and "hover" positions ph0/ph1 don't seem to make much sense
  64192. // for cumulative distributions
  64193. if(!cumulativeSpec.enabled) {
  64194. cdi.pts = inputPoints[i];
  64195. if(uniqueValsPerBin) {
  64196. cdi.ph0 = cdi.ph1 = (inputPoints[i].length) ? pos0[inputPoints[i][0]] : pos[i];
  64197. }
  64198. else {
  64199. cdi.ph0 = roundFn(binEdges[i]);
  64200. cdi.ph1 = roundFn(binEdges[i + 1], true);
  64201. }
  64202. }
  64203. cd.push(cdi);
  64204. }
  64205. }
  64206. if(cd.length === 1) {
  64207. // when we collapse to a single bin, calcdata no longer describes bin size
  64208. // so we need to explicitly specify it
  64209. cd[0].width1 = Axes.tickIncrement(cd[0].p, binSpec.size, false, calendar) - cd[0].p;
  64210. }
  64211. arraysToCalcdata(cd, trace);
  64212. if(Lib.isArrayOrTypedArray(trace.selectedpoints)) {
  64213. Lib.tagSelected(cd, trace, ptNumber2cdIndex);
  64214. }
  64215. return cd;
  64216. };
  64217. /*
  64218. * calcAllAutoBins: we want all histograms on the same axes to share bin specs
  64219. * if they're grouped or stacked. If the user has explicitly specified differing
  64220. * bin specs, there's nothing we can do, but if possible we will try to use the
  64221. * smallest bins of any of the auto values for all histograms grouped/stacked
  64222. * together.
  64223. */
  64224. function calcAllAutoBins(gd, trace, pa, mainData, _overlayEdgeCase) {
  64225. var binAttr = mainData + 'bins';
  64226. var fullLayout = gd._fullLayout;
  64227. var isOverlay = fullLayout.barmode === 'overlay';
  64228. var i, traces, tracei, calendar, pos0, autoVals, cumulativeSpec;
  64229. var cleanBound = (pa.type === 'date') ?
  64230. function(v) { return (v || v === 0) ? Lib.cleanDate(v, null, pa.calendar) : null; } :
  64231. function(v) { return isNumeric(v) ? Number(v) : null; };
  64232. function setBound(attr, bins, newBins) {
  64233. if(bins[attr + 'Found']) {
  64234. bins[attr] = cleanBound(bins[attr]);
  64235. if(bins[attr] === null) bins[attr] = newBins[attr];
  64236. }
  64237. else {
  64238. autoVals[attr] = bins[attr] = newBins[attr];
  64239. Lib.nestedProperty(traces[0], binAttr + '.' + attr).set(newBins[attr]);
  64240. }
  64241. }
  64242. var binOpts = fullLayout._histogramBinOpts[trace._groupName];
  64243. // all but the first trace in this group has already been marked finished
  64244. // clear this flag, so next time we run calc we will run autobin again
  64245. if(trace._autoBinFinished) {
  64246. delete trace._autoBinFinished;
  64247. }
  64248. else {
  64249. traces = binOpts.traces;
  64250. var sizeFound = binOpts.sizeFound;
  64251. var allPos = [];
  64252. autoVals = traces[0]._autoBin = {};
  64253. // Note: we're including `legendonly` traces here for autobin purposes,
  64254. // so that showing & hiding from the legend won't affect bins.
  64255. // But this complicates things a bit since those traces don't `calc`,
  64256. // hence `isFirstVisible`.
  64257. var isFirstVisible = true;
  64258. for(i = 0; i < traces.length; i++) {
  64259. tracei = traces[i];
  64260. if(tracei.visible) {
  64261. pos0 = tracei._pos0 = pa.makeCalcdata(tracei, mainData);
  64262. allPos = Lib.concat(allPos, pos0);
  64263. delete tracei._autoBinFinished;
  64264. if(trace.visible === true) {
  64265. if(isFirstVisible) {
  64266. isFirstVisible = false;
  64267. }
  64268. else {
  64269. delete tracei._autoBin;
  64270. tracei._autoBinFinished = 1;
  64271. }
  64272. }
  64273. }
  64274. }
  64275. calendar = traces[0][mainData + 'calendar'];
  64276. var newBinSpec = Axes.autoBin(
  64277. allPos, pa, binOpts.nbins, false, calendar, sizeFound && binOpts.size);
  64278. // Edge case: single-valued histogram overlaying others
  64279. // Use them all together to calculate the bin size for the single-valued one
  64280. if(isOverlay && newBinSpec._dataSpan === 0 &&
  64281. pa.type !== 'category' && pa.type !== 'multicategory') {
  64282. // Several single-valued histograms! Stop infinite recursion,
  64283. // just return an extra flag that tells handleSingleValueOverlays
  64284. // to sort out this trace too
  64285. if(_overlayEdgeCase) return [newBinSpec, pos0, true];
  64286. newBinSpec = handleSingleValueOverlays(gd, trace, pa, mainData, binAttr);
  64287. }
  64288. // adjust for CDF edge cases
  64289. cumulativeSpec = tracei.cumulative;
  64290. if(cumulativeSpec.enabled && (cumulativeSpec.currentbin !== 'include')) {
  64291. if(cumulativeSpec.direction === 'decreasing') {
  64292. newBinSpec.start = pa.c2r(Axes.tickIncrement(
  64293. pa.r2c(newBinSpec.start, 0, calendar),
  64294. newBinSpec.size, true, calendar
  64295. ));
  64296. }
  64297. else {
  64298. newBinSpec.end = pa.c2r(Axes.tickIncrement(
  64299. pa.r2c(newBinSpec.end, 0, calendar),
  64300. newBinSpec.size, false, calendar
  64301. ));
  64302. }
  64303. }
  64304. binOpts.size = newBinSpec.size;
  64305. if(!sizeFound) {
  64306. autoVals.size = newBinSpec.size;
  64307. Lib.nestedProperty(traces[0], binAttr + '.size').set(newBinSpec.size);
  64308. }
  64309. setBound('start', binOpts, newBinSpec);
  64310. setBound('end', binOpts, newBinSpec);
  64311. }
  64312. pos0 = trace._pos0;
  64313. delete trace._pos0;
  64314. // Each trace can specify its own start/end, or if omitted
  64315. // we ensure they're beyond the bounds of this trace's data,
  64316. // and we need to make sure start is aligned with the main start
  64317. var traceInputBins = trace._input[binAttr] || {};
  64318. var traceBinOptsCalc = Lib.extendFlat({}, binOpts);
  64319. var mainStart = binOpts.start;
  64320. var startIn = pa.r2l(traceInputBins.start);
  64321. var hasStart = startIn !== undefined;
  64322. if((binOpts.startFound || hasStart) && startIn !== pa.r2l(mainStart)) {
  64323. // We have an explicit start to reconcile across traces
  64324. // if this trace has an explicit start, shift it down to a bin edge
  64325. // if another trace had an explicit start, shift it down to a
  64326. // bin edge past our data
  64327. var traceStart = hasStart ?
  64328. startIn :
  64329. Lib.aggNums(Math.min, null, pos0);
  64330. var dummyAx = {
  64331. type: (pa.type === 'category' || pa.type === 'multicategory') ? 'linear' : pa.type,
  64332. r2l: pa.r2l,
  64333. dtick: binOpts.size,
  64334. tick0: mainStart,
  64335. calendar: calendar,
  64336. range: ([traceStart, Axes.tickIncrement(traceStart, binOpts.size, false, calendar)]).map(pa.l2r)
  64337. };
  64338. var newStart = Axes.tickFirst(dummyAx);
  64339. if(newStart > pa.r2l(traceStart)) {
  64340. newStart = Axes.tickIncrement(newStart, binOpts.size, true, calendar);
  64341. }
  64342. traceBinOptsCalc.start = pa.l2r(newStart);
  64343. if(!hasStart) Lib.nestedProperty(trace, binAttr + '.start').set(traceBinOptsCalc.start);
  64344. }
  64345. var mainEnd = binOpts.end;
  64346. var endIn = pa.r2l(traceInputBins.end);
  64347. var hasEnd = endIn !== undefined;
  64348. if((binOpts.endFound || hasEnd) && endIn !== pa.r2l(mainEnd)) {
  64349. // Reconciling an explicit end is easier, as it doesn't need to
  64350. // match bin edges
  64351. var traceEnd = hasEnd ?
  64352. endIn :
  64353. Lib.aggNums(Math.max, null, pos0);
  64354. traceBinOptsCalc.end = pa.l2r(traceEnd);
  64355. if(!hasEnd) Lib.nestedProperty(trace, binAttr + '.start').set(traceBinOptsCalc.end);
  64356. }
  64357. // Backward compatibility for one-time autobinning.
  64358. // autobin: true is handled in cleanData, but autobin: false
  64359. // needs to be here where we have determined the values.
  64360. var autoBinAttr = 'autobin' + mainData;
  64361. if(trace._input[autoBinAttr] === false) {
  64362. trace._input[binAttr] = Lib.extendFlat({}, trace[binAttr] || {});
  64363. delete trace._input[autoBinAttr];
  64364. delete trace[autoBinAttr];
  64365. }
  64366. return [traceBinOptsCalc, pos0];
  64367. }
  64368. /*
  64369. * Adjust single-value histograms in overlay mode to make as good a
  64370. * guess as we can at autobin values the user would like.
  64371. *
  64372. * Returns the binSpec for the trace that sparked all this
  64373. */
  64374. function handleSingleValueOverlays(gd, trace, pa, mainData, binAttr) {
  64375. var overlaidTraceGroup = getConnectedHistograms(gd, trace);
  64376. var pastThisTrace = false;
  64377. var minSize = Infinity;
  64378. var singleValuedTraces = [trace];
  64379. var i, tracei;
  64380. // first collect all the:
  64381. // - min bin size from all multi-valued traces
  64382. // - single-valued traces
  64383. for(i = 0; i < overlaidTraceGroup.length; i++) {
  64384. tracei = overlaidTraceGroup[i];
  64385. if(tracei === trace) pastThisTrace = true;
  64386. else if(!pastThisTrace) {
  64387. // This trace has already had its autobins calculated
  64388. // (so must not have been single-valued).
  64389. minSize = Math.min(minSize, tracei[binAttr].size);
  64390. }
  64391. else {
  64392. var resulti = calcAllAutoBins(gd, tracei, pa, mainData, true);
  64393. var binSpeci = resulti[0];
  64394. var isSingleValued = resulti[2];
  64395. // so we can use this result when we get to tracei in the normal
  64396. // course of events, mark it as done and put _pos0 back
  64397. tracei._autoBinFinished = 1;
  64398. tracei._pos0 = resulti[1];
  64399. if(isSingleValued) {
  64400. singleValuedTraces.push(tracei);
  64401. }
  64402. else {
  64403. minSize = Math.min(minSize, binSpeci.size);
  64404. }
  64405. }
  64406. }
  64407. // find the real data values for each single-valued trace
  64408. // hunt through pos0 for the first valid value
  64409. var dataVals = new Array(singleValuedTraces.length);
  64410. for(i = 0; i < singleValuedTraces.length; i++) {
  64411. var pos0 = singleValuedTraces[i]._pos0;
  64412. for(var j = 0; j < pos0.length; j++) {
  64413. if(pos0[j] !== undefined) {
  64414. dataVals[i] = pos0[j];
  64415. break;
  64416. }
  64417. }
  64418. }
  64419. // are ALL traces are single-valued? use the min difference between
  64420. // all of their values (which defaults to 1 if there's still only one)
  64421. if(!isFinite(minSize)) {
  64422. minSize = Lib.distinctVals(dataVals).minDiff;
  64423. }
  64424. // now apply the min size we found to all single-valued traces
  64425. for(i = 0; i < singleValuedTraces.length; i++) {
  64426. tracei = singleValuedTraces[i];
  64427. var calendar = tracei[mainData + 'calendar'];
  64428. tracei._input[binAttr] = tracei[binAttr] = {
  64429. start: pa.c2r(dataVals[i] - minSize / 2, 0, calendar),
  64430. end: pa.c2r(dataVals[i] + minSize / 2, 0, calendar),
  64431. size: minSize
  64432. };
  64433. }
  64434. return trace[binAttr];
  64435. }
  64436. /*
  64437. * Return an array of histograms that share axes and orientation.
  64438. *
  64439. * Only considers histograms. In principle we could include bars in a
  64440. * similar way to how we do manually binned histograms, though this
  64441. * would have tons of edge cases and value judgments to make.
  64442. */
  64443. function getConnectedHistograms(gd, trace) {
  64444. var xid = trace.xaxis;
  64445. var yid = trace.yaxis;
  64446. var orientation = trace.orientation;
  64447. var out = [];
  64448. var fullData = gd._fullData;
  64449. for(var i = 0; i < fullData.length; i++) {
  64450. var tracei = fullData[i];
  64451. if(tracei.type === 'histogram' &&
  64452. tracei.visible === true &&
  64453. tracei.orientation === orientation &&
  64454. tracei.xaxis === xid && tracei.yaxis === yid
  64455. ) {
  64456. out.push(tracei);
  64457. }
  64458. }
  64459. return out;
  64460. }
  64461. function cdf(size, direction, currentBin) {
  64462. var i, vi, prevSum;
  64463. function firstHalfPoint(i) {
  64464. prevSum = size[i];
  64465. size[i] /= 2;
  64466. }
  64467. function nextHalfPoint(i) {
  64468. vi = size[i];
  64469. size[i] = prevSum + vi / 2;
  64470. prevSum += vi;
  64471. }
  64472. if(currentBin === 'half') {
  64473. if(direction === 'increasing') {
  64474. firstHalfPoint(0);
  64475. for(i = 1; i < size.length; i++) {
  64476. nextHalfPoint(i);
  64477. }
  64478. }
  64479. else {
  64480. firstHalfPoint(size.length - 1);
  64481. for(i = size.length - 2; i >= 0; i--) {
  64482. nextHalfPoint(i);
  64483. }
  64484. }
  64485. }
  64486. else if(direction === 'increasing') {
  64487. for(i = 1; i < size.length; i++) {
  64488. size[i] += size[i - 1];
  64489. }
  64490. // 'exclude' is identical to 'include' just shifted one bin over
  64491. if(currentBin === 'exclude') {
  64492. size.unshift(0);
  64493. size.pop();
  64494. }
  64495. }
  64496. else {
  64497. for(i = size.length - 2; i >= 0; i--) {
  64498. size[i] += size[i + 1];
  64499. }
  64500. if(currentBin === 'exclude') {
  64501. size.push(0);
  64502. size.shift();
  64503. }
  64504. }
  64505. }
  64506. },{"../../lib":168,"../../plots/cartesian/axes":212,"../bar/arrays_to_calcdata":266,"./average":332,"./bin_functions":334,"./bin_label_vals":335,"./norm_functions":343,"fast-isnumeric":18}],337:[function(_dereq_,module,exports){
  64507. /**
  64508. * Copyright 2012-2019, Plotly, Inc.
  64509. * All rights reserved.
  64510. *
  64511. * This source code is licensed under the MIT license found in the
  64512. * LICENSE file in the root directory of this source tree.
  64513. */
  64514. 'use strict';
  64515. module.exports = {
  64516. eventDataKeys: ['binNumber']
  64517. };
  64518. },{}],338:[function(_dereq_,module,exports){
  64519. /**
  64520. * Copyright 2012-2019, Plotly, Inc.
  64521. * All rights reserved.
  64522. *
  64523. * This source code is licensed under the MIT license found in the
  64524. * LICENSE file in the root directory of this source tree.
  64525. */
  64526. 'use strict';
  64527. var Lib = _dereq_('../../lib');
  64528. var nestedProperty = Lib.nestedProperty;
  64529. var attributes = _dereq_('./attributes');
  64530. var BINATTRS = {
  64531. x: [
  64532. {aStr: 'xbins.start', name: 'start'},
  64533. {aStr: 'xbins.end', name: 'end'},
  64534. {aStr: 'xbins.size', name: 'size'},
  64535. {aStr: 'nbinsx', name: 'nbins'}
  64536. ],
  64537. y: [
  64538. {aStr: 'ybins.start', name: 'start'},
  64539. {aStr: 'ybins.end', name: 'end'},
  64540. {aStr: 'ybins.size', name: 'size'},
  64541. {aStr: 'nbinsy', name: 'nbins'}
  64542. ]
  64543. };
  64544. // handle bin attrs and relink auto-determined values so fullData is complete
  64545. module.exports = function crossTraceDefaults(fullData, fullLayout) {
  64546. var allBinOpts = fullLayout._histogramBinOpts = {};
  64547. var isOverlay = fullLayout.barmode === 'overlay';
  64548. var i, j, traceOut, traceIn, binDirection, group, binOpts;
  64549. function coerce(attr) {
  64550. return Lib.coerce(traceOut._input, traceOut, attributes, attr);
  64551. }
  64552. for(i = 0; i < fullData.length; i++) {
  64553. traceOut = fullData[i];
  64554. if(traceOut.type !== 'histogram') continue;
  64555. // TODO: this shouldn't be relinked as it's only used within calc
  64556. // https://github.com/plotly/plotly.js/issues/749
  64557. delete traceOut._autoBinFinished;
  64558. binDirection = traceOut.orientation === 'v' ? 'x' : 'y';
  64559. // in overlay mode make a separate group for each trace
  64560. // otherwise collect all traces of the same subplot & orientation
  64561. group = isOverlay ? traceOut.uid : (traceOut.xaxis + traceOut.yaxis + binDirection);
  64562. traceOut._groupName = group;
  64563. binOpts = allBinOpts[group];
  64564. if(binOpts) {
  64565. binOpts.traces.push(traceOut);
  64566. }
  64567. else {
  64568. binOpts = allBinOpts[group] = {
  64569. traces: [traceOut],
  64570. direction: binDirection
  64571. };
  64572. }
  64573. }
  64574. for(group in allBinOpts) {
  64575. binOpts = allBinOpts[group];
  64576. binDirection = binOpts.direction;
  64577. var attrs = BINATTRS[binDirection];
  64578. for(j = 0; j < attrs.length; j++) {
  64579. var attrSpec = attrs[j];
  64580. var attr = attrSpec.name;
  64581. // nbins(x|y) is moot if we have a size. This depends on
  64582. // nbins coming after size in binAttrs.
  64583. if(attr === 'nbins' && binOpts.sizeFound) continue;
  64584. var aStr = attrSpec.aStr;
  64585. for(i = 0; i < binOpts.traces.length; i++) {
  64586. traceOut = binOpts.traces[i];
  64587. traceIn = traceOut._input;
  64588. if(nestedProperty(traceIn, aStr).get() !== undefined) {
  64589. binOpts[attr] = coerce(aStr);
  64590. binOpts[attr + 'Found'] = true;
  64591. break;
  64592. }
  64593. var autoVals = traceOut._autoBin;
  64594. if(autoVals && autoVals[attr]) {
  64595. // if this is the *first* autoval
  64596. nestedProperty(traceOut, aStr).set(autoVals[attr]);
  64597. }
  64598. }
  64599. // start and end we need to coerce anyway, after having collected the
  64600. // first of each into binOpts, in case a trace wants to restrict its
  64601. // data to a certain range
  64602. if(attr === 'start' || attr === 'end') {
  64603. for(; i < binOpts.traces.length; i++) {
  64604. traceOut = binOpts.traces[i];
  64605. coerce(aStr, (traceOut._autoBin || {})[attr]);
  64606. }
  64607. }
  64608. if(attr === 'nbins' && !binOpts.sizeFound && !binOpts.nbinsFound) {
  64609. traceOut = binOpts.traces[0];
  64610. binOpts[attr] = coerce(aStr);
  64611. }
  64612. }
  64613. }
  64614. };
  64615. },{"../../lib":168,"./attributes":331}],339:[function(_dereq_,module,exports){
  64616. /**
  64617. * Copyright 2012-2019, Plotly, Inc.
  64618. * All rights reserved.
  64619. *
  64620. * This source code is licensed under the MIT license found in the
  64621. * LICENSE file in the root directory of this source tree.
  64622. */
  64623. 'use strict';
  64624. var Registry = _dereq_('../../registry');
  64625. var Lib = _dereq_('../../lib');
  64626. var Color = _dereq_('../../components/color');
  64627. var handleStyleDefaults = _dereq_('../bar/style_defaults');
  64628. var attributes = _dereq_('./attributes');
  64629. module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
  64630. function coerce(attr, dflt) {
  64631. return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
  64632. }
  64633. var x = coerce('x');
  64634. var y = coerce('y');
  64635. var cumulative = coerce('cumulative.enabled');
  64636. if(cumulative) {
  64637. coerce('cumulative.direction');
  64638. coerce('cumulative.currentbin');
  64639. }
  64640. coerce('text');
  64641. var orientation = coerce('orientation', (y && !x) ? 'h' : 'v');
  64642. var sampleLetter = orientation === 'v' ? 'x' : 'y';
  64643. var aggLetter = orientation === 'v' ? 'y' : 'x';
  64644. var len = (x && y) ?
  64645. Math.min(Lib.minRowLength(x) && Lib.minRowLength(y)) :
  64646. Lib.minRowLength(traceOut[sampleLetter] || []);
  64647. if(!len) {
  64648. traceOut.visible = false;
  64649. return;
  64650. }
  64651. traceOut._length = len;
  64652. var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
  64653. handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout);
  64654. var hasAggregationData = traceOut[aggLetter];
  64655. if(hasAggregationData) coerce('histfunc');
  64656. coerce('histnorm');
  64657. // Note: bin defaults are now handled in Histogram.crossTraceDefaults
  64658. // autobin(x|y) are only included here to appease Plotly.validate
  64659. coerce('autobin' + sampleLetter);
  64660. coerce('hovertemplate');
  64661. handleStyleDefaults(traceIn, traceOut, coerce, defaultColor, layout);
  64662. Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
  64663. var lineColor = (traceOut.marker.line || {}).color;
  64664. // override defaultColor for error bars with defaultLine
  64665. var errorBarsSupplyDefaults = Registry.getComponentMethod('errorbars', 'supplyDefaults');
  64666. errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color.defaultLine, {axis: 'y'});
  64667. errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color.defaultLine, {axis: 'x', inherit: 'y'});
  64668. };
  64669. },{"../../components/color":51,"../../lib":168,"../../registry":257,"../bar/style_defaults":281,"./attributes":331}],340:[function(_dereq_,module,exports){
  64670. /**
  64671. * Copyright 2012-2019, Plotly, Inc.
  64672. * All rights reserved.
  64673. *
  64674. * This source code is licensed under the MIT license found in the
  64675. * LICENSE file in the root directory of this source tree.
  64676. */
  64677. 'use strict';
  64678. module.exports = function eventData(out, pt, trace, cd, pointNumber) {
  64679. // standard cartesian event data
  64680. out.x = 'xVal' in pt ? pt.xVal : pt.x;
  64681. out.y = 'yVal' in pt ? pt.yVal : pt.y;
  64682. if(pt.xa) out.xaxis = pt.xa;
  64683. if(pt.ya) out.yaxis = pt.ya;
  64684. // specific to histogram - CDFs do not have pts (yet?)
  64685. if(!(trace.cumulative || {}).enabled) {
  64686. var pts = Array.isArray(pointNumber) ?
  64687. cd[0].pts[pointNumber[0]][pointNumber[1]] :
  64688. cd[pointNumber].pts;
  64689. out.pointNumbers = pts;
  64690. out.binNumber = out.pointNumber;
  64691. delete out.pointNumber;
  64692. delete out.pointIndex;
  64693. var pointIndices;
  64694. if(trace._indexToPoints) {
  64695. pointIndices = [];
  64696. for(var i = 0; i < pts.length; i++) {
  64697. pointIndices = pointIndices.concat(trace._indexToPoints[pts[i]]);
  64698. }
  64699. } else {
  64700. pointIndices = pts;
  64701. }
  64702. out.pointIndices = pointIndices;
  64703. }
  64704. return out;
  64705. };
  64706. },{}],341:[function(_dereq_,module,exports){
  64707. /**
  64708. * Copyright 2012-2019, Plotly, Inc.
  64709. * All rights reserved.
  64710. *
  64711. * This source code is licensed under the MIT license found in the
  64712. * LICENSE file in the root directory of this source tree.
  64713. */
  64714. 'use strict';
  64715. var barHover = _dereq_('../bar/hover').hoverPoints;
  64716. var hoverLabelText = _dereq_('../../plots/cartesian/axes').hoverLabelText;
  64717. module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
  64718. var pts = barHover(pointData, xval, yval, hovermode);
  64719. if(!pts) return;
  64720. pointData = pts[0];
  64721. var di = pointData.cd[pointData.index];
  64722. var trace = pointData.cd[0].trace;
  64723. if(!trace.cumulative.enabled) {
  64724. var posLetter = trace.orientation === 'h' ? 'y' : 'x';
  64725. pointData[posLetter + 'Label'] = hoverLabelText(pointData[posLetter + 'a'], di.ph0, di.ph1);
  64726. }
  64727. if(trace.hovermplate) pointData.hovertemplate = trace.hovertemplate;
  64728. return pts;
  64729. };
  64730. },{"../../plots/cartesian/axes":212,"../bar/hover":273}],342:[function(_dereq_,module,exports){
  64731. /**
  64732. * Copyright 2012-2019, Plotly, Inc.
  64733. * All rights reserved.
  64734. *
  64735. * This source code is licensed under the MIT license found in the
  64736. * LICENSE file in the root directory of this source tree.
  64737. */
  64738. 'use strict';
  64739. /**
  64740. * Histogram has its own attribute, defaults and calc steps,
  64741. * but uses bar's plot to display
  64742. * and bar's crossTraceCalc (formerly known as setPositions) for stacking and grouping
  64743. */
  64744. /**
  64745. * histogram errorBarsOK is debatable, but it's put in for backward compat.
  64746. * there are use cases for it - sqrt for a simple histogram works right now,
  64747. * constant and % work but they're not so meaningful. I guess it could be cool
  64748. * to allow quadrature combination of errors in summed histograms...
  64749. */
  64750. var Histogram = {};
  64751. Histogram.attributes = _dereq_('./attributes');
  64752. Histogram.layoutAttributes = _dereq_('../bar/layout_attributes');
  64753. Histogram.supplyDefaults = _dereq_('./defaults');
  64754. Histogram.crossTraceDefaults = _dereq_('./cross_trace_defaults');
  64755. Histogram.supplyLayoutDefaults = _dereq_('../bar/layout_defaults');
  64756. Histogram.calc = _dereq_('./calc');
  64757. Histogram.crossTraceCalc = _dereq_('../bar/cross_trace_calc').crossTraceCalc;
  64758. Histogram.plot = _dereq_('../bar/plot');
  64759. Histogram.layerName = 'barlayer';
  64760. Histogram.style = _dereq_('../bar/style').style;
  64761. Histogram.styleOnSelect = _dereq_('../bar/style').styleOnSelect;
  64762. Histogram.colorbar = _dereq_('../scatter/marker_colorbar');
  64763. Histogram.hoverPoints = _dereq_('./hover');
  64764. Histogram.selectPoints = _dereq_('../bar/select');
  64765. Histogram.eventData = _dereq_('./event_data');
  64766. Histogram.moduleType = 'trace';
  64767. Histogram.name = 'histogram';
  64768. Histogram.basePlotModule = _dereq_('../../plots/cartesian');
  64769. Histogram.categories = ['cartesian', 'svg', 'bar', 'histogram', 'oriented', 'errorBarsOK', 'showLegend'];
  64770. Histogram.meta = {
  64771. };
  64772. module.exports = Histogram;
  64773. },{"../../plots/cartesian":224,"../bar/cross_trace_calc":270,"../bar/layout_attributes":275,"../bar/layout_defaults":276,"../bar/plot":277,"../bar/select":278,"../bar/style":280,"../scatter/marker_colorbar":385,"./attributes":331,"./calc":336,"./cross_trace_defaults":338,"./defaults":339,"./event_data":340,"./hover":341}],343:[function(_dereq_,module,exports){
  64774. /**
  64775. * Copyright 2012-2019, Plotly, Inc.
  64776. * All rights reserved.
  64777. *
  64778. * This source code is licensed under the MIT license found in the
  64779. * LICENSE file in the root directory of this source tree.
  64780. */
  64781. 'use strict';
  64782. module.exports = {
  64783. percent: function(size, total) {
  64784. var nMax = size.length;
  64785. var norm = 100 / total;
  64786. for(var n = 0; n < nMax; n++) size[n] *= norm;
  64787. },
  64788. probability: function(size, total) {
  64789. var nMax = size.length;
  64790. for(var n = 0; n < nMax; n++) size[n] /= total;
  64791. },
  64792. density: function(size, total, inc, yinc) {
  64793. var nMax = size.length;
  64794. yinc = yinc || 1;
  64795. for(var n = 0; n < nMax; n++) size[n] *= inc[n] * yinc;
  64796. },
  64797. 'probability density': function(size, total, inc, yinc) {
  64798. var nMax = size.length;
  64799. if(yinc) total /= yinc;
  64800. for(var n = 0; n < nMax; n++) size[n] *= inc[n] / total;
  64801. }
  64802. };
  64803. },{}],344:[function(_dereq_,module,exports){
  64804. /**
  64805. * Copyright 2012-2019, Plotly, Inc.
  64806. * All rights reserved.
  64807. *
  64808. * This source code is licensed under the MIT license found in the
  64809. * LICENSE file in the root directory of this source tree.
  64810. */
  64811. 'use strict';
  64812. var histogramAttrs = _dereq_('../histogram/attributes');
  64813. var makeBinAttrs = _dereq_('../histogram/bin_attributes');
  64814. var heatmapAttrs = _dereq_('../heatmap/attributes');
  64815. var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
  64816. var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
  64817. var extendFlat = _dereq_('../../lib/extend').extendFlat;
  64818. module.exports = extendFlat(
  64819. {
  64820. x: histogramAttrs.x,
  64821. y: histogramAttrs.y,
  64822. z: {
  64823. valType: 'data_array',
  64824. editType: 'calc',
  64825. },
  64826. marker: {
  64827. color: {
  64828. valType: 'data_array',
  64829. editType: 'calc',
  64830. },
  64831. editType: 'calc'
  64832. },
  64833. histnorm: histogramAttrs.histnorm,
  64834. histfunc: histogramAttrs.histfunc,
  64835. nbinsx: histogramAttrs.nbinsx,
  64836. xbins: makeBinAttrs('x'),
  64837. nbinsy: histogramAttrs.nbinsy,
  64838. ybins: makeBinAttrs('y'),
  64839. autobinx: histogramAttrs.autobinx,
  64840. autobiny: histogramAttrs.autobiny,
  64841. xgap: heatmapAttrs.xgap,
  64842. ygap: heatmapAttrs.ygap,
  64843. zsmooth: heatmapAttrs.zsmooth,
  64844. zhoverformat: heatmapAttrs.zhoverformat
  64845. },
  64846. colorscaleAttrs('', {
  64847. cLetter: 'z',
  64848. autoColorDflt: false
  64849. }),
  64850. { colorbar: colorbarAttrs }
  64851. );
  64852. },{"../../components/colorbar/attributes":52,"../../components/colorscale/attributes":58,"../../lib/extend":162,"../heatmap/attributes":316,"../histogram/attributes":331,"../histogram/bin_attributes":333}],345:[function(_dereq_,module,exports){
  64853. /**
  64854. * Copyright 2012-2019, Plotly, Inc.
  64855. * All rights reserved.
  64856. *
  64857. * This source code is licensed under the MIT license found in the
  64858. * LICENSE file in the root directory of this source tree.
  64859. */
  64860. 'use strict';
  64861. var Lib = _dereq_('../../lib');
  64862. var Axes = _dereq_('../../plots/cartesian/axes');
  64863. var binFunctions = _dereq_('../histogram/bin_functions');
  64864. var normFunctions = _dereq_('../histogram/norm_functions');
  64865. var doAvg = _dereq_('../histogram/average');
  64866. var getBinSpanLabelRound = _dereq_('../histogram/bin_label_vals');
  64867. module.exports = function calc(gd, trace) {
  64868. var xa = Axes.getFromId(gd, trace.xaxis || 'x');
  64869. var x = trace.x ? xa.makeCalcdata(trace, 'x') : [];
  64870. var ya = Axes.getFromId(gd, trace.yaxis || 'y');
  64871. var y = trace.y ? ya.makeCalcdata(trace, 'y') : [];
  64872. var xcalendar = trace.xcalendar;
  64873. var ycalendar = trace.ycalendar;
  64874. var xr2c = function(v) { return xa.r2c(v, 0, xcalendar); };
  64875. var yr2c = function(v) { return ya.r2c(v, 0, ycalendar); };
  64876. var xc2r = function(v) { return xa.c2r(v, 0, xcalendar); };
  64877. var yc2r = function(v) { return ya.c2r(v, 0, ycalendar); };
  64878. var i, j, n, m;
  64879. var serieslen = trace._length;
  64880. if(x.length > serieslen) x.splice(serieslen, x.length - serieslen);
  64881. if(y.length > serieslen) y.splice(serieslen, y.length - serieslen);
  64882. // calculate the bins
  64883. doAutoBin(trace, 'x', x, xa, xr2c, xc2r, xcalendar);
  64884. doAutoBin(trace, 'y', y, ya, yr2c, yc2r, ycalendar);
  64885. // make the empty bin array & scale the map
  64886. var z = [];
  64887. var onecol = [];
  64888. var zerocol = [];
  64889. var nonuniformBinsX = (typeof(trace.xbins.size) === 'string');
  64890. var nonuniformBinsY = (typeof(trace.ybins.size) === 'string');
  64891. var xEdges = [];
  64892. var yEdges = [];
  64893. var xbins = nonuniformBinsX ? xEdges : trace.xbins;
  64894. var ybins = nonuniformBinsY ? yEdges : trace.ybins;
  64895. var total = 0;
  64896. var counts = [];
  64897. var inputPoints = [];
  64898. var norm = trace.histnorm;
  64899. var func = trace.histfunc;
  64900. var densitynorm = (norm.indexOf('density') !== -1);
  64901. var extremefunc = (func === 'max' || func === 'min');
  64902. var sizeinit = (extremefunc ? null : 0);
  64903. var binfunc = binFunctions.count;
  64904. var normfunc = normFunctions[norm];
  64905. var doavg = false;
  64906. var xinc = [];
  64907. var yinc = [];
  64908. // set a binning function other than count?
  64909. // for binning functions: check first for 'z',
  64910. // then 'mc' in case we had a colored scatter plot
  64911. // and want to transfer these colors to the 2D histo
  64912. // TODO: axe this, make it the responsibility of the app changing type? or an impliedEdit?
  64913. var rawCounterData = ('z' in trace) ?
  64914. trace.z :
  64915. (('marker' in trace && Array.isArray(trace.marker.color)) ?
  64916. trace.marker.color : '');
  64917. if(rawCounterData && func !== 'count') {
  64918. doavg = func === 'avg';
  64919. binfunc = binFunctions[func];
  64920. }
  64921. // decrease end a little in case of rounding errors
  64922. var binSpec = trace.xbins;
  64923. var binStart = xr2c(binSpec.start);
  64924. var binEnd = xr2c(binSpec.end) +
  64925. (binStart - Axes.tickIncrement(binStart, binSpec.size, false, xcalendar)) / 1e6;
  64926. for(i = binStart; i < binEnd; i = Axes.tickIncrement(i, binSpec.size, false, xcalendar)) {
  64927. onecol.push(sizeinit);
  64928. xEdges.push(i);
  64929. if(doavg) zerocol.push(0);
  64930. }
  64931. xEdges.push(i);
  64932. var nx = onecol.length;
  64933. var x0c = xr2c(trace.xbins.start);
  64934. var dx = (i - x0c) / nx;
  64935. var x0 = xc2r(x0c + dx / 2);
  64936. binSpec = trace.ybins;
  64937. binStart = yr2c(binSpec.start);
  64938. binEnd = yr2c(binSpec.end) +
  64939. (binStart - Axes.tickIncrement(binStart, binSpec.size, false, ycalendar)) / 1e6;
  64940. for(i = binStart; i < binEnd; i = Axes.tickIncrement(i, binSpec.size, false, ycalendar)) {
  64941. z.push(onecol.slice());
  64942. yEdges.push(i);
  64943. var ipCol = new Array(nx);
  64944. for(j = 0; j < nx; j++) ipCol[j] = [];
  64945. inputPoints.push(ipCol);
  64946. if(doavg) counts.push(zerocol.slice());
  64947. }
  64948. yEdges.push(i);
  64949. var ny = z.length;
  64950. var y0c = yr2c(trace.ybins.start);
  64951. var dy = (i - y0c) / ny;
  64952. var y0 = yc2r(y0c + dy / 2);
  64953. if(densitynorm) {
  64954. xinc = makeIncrements(onecol.length, xbins, dx, nonuniformBinsX);
  64955. yinc = makeIncrements(z.length, ybins, dy, nonuniformBinsY);
  64956. }
  64957. // for date axes we need bin bounds to be calcdata. For nonuniform bins
  64958. // we already have this, but uniform with start/end/size they're still strings.
  64959. if(!nonuniformBinsX && xa.type === 'date') xbins = binsToCalc(xr2c, xbins);
  64960. if(!nonuniformBinsY && ya.type === 'date') ybins = binsToCalc(yr2c, ybins);
  64961. // put data into bins
  64962. var uniqueValsPerX = true;
  64963. var uniqueValsPerY = true;
  64964. var xVals = new Array(nx);
  64965. var yVals = new Array(ny);
  64966. var xGapLow = Infinity;
  64967. var xGapHigh = Infinity;
  64968. var yGapLow = Infinity;
  64969. var yGapHigh = Infinity;
  64970. for(i = 0; i < serieslen; i++) {
  64971. var xi = x[i];
  64972. var yi = y[i];
  64973. n = Lib.findBin(xi, xbins);
  64974. m = Lib.findBin(yi, ybins);
  64975. if(n >= 0 && n < nx && m >= 0 && m < ny) {
  64976. total += binfunc(n, i, z[m], rawCounterData, counts[m]);
  64977. inputPoints[m][n].push(i);
  64978. if(uniqueValsPerX) {
  64979. if(xVals[n] === undefined) xVals[n] = xi;
  64980. else if(xVals[n] !== xi) uniqueValsPerX = false;
  64981. }
  64982. if(uniqueValsPerY) {
  64983. if(yVals[n] === undefined) yVals[n] = yi;
  64984. else if(yVals[n] !== yi) uniqueValsPerY = false;
  64985. }
  64986. xGapLow = Math.min(xGapLow, xi - xEdges[n]);
  64987. xGapHigh = Math.min(xGapHigh, xEdges[n + 1] - xi);
  64988. yGapLow = Math.min(yGapLow, yi - yEdges[m]);
  64989. yGapHigh = Math.min(yGapHigh, yEdges[m + 1] - yi);
  64990. }
  64991. }
  64992. // normalize, if needed
  64993. if(doavg) {
  64994. for(m = 0; m < ny; m++) total += doAvg(z[m], counts[m]);
  64995. }
  64996. if(normfunc) {
  64997. for(m = 0; m < ny; m++) normfunc(z[m], total, xinc, yinc[m]);
  64998. }
  64999. return {
  65000. x: x,
  65001. xRanges: getRanges(xEdges, uniqueValsPerX && xVals, xGapLow, xGapHigh, xa, xcalendar),
  65002. x0: x0,
  65003. dx: dx,
  65004. y: y,
  65005. yRanges: getRanges(yEdges, uniqueValsPerY && yVals, yGapLow, yGapHigh, ya, ycalendar),
  65006. y0: y0,
  65007. dy: dy,
  65008. z: z,
  65009. pts: inputPoints
  65010. };
  65011. };
  65012. function doAutoBin(trace, axLetter, data, ax, r2c, c2r, calendar) {
  65013. var binAttr = axLetter + 'bins';
  65014. var binSpec = trace[binAttr];
  65015. if(!binSpec) binSpec = trace[binAttr] = {};
  65016. var inputBinSpec = trace._input[binAttr] || {};
  65017. var autoBin = trace._autoBin = {};
  65018. // clear out any previously added autobin info
  65019. if(!inputBinSpec.size) delete binSpec.size;
  65020. if(inputBinSpec.start === undefined) delete binSpec.start;
  65021. if(inputBinSpec.end === undefined) delete binSpec.end;
  65022. var autoSize = !binSpec.size;
  65023. var autoStart = binSpec.start === undefined;
  65024. var autoEnd = binSpec.end === undefined;
  65025. if(autoSize || autoStart || autoEnd) {
  65026. var newBinSpec = Axes.autoBin(data, ax, trace['nbins' + axLetter], '2d', calendar, binSpec.size);
  65027. if(trace.type === 'histogram2dcontour') {
  65028. // the "true" 2nd argument reverses the tick direction (which we can't
  65029. // just do with a minus sign because of month bins)
  65030. if(autoStart) {
  65031. newBinSpec.start = c2r(Axes.tickIncrement(
  65032. r2c(newBinSpec.start), newBinSpec.size, true, calendar));
  65033. }
  65034. if(autoEnd) {
  65035. newBinSpec.end = c2r(Axes.tickIncrement(
  65036. r2c(newBinSpec.end), newBinSpec.size, false, calendar));
  65037. }
  65038. }
  65039. if(autoSize) binSpec.size = autoBin.size = newBinSpec.size;
  65040. if(autoStart) binSpec.start = autoBin.start = newBinSpec.start;
  65041. if(autoEnd) binSpec.end = autoBin.end = newBinSpec.end;
  65042. }
  65043. // Backward compatibility for one-time autobinning.
  65044. // autobin: true is handled in cleanData, but autobin: false
  65045. // needs to be here where we have determined the values.
  65046. var autoBinAttr = 'autobin' + axLetter;
  65047. if(trace._input[autoBinAttr] === false) {
  65048. trace._input[binAttr] = Lib.extendFlat({}, binSpec);
  65049. delete trace._input[autoBinAttr];
  65050. delete trace[autoBinAttr];
  65051. }
  65052. }
  65053. function makeIncrements(len, bins, dv, nonuniform) {
  65054. var out = new Array(len);
  65055. var i;
  65056. if(nonuniform) {
  65057. for(i = 0; i < len; i++) out[i] = 1 / (bins[i + 1] - bins[i]);
  65058. }
  65059. else {
  65060. var inc = 1 / dv;
  65061. for(i = 0; i < len; i++) out[i] = inc;
  65062. }
  65063. return out;
  65064. }
  65065. function binsToCalc(r2c, bins) {
  65066. return {
  65067. start: r2c(bins.start),
  65068. end: r2c(bins.end),
  65069. size: bins.size
  65070. };
  65071. }
  65072. function getRanges(edges, uniqueVals, gapLow, gapHigh, ax, calendar) {
  65073. var i;
  65074. var len = edges.length - 1;
  65075. var out = new Array(len);
  65076. if(uniqueVals) {
  65077. for(i = 0; i < len; i++) out[i] = [uniqueVals[i], uniqueVals[i]];
  65078. }
  65079. else {
  65080. var roundFn = getBinSpanLabelRound(gapLow, gapHigh, edges, ax, calendar);
  65081. for(i = 0; i < len; i++) out[i] = [roundFn(edges[i]), roundFn(edges[i + 1], true)];
  65082. }
  65083. return out;
  65084. }
  65085. },{"../../lib":168,"../../plots/cartesian/axes":212,"../histogram/average":332,"../histogram/bin_functions":334,"../histogram/bin_label_vals":335,"../histogram/norm_functions":343}],346:[function(_dereq_,module,exports){
  65086. /**
  65087. * Copyright 2012-2019, Plotly, Inc.
  65088. * All rights reserved.
  65089. *
  65090. * This source code is licensed under the MIT license found in the
  65091. * LICENSE file in the root directory of this source tree.
  65092. */
  65093. 'use strict';
  65094. var isNumeric = _dereq_('fast-isnumeric');
  65095. var BADNUM = _dereq_('../../constants/numerical').BADNUM;
  65096. var axisIds = _dereq_('../../plots/cartesian/axis_ids');
  65097. var Lib = _dereq_('../../lib');
  65098. var attributes = _dereq_('./attributes');
  65099. var BINDIRECTIONS = ['x', 'y'];
  65100. // Handle bin attrs and relink auto-determined values so fullData is complete
  65101. // does not have cross-trace coupling, but moved out here so we have axis types
  65102. // and relinked trace._autoBin
  65103. module.exports = function crossTraceDefaults(fullData, fullLayout) {
  65104. var i, j, traceOut, binDirection;
  65105. function coerce(attr) {
  65106. return Lib.coerce(traceOut._input, traceOut, attributes, attr);
  65107. }
  65108. for(i = 0; i < fullData.length; i++) {
  65109. traceOut = fullData[i];
  65110. var type = traceOut.type;
  65111. if(type !== 'histogram2d' && type !== 'histogram2dcontour') continue;
  65112. for(j = 0; j < BINDIRECTIONS.length; j++) {
  65113. binDirection = BINDIRECTIONS[j];
  65114. var binAttr = binDirection + 'bins';
  65115. var autoBins = (traceOut._autoBin || {})[binDirection] || {};
  65116. coerce(binAttr + '.start', autoBins.start);
  65117. coerce(binAttr + '.end', autoBins.end);
  65118. coerce(binAttr + '.size', autoBins.size);
  65119. cleanBins(traceOut, binDirection, fullLayout, autoBins);
  65120. if(!(traceOut[binAttr] || {}).size) coerce('nbins' + binDirection);
  65121. }
  65122. }
  65123. };
  65124. function cleanBins(trace, binDirection, fullLayout, autoBins) {
  65125. var ax = fullLayout[axisIds.id2name(trace[binDirection + 'axis'])];
  65126. var axType = ax.type;
  65127. var binAttr = binDirection + 'bins';
  65128. var bins = trace[binAttr];
  65129. var calendar = trace[binDirection + 'calendar'];
  65130. if(!bins) bins = trace[binAttr] = {};
  65131. var cleanBound = (axType === 'date') ?
  65132. function(v, dflt) { return (v || v === 0) ? Lib.cleanDate(v, BADNUM, calendar) : dflt; } :
  65133. function(v, dflt) { return isNumeric(v) ? Number(v) : dflt; };
  65134. bins.start = cleanBound(bins.start, autoBins.start);
  65135. bins.end = cleanBound(bins.end, autoBins.end);
  65136. // logic for bin size is very similar to dtick (cartesian/tick_value_defaults)
  65137. // but without the extra string options for log axes
  65138. // ie the only strings we accept are M<n> for months
  65139. var sizeDflt = autoBins.size;
  65140. var binSize = bins.size;
  65141. if(isNumeric(binSize)) {
  65142. bins.size = (binSize > 0) ? Number(binSize) : sizeDflt;
  65143. }
  65144. else if(typeof binSize !== 'string') {
  65145. bins.size = sizeDflt;
  65146. }
  65147. else {
  65148. // date special case: "M<n>" gives bins every (integer) n months
  65149. var prefix = binSize.charAt(0);
  65150. var sizeNum = binSize.substr(1);
  65151. sizeNum = isNumeric(sizeNum) ? Number(sizeNum) : 0;
  65152. if((sizeNum <= 0) || !(
  65153. axType === 'date' && prefix === 'M' && sizeNum === Math.round(sizeNum)
  65154. )) {
  65155. bins.size = sizeDflt;
  65156. }
  65157. }
  65158. }
  65159. },{"../../constants/numerical":149,"../../lib":168,"../../plots/cartesian/axis_ids":215,"./attributes":344,"fast-isnumeric":18}],347:[function(_dereq_,module,exports){
  65160. /**
  65161. * Copyright 2012-2019, Plotly, Inc.
  65162. * All rights reserved.
  65163. *
  65164. * This source code is licensed under the MIT license found in the
  65165. * LICENSE file in the root directory of this source tree.
  65166. */
  65167. 'use strict';
  65168. var Lib = _dereq_('../../lib');
  65169. var handleSampleDefaults = _dereq_('./sample_defaults');
  65170. var handleStyleDefaults = _dereq_('../heatmap/style_defaults');
  65171. var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
  65172. var attributes = _dereq_('./attributes');
  65173. module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
  65174. function coerce(attr, dflt) {
  65175. return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
  65176. }
  65177. handleSampleDefaults(traceIn, traceOut, coerce, layout);
  65178. if(traceOut.visible === false) return;
  65179. handleStyleDefaults(traceIn, traceOut, coerce, layout);
  65180. colorscaleDefaults(
  65181. traceIn, traceOut, layout, coerce, {prefix: '', cLetter: 'z'}
  65182. );
  65183. };
  65184. },{"../../components/colorscale/defaults":61,"../../lib":168,"../heatmap/style_defaults":329,"./attributes":344,"./sample_defaults":350}],348:[function(_dereq_,module,exports){
  65185. /**
  65186. * Copyright 2012-2019, Plotly, Inc.
  65187. * All rights reserved.
  65188. *
  65189. * This source code is licensed under the MIT license found in the
  65190. * LICENSE file in the root directory of this source tree.
  65191. */
  65192. 'use strict';
  65193. var heatmapHover = _dereq_('../heatmap/hover');
  65194. var hoverLabelText = _dereq_('../../plots/cartesian/axes').hoverLabelText;
  65195. module.exports = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer, contour) {
  65196. var pts = heatmapHover(pointData, xval, yval, hovermode, hoverLayer, contour);
  65197. if(!pts) return;
  65198. pointData = pts[0];
  65199. var indices = pointData.index;
  65200. var ny = indices[0];
  65201. var nx = indices[1];
  65202. var cd0 = pointData.cd[0];
  65203. var xRange = cd0.xRanges[nx];
  65204. var yRange = cd0.yRanges[ny];
  65205. pointData.xLabel = hoverLabelText(pointData.xa, xRange[0], xRange[1]);
  65206. pointData.yLabel = hoverLabelText(pointData.ya, yRange[0], yRange[1]);
  65207. return pts;
  65208. };
  65209. },{"../../plots/cartesian/axes":212,"../heatmap/hover":323}],349:[function(_dereq_,module,exports){
  65210. /**
  65211. * Copyright 2012-2019, Plotly, Inc.
  65212. * All rights reserved.
  65213. *
  65214. * This source code is licensed under the MIT license found in the
  65215. * LICENSE file in the root directory of this source tree.
  65216. */
  65217. 'use strict';
  65218. var Histogram2D = {};
  65219. Histogram2D.attributes = _dereq_('./attributes');
  65220. Histogram2D.supplyDefaults = _dereq_('./defaults');
  65221. Histogram2D.crossTraceDefaults = _dereq_('./cross_trace_defaults');
  65222. Histogram2D.calc = _dereq_('../heatmap/calc');
  65223. Histogram2D.plot = _dereq_('../heatmap/plot');
  65224. Histogram2D.layerName = 'heatmaplayer';
  65225. Histogram2D.colorbar = _dereq_('../heatmap/colorbar');
  65226. Histogram2D.style = _dereq_('../heatmap/style');
  65227. Histogram2D.hoverPoints = _dereq_('./hover');
  65228. Histogram2D.eventData = _dereq_('../histogram/event_data');
  65229. Histogram2D.moduleType = 'trace';
  65230. Histogram2D.name = 'histogram2d';
  65231. Histogram2D.basePlotModule = _dereq_('../../plots/cartesian');
  65232. Histogram2D.categories = ['cartesian', 'svg', '2dMap', 'histogram'];
  65233. Histogram2D.meta = {
  65234. };
  65235. module.exports = Histogram2D;
  65236. },{"../../plots/cartesian":224,"../heatmap/calc":317,"../heatmap/colorbar":319,"../heatmap/plot":327,"../heatmap/style":328,"../histogram/event_data":340,"./attributes":344,"./cross_trace_defaults":346,"./defaults":347,"./hover":348}],350:[function(_dereq_,module,exports){
  65237. /**
  65238. * Copyright 2012-2019, Plotly, Inc.
  65239. * All rights reserved.
  65240. *
  65241. * This source code is licensed under the MIT license found in the
  65242. * LICENSE file in the root directory of this source tree.
  65243. */
  65244. 'use strict';
  65245. var Registry = _dereq_('../../registry');
  65246. var Lib = _dereq_('../../lib');
  65247. module.exports = function handleSampleDefaults(traceIn, traceOut, coerce, layout) {
  65248. var x = coerce('x');
  65249. var y = coerce('y');
  65250. var xlen = Lib.minRowLength(x);
  65251. var ylen = Lib.minRowLength(y);
  65252. // we could try to accept x0 and dx, etc...
  65253. // but that's a pretty weird use case.
  65254. // for now require both x and y explicitly specified.
  65255. if(!xlen || !ylen) {
  65256. traceOut.visible = false;
  65257. return;
  65258. }
  65259. traceOut._length = Math.min(xlen, ylen);
  65260. var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
  65261. handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout);
  65262. // if marker.color is an array, we can use it in aggregation instead of z
  65263. var hasAggregationData = coerce('z') || coerce('marker.color');
  65264. if(hasAggregationData) coerce('histfunc');
  65265. coerce('histnorm');
  65266. // Note: bin defaults are now handled in Histogram2D.crossTraceDefaults
  65267. // autobin(x|y) are only included here to appease Plotly.validate
  65268. coerce('autobinx');
  65269. coerce('autobiny');
  65270. };
  65271. },{"../../lib":168,"../../registry":257}],351:[function(_dereq_,module,exports){
  65272. /**
  65273. * Copyright 2012-2019, Plotly, Inc.
  65274. * All rights reserved.
  65275. *
  65276. * This source code is licensed under the MIT license found in the
  65277. * LICENSE file in the root directory of this source tree.
  65278. */
  65279. 'use strict';
  65280. var histogram2dAttrs = _dereq_('../histogram2d/attributes');
  65281. var contourAttrs = _dereq_('../contour/attributes');
  65282. var colorscaleAttrs = _dereq_('../../components/colorscale/attributes');
  65283. var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
  65284. var extendFlat = _dereq_('../../lib/extend').extendFlat;
  65285. module.exports = extendFlat({
  65286. x: histogram2dAttrs.x,
  65287. y: histogram2dAttrs.y,
  65288. z: histogram2dAttrs.z,
  65289. marker: histogram2dAttrs.marker,
  65290. histnorm: histogram2dAttrs.histnorm,
  65291. histfunc: histogram2dAttrs.histfunc,
  65292. nbinsx: histogram2dAttrs.nbinsx,
  65293. xbins: histogram2dAttrs.xbins,
  65294. nbinsy: histogram2dAttrs.nbinsy,
  65295. ybins: histogram2dAttrs.ybins,
  65296. autobinx: histogram2dAttrs.autobinx,
  65297. autobiny: histogram2dAttrs.autobiny,
  65298. autocontour: contourAttrs.autocontour,
  65299. ncontours: contourAttrs.ncontours,
  65300. contours: contourAttrs.contours,
  65301. line: contourAttrs.line,
  65302. zhoverformat: histogram2dAttrs.zhoverformat
  65303. },
  65304. colorscaleAttrs('', {
  65305. cLetter: 'z',
  65306. editTypeOverride: 'calc'
  65307. }),
  65308. { colorbar: colorbarAttrs }
  65309. );
  65310. },{"../../components/colorbar/attributes":52,"../../components/colorscale/attributes":58,"../../lib/extend":162,"../contour/attributes":294,"../histogram2d/attributes":344}],352:[function(_dereq_,module,exports){
  65311. /**
  65312. * Copyright 2012-2019, Plotly, Inc.
  65313. * All rights reserved.
  65314. *
  65315. * This source code is licensed under the MIT license found in the
  65316. * LICENSE file in the root directory of this source tree.
  65317. */
  65318. 'use strict';
  65319. var Lib = _dereq_('../../lib');
  65320. var handleSampleDefaults = _dereq_('../histogram2d/sample_defaults');
  65321. var handleContoursDefaults = _dereq_('../contour/contours_defaults');
  65322. var handleStyleDefaults = _dereq_('../contour/style_defaults');
  65323. var attributes = _dereq_('./attributes');
  65324. module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
  65325. function coerce(attr, dflt) {
  65326. return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
  65327. }
  65328. function coerce2(attr) {
  65329. return Lib.coerce2(traceIn, traceOut, attributes, attr);
  65330. }
  65331. handleSampleDefaults(traceIn, traceOut, coerce, layout);
  65332. if(traceOut.visible === false) return;
  65333. handleContoursDefaults(traceIn, traceOut, coerce, coerce2);
  65334. handleStyleDefaults(traceIn, traceOut, coerce, layout);
  65335. };
  65336. },{"../../lib":168,"../contour/contours_defaults":301,"../contour/style_defaults":315,"../histogram2d/sample_defaults":350,"./attributes":351}],353:[function(_dereq_,module,exports){
  65337. /**
  65338. * Copyright 2012-2019, Plotly, Inc.
  65339. * All rights reserved.
  65340. *
  65341. * This source code is licensed under the MIT license found in the
  65342. * LICENSE file in the root directory of this source tree.
  65343. */
  65344. 'use strict';
  65345. var Histogram2dContour = {};
  65346. Histogram2dContour.attributes = _dereq_('./attributes');
  65347. Histogram2dContour.supplyDefaults = _dereq_('./defaults');
  65348. Histogram2dContour.crossTraceDefaults = _dereq_('../histogram2d/cross_trace_defaults');
  65349. Histogram2dContour.calc = _dereq_('../contour/calc');
  65350. Histogram2dContour.plot = _dereq_('../contour/plot').plot;
  65351. Histogram2dContour.layerName = 'contourlayer';
  65352. Histogram2dContour.style = _dereq_('../contour/style');
  65353. Histogram2dContour.colorbar = _dereq_('../contour/colorbar');
  65354. Histogram2dContour.hoverPoints = _dereq_('../contour/hover');
  65355. Histogram2dContour.moduleType = 'trace';
  65356. Histogram2dContour.name = 'histogram2dcontour';
  65357. Histogram2dContour.basePlotModule = _dereq_('../../plots/cartesian');
  65358. Histogram2dContour.categories = ['cartesian', 'svg', '2dMap', 'contour', 'histogram', 'showLegend'];
  65359. Histogram2dContour.meta = {
  65360. };
  65361. module.exports = Histogram2dContour;
  65362. },{"../../plots/cartesian":224,"../contour/calc":295,"../contour/colorbar":297,"../contour/hover":307,"../contour/plot":312,"../contour/style":314,"../histogram2d/cross_trace_defaults":346,"./attributes":351,"./defaults":352}],354:[function(_dereq_,module,exports){
  65363. /**
  65364. * Copyright 2012-2019, Plotly, Inc.
  65365. * All rights reserved.
  65366. *
  65367. * This source code is licensed under the MIT license found in the
  65368. * LICENSE file in the root directory of this source tree.
  65369. */
  65370. 'use strict';
  65371. var colorAttrs = _dereq_('../../components/color/attributes');
  65372. var fontAttrs = _dereq_('../../plots/font_attributes');
  65373. var plotAttrs = _dereq_('../../plots/attributes');
  65374. var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
  65375. var domainAttrs = _dereq_('../../plots/domain').attributes;
  65376. var extendFlat = _dereq_('../../lib/extend').extendFlat;
  65377. var textFontAttrs = fontAttrs({
  65378. editType: 'calc',
  65379. arrayOk: true,
  65380. colorEditType: 'plot',
  65381. });
  65382. module.exports = {
  65383. labels: {
  65384. valType: 'data_array',
  65385. editType: 'calc',
  65386. },
  65387. // equivalent of x0 and dx, if label is missing
  65388. label0: {
  65389. valType: 'number',
  65390. dflt: 0,
  65391. editType: 'calc',
  65392. },
  65393. dlabel: {
  65394. valType: 'number',
  65395. dflt: 1,
  65396. editType: 'calc',
  65397. },
  65398. values: {
  65399. valType: 'data_array',
  65400. editType: 'calc',
  65401. },
  65402. marker: {
  65403. colors: {
  65404. valType: 'data_array', // TODO 'color_array' ?
  65405. editType: 'calc',
  65406. },
  65407. line: {
  65408. color: {
  65409. valType: 'color',
  65410. dflt: colorAttrs.defaultLine,
  65411. arrayOk: true,
  65412. editType: 'style',
  65413. },
  65414. width: {
  65415. valType: 'number',
  65416. min: 0,
  65417. dflt: 0,
  65418. arrayOk: true,
  65419. editType: 'style',
  65420. },
  65421. editType: 'calc'
  65422. },
  65423. editType: 'calc'
  65424. },
  65425. text: {
  65426. valType: 'data_array',
  65427. editType: 'calc',
  65428. },
  65429. hovertext: {
  65430. valType: 'string',
  65431. dflt: '',
  65432. arrayOk: true,
  65433. editType: 'style',
  65434. },
  65435. // 'see eg:'
  65436. // 'https://www.e-education.psu.edu/natureofgeoinfo/sites/www.e-education.psu.edu.natureofgeoinfo/files/image/hisp_pies.gif',
  65437. // '(this example involves a map too - may someday be a whole trace type',
  65438. // 'of its own. but the point is the size of the whole pie is important.)'
  65439. scalegroup: {
  65440. valType: 'string',
  65441. dflt: '',
  65442. editType: 'calc',
  65443. },
  65444. // labels (legend is handled by plots.attributes.showlegend and layout.hiddenlabels)
  65445. textinfo: {
  65446. valType: 'flaglist',
  65447. flags: ['label', 'text', 'value', 'percent'],
  65448. extras: ['none'],
  65449. editType: 'calc',
  65450. },
  65451. hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
  65452. flags: ['label', 'text', 'value', 'percent', 'name']
  65453. }),
  65454. hovertemplate: hovertemplateAttrs({}, {
  65455. keys: ['label', 'color', 'value', 'percent', 'text']
  65456. }),
  65457. textposition: {
  65458. valType: 'enumerated',
  65459. values: ['inside', 'outside', 'auto', 'none'],
  65460. dflt: 'auto',
  65461. arrayOk: true,
  65462. editType: 'calc',
  65463. },
  65464. textfont: extendFlat({}, textFontAttrs, {
  65465. }),
  65466. insidetextfont: extendFlat({}, textFontAttrs, {
  65467. }),
  65468. outsidetextfont: extendFlat({}, textFontAttrs, {
  65469. }),
  65470. title: {
  65471. text: {
  65472. valType: 'string',
  65473. dflt: '',
  65474. editType: 'calc',
  65475. },
  65476. font: extendFlat({}, textFontAttrs, {
  65477. }),
  65478. position: {
  65479. valType: 'enumerated',
  65480. values: [
  65481. 'top left', 'top center', 'top right',
  65482. 'middle center',
  65483. 'bottom left', 'bottom center', 'bottom right'
  65484. ],
  65485. editType: 'calc',
  65486. },
  65487. editType: 'calc'
  65488. },
  65489. // position and shape
  65490. domain: domainAttrs({name: 'pie', trace: true, editType: 'calc'}),
  65491. hole: {
  65492. valType: 'number',
  65493. min: 0,
  65494. max: 1,
  65495. dflt: 0,
  65496. editType: 'calc',
  65497. },
  65498. // ordering and direction
  65499. sort: {
  65500. valType: 'boolean',
  65501. dflt: true,
  65502. editType: 'calc',
  65503. },
  65504. direction: {
  65505. /**
  65506. * there are two common conventions, both of which place the first
  65507. * (largest, if sorted) slice with its left edge at 12 o'clock but
  65508. * succeeding slices follow either cw or ccw from there.
  65509. *
  65510. * see http://visage.co/data-visualization-101-pie-charts/
  65511. */
  65512. valType: 'enumerated',
  65513. values: ['clockwise', 'counterclockwise'],
  65514. dflt: 'counterclockwise',
  65515. editType: 'calc',
  65516. },
  65517. rotation: {
  65518. valType: 'number',
  65519. min: -360,
  65520. max: 360,
  65521. dflt: 0,
  65522. editType: 'calc',
  65523. },
  65524. pull: {
  65525. valType: 'number',
  65526. min: 0,
  65527. max: 1,
  65528. dflt: 0,
  65529. arrayOk: true,
  65530. editType: 'calc',
  65531. },
  65532. _deprecated: {
  65533. title: {
  65534. valType: 'string',
  65535. dflt: '',
  65536. editType: 'calc',
  65537. },
  65538. titlefont: extendFlat({}, textFontAttrs, {
  65539. }),
  65540. titleposition: {
  65541. valType: 'enumerated',
  65542. values: [
  65543. 'top left', 'top center', 'top right',
  65544. 'middle center',
  65545. 'bottom left', 'bottom center', 'bottom right'
  65546. ],
  65547. editType: 'calc',
  65548. }
  65549. }
  65550. };
  65551. },{"../../components/color/attributes":50,"../../components/fx/hovertemplate_attributes":89,"../../lib/extend":162,"../../plots/attributes":209,"../../plots/domain":238,"../../plots/font_attributes":239}],355:[function(_dereq_,module,exports){
  65552. /**
  65553. * Copyright 2012-2019, Plotly, Inc.
  65554. * All rights reserved.
  65555. *
  65556. * This source code is licensed under the MIT license found in the
  65557. * LICENSE file in the root directory of this source tree.
  65558. */
  65559. 'use strict';
  65560. var Registry = _dereq_('../../registry');
  65561. var getModuleCalcData = _dereq_('../../plots/get_data').getModuleCalcData;
  65562. exports.name = 'pie';
  65563. exports.plot = function(gd) {
  65564. var Pie = Registry.getModule('pie');
  65565. var cdPie = getModuleCalcData(gd.calcdata, Pie)[0];
  65566. if(cdPie.length) Pie.plot(gd, cdPie);
  65567. };
  65568. exports.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) {
  65569. var hadPie = (oldFullLayout._has && oldFullLayout._has('pie'));
  65570. var hasPie = (newFullLayout._has && newFullLayout._has('pie'));
  65571. if(hadPie && !hasPie) {
  65572. oldFullLayout._pielayer.selectAll('g.trace').remove();
  65573. }
  65574. };
  65575. },{"../../plots/get_data":241,"../../registry":257}],356:[function(_dereq_,module,exports){
  65576. /**
  65577. * Copyright 2012-2019, Plotly, Inc.
  65578. * All rights reserved.
  65579. *
  65580. * This source code is licensed under the MIT license found in the
  65581. * LICENSE file in the root directory of this source tree.
  65582. */
  65583. 'use strict';
  65584. var isNumeric = _dereq_('fast-isnumeric');
  65585. var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;
  65586. var tinycolor = _dereq_('tinycolor2');
  65587. var Color = _dereq_('../../components/color');
  65588. var helpers = _dereq_('./helpers');
  65589. exports.calc = function calc(gd, trace) {
  65590. var vals = trace.values;
  65591. var hasVals = isArrayOrTypedArray(vals) && vals.length;
  65592. var labels = trace.labels;
  65593. var colors = trace.marker.colors || [];
  65594. var cd = [];
  65595. var fullLayout = gd._fullLayout;
  65596. var colorMap = fullLayout._piecolormap;
  65597. var allThisTraceLabels = {};
  65598. var vTotal = 0;
  65599. var hiddenLabels = fullLayout.hiddenlabels || [];
  65600. var i, v, label, hidden, pt;
  65601. if(trace.dlabel) {
  65602. labels = new Array(vals.length);
  65603. for(i = 0; i < vals.length; i++) {
  65604. labels[i] = String(trace.label0 + i * trace.dlabel);
  65605. }
  65606. }
  65607. function pullColor(color, label) {
  65608. if(!color) return false;
  65609. color = tinycolor(color);
  65610. if(!color.isValid()) return false;
  65611. color = Color.addOpacity(color, color.getAlpha());
  65612. if(!colorMap[label]) colorMap[label] = color;
  65613. return color;
  65614. }
  65615. var seriesLen = (hasVals ? vals : labels).length;
  65616. for(i = 0; i < seriesLen; i++) {
  65617. if(hasVals) {
  65618. v = vals[i];
  65619. if(!isNumeric(v)) continue;
  65620. v = +v;
  65621. if(v < 0) continue;
  65622. }
  65623. else v = 1;
  65624. label = labels[i];
  65625. if(label === undefined || label === '') label = i;
  65626. label = String(label);
  65627. var thisLabelIndex = allThisTraceLabels[label];
  65628. if(thisLabelIndex === undefined) {
  65629. allThisTraceLabels[label] = cd.length;
  65630. hidden = hiddenLabels.indexOf(label) !== -1;
  65631. if(!hidden) vTotal += v;
  65632. cd.push({
  65633. v: v,
  65634. label: label,
  65635. color: pullColor(colors[i], label),
  65636. i: i,
  65637. pts: [i],
  65638. hidden: hidden
  65639. });
  65640. }
  65641. else {
  65642. pt = cd[thisLabelIndex];
  65643. pt.v += v;
  65644. pt.pts.push(i);
  65645. if(!pt.hidden) vTotal += v;
  65646. if(pt.color === false && colors[i]) {
  65647. pt.color = pullColor(colors[i], label);
  65648. }
  65649. }
  65650. }
  65651. if(trace.sort) cd.sort(function(a, b) { return b.v - a.v; });
  65652. // include the sum of all values in the first point
  65653. if(cd[0]) cd[0].vTotal = vTotal;
  65654. // now insert text
  65655. if(trace.textinfo && trace.textinfo !== 'none') {
  65656. var hasLabel = trace.textinfo.indexOf('label') !== -1;
  65657. var hasText = trace.textinfo.indexOf('text') !== -1;
  65658. var hasValue = trace.textinfo.indexOf('value') !== -1;
  65659. var hasPercent = trace.textinfo.indexOf('percent') !== -1;
  65660. var separators = fullLayout.separators;
  65661. var thisText;
  65662. for(i = 0; i < cd.length; i++) {
  65663. pt = cd[i];
  65664. thisText = hasLabel ? [pt.label] : [];
  65665. if(hasText) {
  65666. var texti = helpers.getFirstFilled(trace.text, pt.pts);
  65667. if(texti) thisText.push(texti);
  65668. }
  65669. if(hasValue) thisText.push(helpers.formatPieValue(pt.v, separators));
  65670. if(hasPercent) thisText.push(helpers.formatPiePercent(pt.v / vTotal, separators));
  65671. pt.text = thisText.join('<br>');
  65672. }
  65673. }
  65674. return cd;
  65675. };
  65676. /*
  65677. * `calc` filled in (and collated) explicit colors.
  65678. * Now we need to propagate these explicit colors to other traces,
  65679. * and fill in default colors.
  65680. * This is done after sorting, so we pick defaults
  65681. * in the order slices will be displayed
  65682. */
  65683. exports.crossTraceCalc = function(gd) {
  65684. var fullLayout = gd._fullLayout;
  65685. var calcdata = gd.calcdata;
  65686. var pieColorWay = fullLayout.piecolorway;
  65687. var colorMap = fullLayout._piecolormap;
  65688. if(fullLayout.extendpiecolors) {
  65689. pieColorWay = generateExtendedColors(pieColorWay);
  65690. }
  65691. var dfltColorCount = 0;
  65692. var i, j, cd, pt;
  65693. for(i = 0; i < calcdata.length; i++) {
  65694. cd = calcdata[i];
  65695. if(cd[0].trace.type !== 'pie') continue;
  65696. for(j = 0; j < cd.length; j++) {
  65697. pt = cd[j];
  65698. if(pt.color === false) {
  65699. // have we seen this label and assigned a color to it in a previous trace?
  65700. if(colorMap[pt.label]) {
  65701. pt.color = colorMap[pt.label];
  65702. }
  65703. else {
  65704. colorMap[pt.label] = pt.color = pieColorWay[dfltColorCount % pieColorWay.length];
  65705. dfltColorCount++;
  65706. }
  65707. }
  65708. }
  65709. }
  65710. };
  65711. /**
  65712. * pick a default color from the main default set, augmented by
  65713. * itself lighter then darker before repeating
  65714. */
  65715. var extendedColorWays = {};
  65716. function generateExtendedColors(colorList) {
  65717. var i;
  65718. var colorString = JSON.stringify(colorList);
  65719. var pieColors = extendedColorWays[colorString];
  65720. if(!pieColors) {
  65721. pieColors = colorList.slice();
  65722. for(i = 0; i < colorList.length; i++) {
  65723. pieColors.push(tinycolor(colorList[i]).lighten(20).toHexString());
  65724. }
  65725. for(i = 0; i < colorList.length; i++) {
  65726. pieColors.push(tinycolor(colorList[i]).darken(20).toHexString());
  65727. }
  65728. extendedColorWays[colorString] = pieColors;
  65729. }
  65730. return pieColors;
  65731. }
  65732. },{"../../components/color":51,"../../lib":168,"./helpers":359,"fast-isnumeric":18,"tinycolor2":34}],357:[function(_dereq_,module,exports){
  65733. /**
  65734. * Copyright 2012-2019, Plotly, Inc.
  65735. * All rights reserved.
  65736. *
  65737. * This source code is licensed under the MIT license found in the
  65738. * LICENSE file in the root directory of this source tree.
  65739. */
  65740. 'use strict';
  65741. var Lib = _dereq_('../../lib');
  65742. var attributes = _dereq_('./attributes');
  65743. var handleDomainDefaults = _dereq_('../../plots/domain').defaults;
  65744. module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
  65745. function coerce(attr, dflt) {
  65746. return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
  65747. }
  65748. var coerceFont = Lib.coerceFont;
  65749. var len;
  65750. var vals = coerce('values');
  65751. var hasVals = Lib.isArrayOrTypedArray(vals);
  65752. var labels = coerce('labels');
  65753. if(Array.isArray(labels)) {
  65754. len = labels.length;
  65755. if(hasVals) len = Math.min(len, vals.length);
  65756. }
  65757. else if(hasVals) {
  65758. len = vals.length;
  65759. coerce('label0');
  65760. coerce('dlabel');
  65761. }
  65762. if(!len) {
  65763. traceOut.visible = false;
  65764. return;
  65765. }
  65766. traceOut._length = len;
  65767. var lineWidth = coerce('marker.line.width');
  65768. if(lineWidth) coerce('marker.line.color');
  65769. coerce('marker.colors');
  65770. coerce('scalegroup');
  65771. // TODO: hole needs to be coerced to the same value within a scaleegroup
  65772. var textData = coerce('text');
  65773. var textInfo = coerce('textinfo', Array.isArray(textData) ? 'text+percent' : 'percent');
  65774. coerce('hovertext');
  65775. coerce('hovertemplate');
  65776. if(textInfo && textInfo !== 'none') {
  65777. var textPosition = coerce('textposition');
  65778. var hasBoth = Array.isArray(textPosition) || textPosition === 'auto';
  65779. var hasInside = hasBoth || textPosition === 'inside';
  65780. var hasOutside = hasBoth || textPosition === 'outside';
  65781. if(hasInside || hasOutside) {
  65782. var dfltFont = coerceFont(coerce, 'textfont', layout.font);
  65783. if(hasInside) {
  65784. var insideTextFontDefault = Lib.extendFlat({}, dfltFont);
  65785. var isTraceTextfontColorSet = traceIn.textfont && traceIn.textfont.color;
  65786. var isColorInheritedFromLayoutFont = !isTraceTextfontColorSet;
  65787. if(isColorInheritedFromLayoutFont) {
  65788. delete insideTextFontDefault.color;
  65789. }
  65790. coerceFont(coerce, 'insidetextfont', insideTextFontDefault);
  65791. }
  65792. if(hasOutside) coerceFont(coerce, 'outsidetextfont', dfltFont);
  65793. }
  65794. }
  65795. handleDomainDefaults(traceOut, layout, coerce);
  65796. var hole = coerce('hole');
  65797. var title = coerce('title.text');
  65798. if(title) {
  65799. var titlePosition = coerce('title.position', hole ? 'middle center' : 'top center');
  65800. if(!hole && titlePosition === 'middle center') traceOut.title.position = 'top center';
  65801. coerceFont(coerce, 'title.font', layout.font);
  65802. }
  65803. coerce('sort');
  65804. coerce('direction');
  65805. coerce('rotation');
  65806. coerce('pull');
  65807. };
  65808. },{"../../lib":168,"../../plots/domain":238,"./attributes":354}],358:[function(_dereq_,module,exports){
  65809. /**
  65810. * Copyright 2012-2019, Plotly, Inc.
  65811. * All rights reserved.
  65812. *
  65813. * This source code is licensed under the MIT license found in the
  65814. * LICENSE file in the root directory of this source tree.
  65815. */
  65816. 'use strict';
  65817. var appendArrayMultiPointValues = _dereq_('../../components/fx/helpers').appendArrayMultiPointValues;
  65818. // Note: like other eventData routines, this creates the data for hover/unhover/click events
  65819. // but it has a different API and goes through a totally different pathway.
  65820. // So to ensure it doesn't get misused, it's not attached to the Pie module.
  65821. module.exports = function eventData(pt, trace) {
  65822. var out = {
  65823. curveNumber: trace.index,
  65824. pointNumbers: pt.pts,
  65825. data: trace._input,
  65826. fullData: trace,
  65827. label: pt.label,
  65828. color: pt.color,
  65829. value: pt.v,
  65830. percent: pt.percent,
  65831. text: pt.text,
  65832. // pt.v (and pt.i below) for backward compatibility
  65833. v: pt.v
  65834. };
  65835. // Only include pointNumber if it's unambiguous
  65836. if(pt.pts.length === 1) out.pointNumber = out.i = pt.pts[0];
  65837. // Add extra data arrays to the output
  65838. // notice that this is the multi-point version ('s' on the end!)
  65839. // so added data will be arrays matching the pointNumbers array.
  65840. appendArrayMultiPointValues(out, trace, pt.pts);
  65841. return out;
  65842. };
  65843. },{"../../components/fx/helpers":86}],359:[function(_dereq_,module,exports){
  65844. /**
  65845. * Copyright 2012-2019, Plotly, Inc.
  65846. * All rights reserved.
  65847. *
  65848. * This source code is licensed under the MIT license found in the
  65849. * LICENSE file in the root directory of this source tree.
  65850. */
  65851. 'use strict';
  65852. var Lib = _dereq_('../../lib');
  65853. exports.formatPiePercent = function formatPiePercent(v, separators) {
  65854. var vRounded = (v * 100).toPrecision(3);
  65855. if(vRounded.lastIndexOf('.') !== -1) {
  65856. vRounded = vRounded.replace(/[.]?0+$/, '');
  65857. }
  65858. return Lib.numSeparate(vRounded, separators) + '%';
  65859. };
  65860. exports.formatPieValue = function formatPieValue(v, separators) {
  65861. var vRounded = v.toPrecision(10);
  65862. if(vRounded.lastIndexOf('.') !== -1) {
  65863. vRounded = vRounded.replace(/[.]?0+$/, '');
  65864. }
  65865. return Lib.numSeparate(vRounded, separators);
  65866. };
  65867. exports.getFirstFilled = function getFirstFilled(array, indices) {
  65868. if(!Array.isArray(array)) return;
  65869. for(var i = 0; i < indices.length; i++) {
  65870. var v = array[indices[i]];
  65871. if(v || v === 0) return v;
  65872. }
  65873. };
  65874. exports.castOption = function castOption(item, indices) {
  65875. if(Array.isArray(item)) return exports.getFirstFilled(item, indices);
  65876. else if(item) return item;
  65877. };
  65878. },{"../../lib":168}],360:[function(_dereq_,module,exports){
  65879. /**
  65880. * Copyright 2012-2019, Plotly, Inc.
  65881. * All rights reserved.
  65882. *
  65883. * This source code is licensed under the MIT license found in the
  65884. * LICENSE file in the root directory of this source tree.
  65885. */
  65886. 'use strict';
  65887. var Pie = {};
  65888. Pie.attributes = _dereq_('./attributes');
  65889. Pie.supplyDefaults = _dereq_('./defaults');
  65890. Pie.supplyLayoutDefaults = _dereq_('./layout_defaults');
  65891. Pie.layoutAttributes = _dereq_('./layout_attributes');
  65892. var calcModule = _dereq_('./calc');
  65893. Pie.calc = calcModule.calc;
  65894. Pie.crossTraceCalc = calcModule.crossTraceCalc;
  65895. Pie.plot = _dereq_('./plot');
  65896. Pie.style = _dereq_('./style');
  65897. Pie.styleOne = _dereq_('./style_one');
  65898. Pie.moduleType = 'trace';
  65899. Pie.name = 'pie';
  65900. Pie.basePlotModule = _dereq_('./base_plot');
  65901. Pie.categories = ['pie', 'showLegend'];
  65902. Pie.meta = {
  65903. };
  65904. module.exports = Pie;
  65905. },{"./attributes":354,"./base_plot":355,"./calc":356,"./defaults":357,"./layout_attributes":361,"./layout_defaults":362,"./plot":363,"./style":364,"./style_one":365}],361:[function(_dereq_,module,exports){
  65906. /**
  65907. * Copyright 2012-2019, Plotly, Inc.
  65908. * All rights reserved.
  65909. *
  65910. * This source code is licensed under the MIT license found in the
  65911. * LICENSE file in the root directory of this source tree.
  65912. */
  65913. 'use strict';
  65914. module.exports = {
  65915. /**
  65916. * hiddenlabels is the pie chart analog of visible:'legendonly'
  65917. * but it can contain many labels, and can hide slices
  65918. * from several pies simultaneously
  65919. */
  65920. hiddenlabels: {
  65921. valType: 'data_array',
  65922. editType: 'calc'
  65923. },
  65924. piecolorway: {
  65925. valType: 'colorlist',
  65926. editType: 'calc',
  65927. },
  65928. extendpiecolors: {
  65929. valType: 'boolean',
  65930. dflt: true,
  65931. editType: 'calc',
  65932. }
  65933. };
  65934. },{}],362:[function(_dereq_,module,exports){
  65935. /**
  65936. * Copyright 2012-2019, Plotly, Inc.
  65937. * All rights reserved.
  65938. *
  65939. * This source code is licensed under the MIT license found in the
  65940. * LICENSE file in the root directory of this source tree.
  65941. */
  65942. 'use strict';
  65943. var Lib = _dereq_('../../lib');
  65944. var layoutAttributes = _dereq_('./layout_attributes');
  65945. module.exports = function supplyLayoutDefaults(layoutIn, layoutOut) {
  65946. function coerce(attr, dflt) {
  65947. return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
  65948. }
  65949. coerce('hiddenlabels');
  65950. coerce('piecolorway', layoutOut.colorway);
  65951. coerce('extendpiecolors');
  65952. };
  65953. },{"../../lib":168,"./layout_attributes":361}],363:[function(_dereq_,module,exports){
  65954. /**
  65955. * Copyright 2012-2019, Plotly, Inc.
  65956. * All rights reserved.
  65957. *
  65958. * This source code is licensed under the MIT license found in the
  65959. * LICENSE file in the root directory of this source tree.
  65960. */
  65961. 'use strict';
  65962. var d3 = _dereq_('d3');
  65963. var Fx = _dereq_('../../components/fx');
  65964. var Color = _dereq_('../../components/color');
  65965. var Drawing = _dereq_('../../components/drawing');
  65966. var Lib = _dereq_('../../lib');
  65967. var svgTextUtils = _dereq_('../../lib/svg_text_utils');
  65968. var helpers = _dereq_('./helpers');
  65969. var eventData = _dereq_('./event_data');
  65970. module.exports = function plot(gd, cdpie) {
  65971. var fullLayout = gd._fullLayout;
  65972. prerenderTitles(cdpie, gd);
  65973. scalePies(cdpie, fullLayout._size);
  65974. var pieGroups = Lib.makeTraceGroups(fullLayout._pielayer, cdpie, 'trace').each(function(cd) {
  65975. var pieGroup = d3.select(this);
  65976. var cd0 = cd[0];
  65977. var trace = cd0.trace;
  65978. setCoords(cd);
  65979. // TODO: miter might look better but can sometimes cause problems
  65980. // maybe miter with a small-ish stroke-miterlimit?
  65981. pieGroup.attr('stroke-linejoin', 'round');
  65982. pieGroup.each(function() {
  65983. var slices = d3.select(this).selectAll('g.slice').data(cd);
  65984. slices.enter().append('g')
  65985. .classed('slice', true);
  65986. slices.exit().remove();
  65987. var quadrants = [
  65988. [[], []], // y<0: x<0, x>=0
  65989. [[], []] // y>=0: x<0, x>=0
  65990. ];
  65991. var hasOutsideText = false;
  65992. slices.each(function(pt) {
  65993. if(pt.hidden) {
  65994. d3.select(this).selectAll('path,g').remove();
  65995. return;
  65996. }
  65997. // to have consistent event data compared to other traces
  65998. pt.pointNumber = pt.i;
  65999. pt.curveNumber = trace.index;
  66000. quadrants[pt.pxmid[1] < 0 ? 0 : 1][pt.pxmid[0] < 0 ? 0 : 1].push(pt);
  66001. var cx = cd0.cx;
  66002. var cy = cd0.cy;
  66003. var sliceTop = d3.select(this);
  66004. var slicePath = sliceTop.selectAll('path.surface').data([pt]);
  66005. // hover state vars
  66006. // have we drawn a hover label, so it should be cleared later
  66007. var hasHoverLabel = false;
  66008. // have we emitted a hover event, so later an unhover event should be emitted
  66009. // note that click events do not depend on this - you can still get them
  66010. // with hovermode: false or if you were earlier dragging, then clicked
  66011. // in the same slice that you moused up in
  66012. var hasHoverEvent = false;
  66013. function handleMouseOver() {
  66014. // in case fullLayout or fullData has changed without a replot
  66015. var fullLayout2 = gd._fullLayout;
  66016. var trace2 = gd._fullData[trace.index];
  66017. if(gd._dragging || fullLayout2.hovermode === false) return;
  66018. var hoverinfo = trace2.hoverinfo;
  66019. if(Array.isArray(hoverinfo)) {
  66020. // super hacky: we need to pull out the *first* hoverinfo from
  66021. // pt.pts, then put it back into an array in a dummy trace
  66022. // and call castHoverinfo on that.
  66023. // TODO: do we want to have Fx.castHoverinfo somehow handle this?
  66024. // it already takes an array for index, for 2D, so this seems tricky.
  66025. hoverinfo = Fx.castHoverinfo({
  66026. hoverinfo: [helpers.castOption(hoverinfo, pt.pts)],
  66027. _module: trace._module
  66028. }, fullLayout2, 0);
  66029. }
  66030. if(hoverinfo === 'all') hoverinfo = 'label+text+value+percent+name';
  66031. // in case we dragged over the pie from another subplot,
  66032. // or if hover is turned off
  66033. if(trace2.hovertemplate || (hoverinfo !== 'none' && hoverinfo !== 'skip' && hoverinfo)) {
  66034. var rInscribed = getInscribedRadiusFraction(pt, cd0);
  66035. var hoverCenterX = cx + pt.pxmid[0] * (1 - rInscribed);
  66036. var hoverCenterY = cy + pt.pxmid[1] * (1 - rInscribed);
  66037. var separators = fullLayout.separators;
  66038. var thisText = [];
  66039. if(hoverinfo && hoverinfo.indexOf('label') !== -1) thisText.push(pt.label);
  66040. pt.text = helpers.castOption(trace2.hovertext || trace2.text, pt.pts);
  66041. if(hoverinfo && hoverinfo.indexOf('text') !== -1) {
  66042. var texti = pt.text;
  66043. if(texti) thisText.push(texti);
  66044. }
  66045. pt.value = pt.v;
  66046. pt.valueLabel = helpers.formatPieValue(pt.v, separators);
  66047. if(hoverinfo && hoverinfo.indexOf('value') !== -1) thisText.push(pt.valueLabel);
  66048. pt.percent = pt.v / cd0.vTotal;
  66049. pt.percentLabel = helpers.formatPiePercent(pt.percent, separators);
  66050. if(hoverinfo && hoverinfo.indexOf('percent') !== -1) thisText.push(pt.percentLabel);
  66051. var hoverLabel = trace.hoverlabel;
  66052. var hoverFont = hoverLabel.font;
  66053. Fx.loneHover({
  66054. x0: hoverCenterX - rInscribed * cd0.r,
  66055. x1: hoverCenterX + rInscribed * cd0.r,
  66056. y: hoverCenterY,
  66057. text: thisText.join('<br>'),
  66058. name: (trace2.hovertemplate || hoverinfo.indexOf('name') !== -1) ? trace2.name : undefined,
  66059. idealAlign: pt.pxmid[0] < 0 ? 'left' : 'right',
  66060. color: helpers.castOption(hoverLabel.bgcolor, pt.pts) || pt.color,
  66061. borderColor: helpers.castOption(hoverLabel.bordercolor, pt.pts),
  66062. fontFamily: helpers.castOption(hoverFont.family, pt.pts),
  66063. fontSize: helpers.castOption(hoverFont.size, pt.pts),
  66064. fontColor: helpers.castOption(hoverFont.color, pt.pts),
  66065. trace: trace2,
  66066. hovertemplate: helpers.castOption(trace2.hovertemplate, pt.pts),
  66067. hovertemplateLabels: pt,
  66068. eventData: [eventData(pt, trace2)]
  66069. }, {
  66070. container: fullLayout2._hoverlayer.node(),
  66071. outerContainer: fullLayout2._paper.node(),
  66072. gd: gd
  66073. });
  66074. hasHoverLabel = true;
  66075. }
  66076. gd.emit('plotly_hover', {
  66077. points: [eventData(pt, trace2)],
  66078. event: d3.event
  66079. });
  66080. hasHoverEvent = true;
  66081. }
  66082. function handleMouseOut(evt) {
  66083. var fullLayout2 = gd._fullLayout;
  66084. var trace2 = gd._fullData[trace.index];
  66085. if(hasHoverEvent) {
  66086. evt.originalEvent = d3.event;
  66087. gd.emit('plotly_unhover', {
  66088. points: [eventData(pt, trace2)],
  66089. event: d3.event
  66090. });
  66091. hasHoverEvent = false;
  66092. }
  66093. if(hasHoverLabel) {
  66094. Fx.loneUnhover(fullLayout2._hoverlayer.node());
  66095. hasHoverLabel = false;
  66096. }
  66097. }
  66098. function handleClick() {
  66099. // TODO: this does not support right-click. If we want to support it, we
  66100. // would likely need to change pie to use dragElement instead of straight
  66101. // mapbox event binding. Or perhaps better, make a simple wrapper with the
  66102. // right mousedown, mousemove, and mouseup handlers just for a left/right click
  66103. // mapbox would use this too.
  66104. var fullLayout2 = gd._fullLayout;
  66105. var trace2 = gd._fullData[trace.index];
  66106. if(gd._dragging || fullLayout2.hovermode === false) return;
  66107. gd._hoverdata = [eventData(pt, trace2)];
  66108. Fx.click(gd, d3.event);
  66109. }
  66110. slicePath.enter().append('path')
  66111. .classed('surface', true)
  66112. .style({'pointer-events': 'all'});
  66113. sliceTop.select('path.textline').remove();
  66114. sliceTop
  66115. .on('mouseover', handleMouseOver)
  66116. .on('mouseout', handleMouseOut)
  66117. .on('click', handleClick);
  66118. if(trace.pull) {
  66119. var pull = +helpers.castOption(trace.pull, pt.pts) || 0;
  66120. if(pull > 0) {
  66121. cx += pull * pt.pxmid[0];
  66122. cy += pull * pt.pxmid[1];
  66123. }
  66124. }
  66125. pt.cxFinal = cx;
  66126. pt.cyFinal = cy;
  66127. function arc(start, finish, cw, scale) {
  66128. return 'a' + (scale * cd0.r) + ',' + (scale * cd0.r) + ' 0 ' +
  66129. pt.largeArc + (cw ? ' 1 ' : ' 0 ') +
  66130. (scale * (finish[0] - start[0])) + ',' + (scale * (finish[1] - start[1]));
  66131. }
  66132. var hole = trace.hole;
  66133. if(pt.v === cd0.vTotal) { // 100% fails bcs arc start and end are identical
  66134. var outerCircle = 'M' + (cx + pt.px0[0]) + ',' + (cy + pt.px0[1]) +
  66135. arc(pt.px0, pt.pxmid, true, 1) +
  66136. arc(pt.pxmid, pt.px0, true, 1) + 'Z';
  66137. if(hole) {
  66138. slicePath.attr('d',
  66139. 'M' + (cx + hole * pt.px0[0]) + ',' + (cy + hole * pt.px0[1]) +
  66140. arc(pt.px0, pt.pxmid, false, hole) +
  66141. arc(pt.pxmid, pt.px0, false, hole) +
  66142. 'Z' + outerCircle);
  66143. }
  66144. else slicePath.attr('d', outerCircle);
  66145. } else {
  66146. var outerArc = arc(pt.px0, pt.px1, true, 1);
  66147. if(hole) {
  66148. var rim = 1 - hole;
  66149. slicePath.attr('d',
  66150. 'M' + (cx + hole * pt.px1[0]) + ',' + (cy + hole * pt.px1[1]) +
  66151. arc(pt.px1, pt.px0, false, hole) +
  66152. 'l' + (rim * pt.px0[0]) + ',' + (rim * pt.px0[1]) +
  66153. outerArc +
  66154. 'Z');
  66155. } else {
  66156. slicePath.attr('d',
  66157. 'M' + cx + ',' + cy +
  66158. 'l' + pt.px0[0] + ',' + pt.px0[1] +
  66159. outerArc +
  66160. 'Z');
  66161. }
  66162. }
  66163. // add text
  66164. var textPosition = helpers.castOption(trace.textposition, pt.pts);
  66165. var sliceTextGroup = sliceTop.selectAll('g.slicetext')
  66166. .data(pt.text && (textPosition !== 'none') ? [0] : []);
  66167. sliceTextGroup.enter().append('g')
  66168. .classed('slicetext', true);
  66169. sliceTextGroup.exit().remove();
  66170. sliceTextGroup.each(function() {
  66171. var sliceText = Lib.ensureSingle(d3.select(this), 'text', '', function(s) {
  66172. // prohibit tex interpretation until we can handle
  66173. // tex and regular text together
  66174. s.attr('data-notex', 1);
  66175. });
  66176. sliceText.text(pt.text)
  66177. .attr({
  66178. 'class': 'slicetext',
  66179. transform: '',
  66180. 'text-anchor': 'middle'
  66181. })
  66182. .call(Drawing.font, textPosition === 'outside' ?
  66183. determineOutsideTextFont(trace, pt, gd._fullLayout.font) :
  66184. determineInsideTextFont(trace, pt, gd._fullLayout.font))
  66185. .call(svgTextUtils.convertToTspans, gd);
  66186. // position the text relative to the slice
  66187. var textBB = Drawing.bBox(sliceText.node());
  66188. var transform;
  66189. if(textPosition === 'outside') {
  66190. transform = transformOutsideText(textBB, pt);
  66191. } else {
  66192. transform = transformInsideText(textBB, pt, cd0);
  66193. if(textPosition === 'auto' && transform.scale < 1) {
  66194. sliceText.call(Drawing.font, trace.outsidetextfont);
  66195. if(trace.outsidetextfont.family !== trace.insidetextfont.family ||
  66196. trace.outsidetextfont.size !== trace.insidetextfont.size) {
  66197. textBB = Drawing.bBox(sliceText.node());
  66198. }
  66199. transform = transformOutsideText(textBB, pt);
  66200. }
  66201. }
  66202. var translateX = cx + pt.pxmid[0] * transform.rCenter + (transform.x || 0);
  66203. var translateY = cy + pt.pxmid[1] * transform.rCenter + (transform.y || 0);
  66204. // save some stuff to use later ensure no labels overlap
  66205. if(transform.outside) {
  66206. pt.yLabelMin = translateY - textBB.height / 2;
  66207. pt.yLabelMid = translateY;
  66208. pt.yLabelMax = translateY + textBB.height / 2;
  66209. pt.labelExtraX = 0;
  66210. pt.labelExtraY = 0;
  66211. hasOutsideText = true;
  66212. }
  66213. sliceText.attr('transform',
  66214. 'translate(' + translateX + ',' + translateY + ')' +
  66215. (transform.scale < 1 ? ('scale(' + transform.scale + ')') : '') +
  66216. (transform.rotate ? ('rotate(' + transform.rotate + ')') : '') +
  66217. 'translate(' +
  66218. (-(textBB.left + textBB.right) / 2) + ',' +
  66219. (-(textBB.top + textBB.bottom) / 2) +
  66220. ')');
  66221. });
  66222. });
  66223. // add the title
  66224. var titleTextGroup = d3.select(this).selectAll('g.titletext')
  66225. .data(trace.title.text ? [0] : []);
  66226. titleTextGroup.enter().append('g')
  66227. .classed('titletext', true);
  66228. titleTextGroup.exit().remove();
  66229. titleTextGroup.each(function() {
  66230. var titleText = Lib.ensureSingle(d3.select(this), 'text', '', function(s) {
  66231. // prohibit tex interpretation as above
  66232. s.attr('data-notex', 1);
  66233. });
  66234. var txt = fullLayout.meta ?
  66235. Lib.templateString(trace.title.text, {meta: fullLayout.meta}) :
  66236. trace.title.text;
  66237. titleText.text(txt)
  66238. .attr({
  66239. 'class': 'titletext',
  66240. transform: '',
  66241. 'text-anchor': 'middle',
  66242. })
  66243. .call(Drawing.font, trace.title.font)
  66244. .call(svgTextUtils.convertToTspans, gd);
  66245. var transform;
  66246. if(trace.title.position === 'middle center') {
  66247. transform = positionTitleInside(cd0);
  66248. } else {
  66249. transform = positionTitleOutside(cd0, fullLayout._size);
  66250. }
  66251. titleText.attr('transform',
  66252. 'translate(' + transform.x + ',' + transform.y + ')' +
  66253. (transform.scale < 1 ? ('scale(' + transform.scale + ')') : '') +
  66254. 'translate(' + transform.tx + ',' + transform.ty + ')');
  66255. });
  66256. // now make sure no labels overlap (at least within one pie)
  66257. if(hasOutsideText) scootLabels(quadrants, trace);
  66258. slices.each(function(pt) {
  66259. if(pt.labelExtraX || pt.labelExtraY) {
  66260. // first move the text to its new location
  66261. var sliceTop = d3.select(this);
  66262. var sliceText = sliceTop.select('g.slicetext text');
  66263. sliceText.attr('transform', 'translate(' + pt.labelExtraX + ',' + pt.labelExtraY + ')' +
  66264. sliceText.attr('transform'));
  66265. // then add a line to the new location
  66266. var lineStartX = pt.cxFinal + pt.pxmid[0];
  66267. var lineStartY = pt.cyFinal + pt.pxmid[1];
  66268. var textLinePath = 'M' + lineStartX + ',' + lineStartY;
  66269. var finalX = (pt.yLabelMax - pt.yLabelMin) * (pt.pxmid[0] < 0 ? -1 : 1) / 4;
  66270. if(pt.labelExtraX) {
  66271. var yFromX = pt.labelExtraX * pt.pxmid[1] / pt.pxmid[0];
  66272. var yNet = pt.yLabelMid + pt.labelExtraY - (pt.cyFinal + pt.pxmid[1]);
  66273. if(Math.abs(yFromX) > Math.abs(yNet)) {
  66274. textLinePath +=
  66275. 'l' + (yNet * pt.pxmid[0] / pt.pxmid[1]) + ',' + yNet +
  66276. 'H' + (lineStartX + pt.labelExtraX + finalX);
  66277. } else {
  66278. textLinePath += 'l' + pt.labelExtraX + ',' + yFromX +
  66279. 'v' + (yNet - yFromX) +
  66280. 'h' + finalX;
  66281. }
  66282. } else {
  66283. textLinePath +=
  66284. 'V' + (pt.yLabelMid + pt.labelExtraY) +
  66285. 'h' + finalX;
  66286. }
  66287. sliceTop.append('path')
  66288. .classed('textline', true)
  66289. .call(Color.stroke, trace.outsidetextfont.color)
  66290. .attr({
  66291. 'stroke-width': Math.min(2, trace.outsidetextfont.size / 8),
  66292. d: textLinePath,
  66293. fill: 'none'
  66294. });
  66295. }
  66296. });
  66297. });
  66298. });
  66299. // This is for a bug in Chrome (as of 2015-07-22, and does not affect FF)
  66300. // if insidetextfont and outsidetextfont are different sizes, sometimes the size
  66301. // of an "em" gets taken from the wrong element at first so lines are
  66302. // spaced wrong. You just have to tell it to try again later and it gets fixed.
  66303. // I have no idea why we haven't seen this in other contexts. Also, sometimes
  66304. // it gets the initial draw correct but on redraw it gets confused.
  66305. setTimeout(function() {
  66306. pieGroups.selectAll('tspan').each(function() {
  66307. var s = d3.select(this);
  66308. if(s.attr('dy')) s.attr('dy', s.attr('dy'));
  66309. });
  66310. }, 0);
  66311. };
  66312. function determineOutsideTextFont(trace, pt, layoutFont) {
  66313. var color = helpers.castOption(trace.outsidetextfont.color, pt.pts) ||
  66314. helpers.castOption(trace.textfont.color, pt.pts) ||
  66315. layoutFont.color;
  66316. var family = helpers.castOption(trace.outsidetextfont.family, pt.pts) ||
  66317. helpers.castOption(trace.textfont.family, pt.pts) ||
  66318. layoutFont.family;
  66319. var size = helpers.castOption(trace.outsidetextfont.size, pt.pts) ||
  66320. helpers.castOption(trace.textfont.size, pt.pts) ||
  66321. layoutFont.size;
  66322. return {
  66323. color: color,
  66324. family: family,
  66325. size: size
  66326. };
  66327. }
  66328. function determineInsideTextFont(trace, pt, layoutFont) {
  66329. var customColor = helpers.castOption(trace.insidetextfont.color, pt.pts);
  66330. if(!customColor && trace._input.textfont) {
  66331. // Why not simply using trace.textfont? Because if not set, it
  66332. // defaults to layout.font which has a default color. But if
  66333. // textfont.color and insidetextfont.color don't supply a value,
  66334. // a contrasting color shall be used.
  66335. customColor = helpers.castOption(trace._input.textfont.color, pt.pts);
  66336. }
  66337. var family = helpers.castOption(trace.insidetextfont.family, pt.pts) ||
  66338. helpers.castOption(trace.textfont.family, pt.pts) ||
  66339. layoutFont.family;
  66340. var size = helpers.castOption(trace.insidetextfont.size, pt.pts) ||
  66341. helpers.castOption(trace.textfont.size, pt.pts) ||
  66342. layoutFont.size;
  66343. return {
  66344. color: customColor || Color.contrast(pt.color),
  66345. family: family,
  66346. size: size
  66347. };
  66348. }
  66349. function prerenderTitles(cdpie, gd) {
  66350. var fullLayout = gd._fullLayout;
  66351. var cd0, trace;
  66352. // Determine the width and height of the title for each pie.
  66353. for(var i = 0; i < cdpie.length; i++) {
  66354. cd0 = cdpie[i][0];
  66355. trace = cd0.trace;
  66356. if(trace.title.text) {
  66357. var txt = fullLayout.meta ?
  66358. Lib.templateString(trace.title.text, {meta: fullLayout.meta}) :
  66359. trace.title.text;
  66360. var dummyTitle = Drawing.tester.append('text')
  66361. .attr('data-notex', 1)
  66362. .text(txt)
  66363. .call(Drawing.font, trace.title.font)
  66364. .call(svgTextUtils.convertToTspans, gd);
  66365. var bBox = Drawing.bBox(dummyTitle.node(), true);
  66366. cd0.titleBox = {
  66367. width: bBox.width,
  66368. height: bBox.height,
  66369. };
  66370. dummyTitle.remove();
  66371. }
  66372. }
  66373. }
  66374. function transformInsideText(textBB, pt, cd0) {
  66375. var textDiameter = Math.sqrt(textBB.width * textBB.width + textBB.height * textBB.height);
  66376. var textAspect = textBB.width / textBB.height;
  66377. var halfAngle = Math.PI * Math.min(pt.v / cd0.vTotal, 0.5);
  66378. var ring = 1 - cd0.trace.hole;
  66379. var rInscribed = getInscribedRadiusFraction(pt, cd0);
  66380. // max size text can be inserted inside without rotating it
  66381. // this inscribes the text rectangle in a circle, which is then inscribed
  66382. // in the slice, so it will be an underestimate, which some day we may want
  66383. // to improve so this case can get more use
  66384. var transform = {
  66385. scale: rInscribed * cd0.r * 2 / textDiameter,
  66386. // and the center position and rotation in this case
  66387. rCenter: 1 - rInscribed,
  66388. rotate: 0
  66389. };
  66390. if(transform.scale >= 1) return transform;
  66391. // max size if text is rotated radially
  66392. var Qr = textAspect + 1 / (2 * Math.tan(halfAngle));
  66393. var maxHalfHeightRotRadial = cd0.r * Math.min(
  66394. 1 / (Math.sqrt(Qr * Qr + 0.5) + Qr),
  66395. ring / (Math.sqrt(textAspect * textAspect + ring / 2) + textAspect)
  66396. );
  66397. var radialTransform = {
  66398. scale: maxHalfHeightRotRadial * 2 / textBB.height,
  66399. rCenter: Math.cos(maxHalfHeightRotRadial / cd0.r) -
  66400. maxHalfHeightRotRadial * textAspect / cd0.r,
  66401. rotate: (180 / Math.PI * pt.midangle + 720) % 180 - 90
  66402. };
  66403. // max size if text is rotated tangentially
  66404. var aspectInv = 1 / textAspect;
  66405. var Qt = aspectInv + 1 / (2 * Math.tan(halfAngle));
  66406. var maxHalfWidthTangential = cd0.r * Math.min(
  66407. 1 / (Math.sqrt(Qt * Qt + 0.5) + Qt),
  66408. ring / (Math.sqrt(aspectInv * aspectInv + ring / 2) + aspectInv)
  66409. );
  66410. var tangentialTransform = {
  66411. scale: maxHalfWidthTangential * 2 / textBB.width,
  66412. rCenter: Math.cos(maxHalfWidthTangential / cd0.r) -
  66413. maxHalfWidthTangential / textAspect / cd0.r,
  66414. rotate: (180 / Math.PI * pt.midangle + 810) % 180 - 90
  66415. };
  66416. // if we need a rotated transform, pick the biggest one
  66417. // even if both are bigger than 1
  66418. var rotatedTransform = tangentialTransform.scale > radialTransform.scale ?
  66419. tangentialTransform : radialTransform;
  66420. if(transform.scale < 1 && rotatedTransform.scale > transform.scale) return rotatedTransform;
  66421. return transform;
  66422. }
  66423. function getInscribedRadiusFraction(pt, cd0) {
  66424. if(pt.v === cd0.vTotal && !cd0.trace.hole) return 1;// special case of 100% with no hole
  66425. var halfAngle = Math.PI * Math.min(pt.v / cd0.vTotal, 0.5);
  66426. return Math.min(1 / (1 + 1 / Math.sin(halfAngle)), (1 - cd0.trace.hole) / 2);
  66427. }
  66428. function transformOutsideText(textBB, pt) {
  66429. var x = pt.pxmid[0];
  66430. var y = pt.pxmid[1];
  66431. var dx = textBB.width / 2;
  66432. var dy = textBB.height / 2;
  66433. if(x < 0) dx *= -1;
  66434. if(y < 0) dy *= -1;
  66435. return {
  66436. scale: 1,
  66437. rCenter: 1,
  66438. rotate: 0,
  66439. x: dx + Math.abs(dy) * (dx > 0 ? 1 : -1) / 2,
  66440. y: dy / (1 + x * x / (y * y)),
  66441. outside: true
  66442. };
  66443. }
  66444. function positionTitleInside(cd0) {
  66445. var textDiameter =
  66446. Math.sqrt(cd0.titleBox.width * cd0.titleBox.width + cd0.titleBox.height * cd0.titleBox.height);
  66447. return {
  66448. x: cd0.cx,
  66449. y: cd0.cy,
  66450. scale: cd0.trace.hole * cd0.r * 2 / textDiameter,
  66451. tx: 0,
  66452. ty: - cd0.titleBox.height / 2 + cd0.trace.title.font.size
  66453. };
  66454. }
  66455. function positionTitleOutside(cd0, plotSize) {
  66456. var scaleX = 1;
  66457. var scaleY = 1;
  66458. var maxWidth, maxPull;
  66459. var trace = cd0.trace;
  66460. // position of the baseline point of the text box in the plot, before scaling.
  66461. // we anchored the text in the middle, so the baseline is on the bottom middle
  66462. // of the first line of text.
  66463. var topMiddle = {
  66464. x: cd0.cx,
  66465. y: cd0.cy
  66466. };
  66467. // relative translation of the text box after scaling
  66468. var translate = {
  66469. tx: 0,
  66470. ty: 0
  66471. };
  66472. // we reason below as if the baseline is the top middle point of the text box.
  66473. // so we must add the font size to approximate the y-coord. of the top.
  66474. // note that this correction must happen after scaling.
  66475. translate.ty += trace.title.font.size;
  66476. maxPull = getMaxPull(trace);
  66477. if(trace.title.position.indexOf('top') !== -1) {
  66478. topMiddle.y -= (1 + maxPull) * cd0.r;
  66479. translate.ty -= cd0.titleBox.height;
  66480. }
  66481. else if(trace.title.position.indexOf('bottom') !== -1) {
  66482. topMiddle.y += (1 + maxPull) * cd0.r;
  66483. }
  66484. if(trace.title.position.indexOf('left') !== -1) {
  66485. // we start the text at the left edge of the pie
  66486. maxWidth = plotSize.w * (trace.domain.x[1] - trace.domain.x[0]) / 2 + cd0.r;
  66487. topMiddle.x -= (1 + maxPull) * cd0.r;
  66488. translate.tx += cd0.titleBox.width / 2;
  66489. } else if(trace.title.position.indexOf('center') !== -1) {
  66490. maxWidth = plotSize.w * (trace.domain.x[1] - trace.domain.x[0]);
  66491. } else if(trace.title.position.indexOf('right') !== -1) {
  66492. maxWidth = plotSize.w * (trace.domain.x[1] - trace.domain.x[0]) / 2 + cd0.r;
  66493. topMiddle.x += (1 + maxPull) * cd0.r;
  66494. translate.tx -= cd0.titleBox.width / 2;
  66495. }
  66496. scaleX = maxWidth / cd0.titleBox.width;
  66497. scaleY = getTitleSpace(cd0, plotSize) / cd0.titleBox.height;
  66498. return {
  66499. x: topMiddle.x,
  66500. y: topMiddle.y,
  66501. scale: Math.min(scaleX, scaleY),
  66502. tx: translate.tx,
  66503. ty: translate.ty
  66504. };
  66505. }
  66506. function getTitleSpace(cd0, plotSize) {
  66507. var trace = cd0.trace;
  66508. var pieBoxHeight = plotSize.h * (trace.domain.y[1] - trace.domain.y[0]);
  66509. // use at most half of the plot for the title
  66510. return Math.min(cd0.titleBox.height, pieBoxHeight / 2);
  66511. }
  66512. function getMaxPull(trace) {
  66513. var maxPull = trace.pull;
  66514. var j;
  66515. if(Array.isArray(maxPull)) {
  66516. maxPull = 0;
  66517. for(j = 0; j < trace.pull.length; j++) {
  66518. if(trace.pull[j] > maxPull) maxPull = trace.pull[j];
  66519. }
  66520. }
  66521. return maxPull;
  66522. }
  66523. function scootLabels(quadrants, trace) {
  66524. var xHalf, yHalf, equatorFirst, farthestX, farthestY,
  66525. xDiffSign, yDiffSign, thisQuad, oppositeQuad,
  66526. wholeSide, i, thisQuadOutside, firstOppositeOutsidePt;
  66527. function topFirst(a, b) { return a.pxmid[1] - b.pxmid[1]; }
  66528. function bottomFirst(a, b) { return b.pxmid[1] - a.pxmid[1]; }
  66529. function scootOneLabel(thisPt, prevPt) {
  66530. if(!prevPt) prevPt = {};
  66531. var prevOuterY = prevPt.labelExtraY + (yHalf ? prevPt.yLabelMax : prevPt.yLabelMin);
  66532. var thisInnerY = yHalf ? thisPt.yLabelMin : thisPt.yLabelMax;
  66533. var thisOuterY = yHalf ? thisPt.yLabelMax : thisPt.yLabelMin;
  66534. var thisSliceOuterY = thisPt.cyFinal + farthestY(thisPt.px0[1], thisPt.px1[1]);
  66535. var newExtraY = prevOuterY - thisInnerY;
  66536. var xBuffer, i, otherPt, otherOuterY, otherOuterX, newExtraX;
  66537. // make sure this label doesn't overlap other labels
  66538. // this *only* has us move these labels vertically
  66539. if(newExtraY * yDiffSign > 0) thisPt.labelExtraY = newExtraY;
  66540. // make sure this label doesn't overlap any slices
  66541. if(!Array.isArray(trace.pull)) return; // this can only happen with array pulls
  66542. for(i = 0; i < wholeSide.length; i++) {
  66543. otherPt = wholeSide[i];
  66544. // overlap can only happen if the other point is pulled more than this one
  66545. if(otherPt === thisPt || (
  66546. (helpers.castOption(trace.pull, thisPt.pts) || 0) >=
  66547. (helpers.castOption(trace.pull, otherPt.pts) || 0))
  66548. ) {
  66549. continue;
  66550. }
  66551. if((thisPt.pxmid[1] - otherPt.pxmid[1]) * yDiffSign > 0) {
  66552. // closer to the equator - by construction all of these happen first
  66553. // move the text vertically to get away from these slices
  66554. otherOuterY = otherPt.cyFinal + farthestY(otherPt.px0[1], otherPt.px1[1]);
  66555. newExtraY = otherOuterY - thisInnerY - thisPt.labelExtraY;
  66556. if(newExtraY * yDiffSign > 0) thisPt.labelExtraY += newExtraY;
  66557. } else if((thisOuterY + thisPt.labelExtraY - thisSliceOuterY) * yDiffSign > 0) {
  66558. // farther from the equator - happens after we've done all the
  66559. // vertical moving we're going to do
  66560. // move horizontally to get away from these more polar slices
  66561. // if we're moving horz. based on a slice that's several slices away from this one
  66562. // then we need some extra space for the lines to labels between them
  66563. xBuffer = 3 * xDiffSign * Math.abs(i - wholeSide.indexOf(thisPt));
  66564. otherOuterX = otherPt.cxFinal + farthestX(otherPt.px0[0], otherPt.px1[0]);
  66565. newExtraX = otherOuterX + xBuffer - (thisPt.cxFinal + thisPt.pxmid[0]) - thisPt.labelExtraX;
  66566. if(newExtraX * xDiffSign > 0) thisPt.labelExtraX += newExtraX;
  66567. }
  66568. }
  66569. }
  66570. for(yHalf = 0; yHalf < 2; yHalf++) {
  66571. equatorFirst = yHalf ? topFirst : bottomFirst;
  66572. farthestY = yHalf ? Math.max : Math.min;
  66573. yDiffSign = yHalf ? 1 : -1;
  66574. for(xHalf = 0; xHalf < 2; xHalf++) {
  66575. farthestX = xHalf ? Math.max : Math.min;
  66576. xDiffSign = xHalf ? 1 : -1;
  66577. // first sort the array
  66578. // note this is a copy of cd, so cd itself doesn't get sorted
  66579. // but we can still modify points in place.
  66580. thisQuad = quadrants[yHalf][xHalf];
  66581. thisQuad.sort(equatorFirst);
  66582. oppositeQuad = quadrants[1 - yHalf][xHalf];
  66583. wholeSide = oppositeQuad.concat(thisQuad);
  66584. thisQuadOutside = [];
  66585. for(i = 0; i < thisQuad.length; i++) {
  66586. if(thisQuad[i].yLabelMid !== undefined) thisQuadOutside.push(thisQuad[i]);
  66587. }
  66588. firstOppositeOutsidePt = false;
  66589. for(i = 0; yHalf && i < oppositeQuad.length; i++) {
  66590. if(oppositeQuad[i].yLabelMid !== undefined) {
  66591. firstOppositeOutsidePt = oppositeQuad[i];
  66592. break;
  66593. }
  66594. }
  66595. // each needs to avoid the previous
  66596. for(i = 0; i < thisQuadOutside.length; i++) {
  66597. var prevPt = i && thisQuadOutside[i - 1];
  66598. // bottom half needs to avoid the first label of the top half
  66599. // top half we still need to call scootOneLabel on the first slice
  66600. // so we can avoid other slices, but we don't pass a prevPt
  66601. if(firstOppositeOutsidePt && !i) prevPt = firstOppositeOutsidePt;
  66602. scootOneLabel(thisQuadOutside[i], prevPt);
  66603. }
  66604. }
  66605. }
  66606. }
  66607. function scalePies(cdpie, plotSize) {
  66608. var scaleGroups = [];
  66609. var pieBoxWidth, pieBoxHeight, i, j, cd0, trace,
  66610. maxPull, scaleGroup, minPxPerValUnit;
  66611. // first figure out the center and maximum radius for each pie
  66612. for(i = 0; i < cdpie.length; i++) {
  66613. cd0 = cdpie[i][0];
  66614. trace = cd0.trace;
  66615. pieBoxWidth = plotSize.w * (trace.domain.x[1] - trace.domain.x[0]);
  66616. pieBoxHeight = plotSize.h * (trace.domain.y[1] - trace.domain.y[0]);
  66617. // leave some space for the title, if it will be displayed outside
  66618. if(trace.title.text && trace.title.position !== 'middle center') {
  66619. pieBoxHeight -= getTitleSpace(cd0, plotSize);
  66620. }
  66621. maxPull = getMaxPull(trace);
  66622. cd0.r = Math.min(pieBoxWidth, pieBoxHeight) / (2 + 2 * maxPull);
  66623. cd0.cx = plotSize.l + plotSize.w * (trace.domain.x[1] + trace.domain.x[0]) / 2;
  66624. cd0.cy = plotSize.t + plotSize.h * (1 - trace.domain.y[0]) - pieBoxHeight / 2;
  66625. if(trace.title.text && trace.title.position.indexOf('bottom') !== -1) {
  66626. cd0.cy -= getTitleSpace(cd0, plotSize);
  66627. }
  66628. if(trace.scalegroup && scaleGroups.indexOf(trace.scalegroup) === -1) {
  66629. scaleGroups.push(trace.scalegroup);
  66630. }
  66631. }
  66632. // Then scale any pies that are grouped
  66633. for(j = 0; j < scaleGroups.length; j++) {
  66634. minPxPerValUnit = Infinity;
  66635. scaleGroup = scaleGroups[j];
  66636. for(i = 0; i < cdpie.length; i++) {
  66637. cd0 = cdpie[i][0];
  66638. if(cd0.trace.scalegroup === scaleGroup) {
  66639. minPxPerValUnit = Math.min(minPxPerValUnit,
  66640. cd0.r * cd0.r / cd0.vTotal);
  66641. }
  66642. }
  66643. for(i = 0; i < cdpie.length; i++) {
  66644. cd0 = cdpie[i][0];
  66645. if(cd0.trace.scalegroup === scaleGroup) {
  66646. cd0.r = Math.sqrt(minPxPerValUnit * cd0.vTotal);
  66647. }
  66648. }
  66649. }
  66650. }
  66651. function setCoords(cd) {
  66652. var cd0 = cd[0];
  66653. var trace = cd0.trace;
  66654. var currentAngle = trace.rotation * Math.PI / 180;
  66655. var angleFactor = 2 * Math.PI / cd0.vTotal;
  66656. var firstPt = 'px0';
  66657. var lastPt = 'px1';
  66658. var i, cdi, currentCoords;
  66659. if(trace.direction === 'counterclockwise') {
  66660. for(i = 0; i < cd.length; i++) {
  66661. if(!cd[i].hidden) break; // find the first non-hidden slice
  66662. }
  66663. if(i === cd.length) return; // all slices hidden
  66664. currentAngle += angleFactor * cd[i].v;
  66665. angleFactor *= -1;
  66666. firstPt = 'px1';
  66667. lastPt = 'px0';
  66668. }
  66669. function getCoords(angle) {
  66670. return [cd0.r * Math.sin(angle), -cd0.r * Math.cos(angle)];
  66671. }
  66672. currentCoords = getCoords(currentAngle);
  66673. for(i = 0; i < cd.length; i++) {
  66674. cdi = cd[i];
  66675. if(cdi.hidden) continue;
  66676. cdi[firstPt] = currentCoords;
  66677. currentAngle += angleFactor * cdi.v / 2;
  66678. cdi.pxmid = getCoords(currentAngle);
  66679. cdi.midangle = currentAngle;
  66680. currentAngle += angleFactor * cdi.v / 2;
  66681. currentCoords = getCoords(currentAngle);
  66682. cdi[lastPt] = currentCoords;
  66683. cdi.largeArc = (cdi.v > cd0.vTotal / 2) ? 1 : 0;
  66684. }
  66685. }
  66686. },{"../../components/color":51,"../../components/drawing":72,"../../components/fx":90,"../../lib":168,"../../lib/svg_text_utils":189,"./event_data":358,"./helpers":359,"d3":16}],364:[function(_dereq_,module,exports){
  66687. /**
  66688. * Copyright 2012-2019, Plotly, Inc.
  66689. * All rights reserved.
  66690. *
  66691. * This source code is licensed under the MIT license found in the
  66692. * LICENSE file in the root directory of this source tree.
  66693. */
  66694. 'use strict';
  66695. var d3 = _dereq_('d3');
  66696. var styleOne = _dereq_('./style_one');
  66697. module.exports = function style(gd) {
  66698. gd._fullLayout._pielayer.selectAll('.trace').each(function(cd) {
  66699. var cd0 = cd[0];
  66700. var trace = cd0.trace;
  66701. var traceSelection = d3.select(this);
  66702. traceSelection.style({opacity: trace.opacity});
  66703. traceSelection.selectAll('path.surface').each(function(pt) {
  66704. d3.select(this).call(styleOne, pt, trace);
  66705. });
  66706. });
  66707. };
  66708. },{"./style_one":365,"d3":16}],365:[function(_dereq_,module,exports){
  66709. /**
  66710. * Copyright 2012-2019, Plotly, Inc.
  66711. * All rights reserved.
  66712. *
  66713. * This source code is licensed under the MIT license found in the
  66714. * LICENSE file in the root directory of this source tree.
  66715. */
  66716. 'use strict';
  66717. var Color = _dereq_('../../components/color');
  66718. var castOption = _dereq_('./helpers').castOption;
  66719. module.exports = function styleOne(s, pt, trace) {
  66720. var line = trace.marker.line;
  66721. var lineColor = castOption(line.color, pt.pts) || Color.defaultLine;
  66722. var lineWidth = castOption(line.width, pt.pts) || 0;
  66723. s.style({'stroke-width': lineWidth})
  66724. .call(Color.fill, pt.color)
  66725. .call(Color.stroke, lineColor);
  66726. };
  66727. },{"../../components/color":51,"./helpers":359}],366:[function(_dereq_,module,exports){
  66728. /**
  66729. * Copyright 2012-2019, Plotly, Inc.
  66730. * All rights reserved.
  66731. *
  66732. * This source code is licensed under the MIT license found in the
  66733. * LICENSE file in the root directory of this source tree.
  66734. */
  66735. 'use strict';
  66736. var Lib = _dereq_('../../lib');
  66737. // arrayOk attributes, merge them into calcdata array
  66738. module.exports = function arraysToCalcdata(cd, trace) {
  66739. // so each point knows which index it originally came from
  66740. for(var i = 0; i < cd.length; i++) cd[i].i = i;
  66741. Lib.mergeArray(trace.text, cd, 'tx');
  66742. Lib.mergeArray(trace.hovertext, cd, 'htx');
  66743. Lib.mergeArray(trace.customdata, cd, 'data');
  66744. Lib.mergeArray(trace.textposition, cd, 'tp');
  66745. if(trace.textfont) {
  66746. Lib.mergeArray(trace.textfont.size, cd, 'ts');
  66747. Lib.mergeArray(trace.textfont.color, cd, 'tc');
  66748. Lib.mergeArray(trace.textfont.family, cd, 'tf');
  66749. }
  66750. var marker = trace.marker;
  66751. if(marker) {
  66752. Lib.mergeArray(marker.size, cd, 'ms');
  66753. Lib.mergeArray(marker.opacity, cd, 'mo');
  66754. Lib.mergeArray(marker.symbol, cd, 'mx');
  66755. Lib.mergeArray(marker.color, cd, 'mc');
  66756. var markerLine = marker.line;
  66757. if(marker.line) {
  66758. Lib.mergeArray(markerLine.color, cd, 'mlc');
  66759. Lib.mergeArray(markerLine.width, cd, 'mlw');
  66760. }
  66761. var markerGradient = marker.gradient;
  66762. if(markerGradient && markerGradient.type !== 'none') {
  66763. Lib.mergeArray(markerGradient.type, cd, 'mgt');
  66764. Lib.mergeArray(markerGradient.color, cd, 'mgc');
  66765. }
  66766. }
  66767. };
  66768. },{"../../lib":168}],367:[function(_dereq_,module,exports){
  66769. /**
  66770. * Copyright 2012-2019, Plotly, Inc.
  66771. * All rights reserved.
  66772. *
  66773. * This source code is licensed under the MIT license found in the
  66774. * LICENSE file in the root directory of this source tree.
  66775. */
  66776. 'use strict';
  66777. var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
  66778. var colorAttributes = _dereq_('../../components/colorscale/attributes');
  66779. var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
  66780. var fontAttrs = _dereq_('../../plots/font_attributes');
  66781. var dash = _dereq_('../../components/drawing/attributes').dash;
  66782. var Drawing = _dereq_('../../components/drawing');
  66783. var constants = _dereq_('./constants');
  66784. var extendFlat = _dereq_('../../lib/extend').extendFlat;
  66785. module.exports = {
  66786. x: {
  66787. valType: 'data_array',
  66788. editType: 'calc+clearAxisTypes',
  66789. anim: true,
  66790. },
  66791. x0: {
  66792. valType: 'any',
  66793. dflt: 0,
  66794. editType: 'calc+clearAxisTypes',
  66795. anim: true,
  66796. },
  66797. dx: {
  66798. valType: 'number',
  66799. dflt: 1,
  66800. editType: 'calc',
  66801. anim: true,
  66802. },
  66803. y: {
  66804. valType: 'data_array',
  66805. editType: 'calc+clearAxisTypes',
  66806. anim: true,
  66807. },
  66808. y0: {
  66809. valType: 'any',
  66810. dflt: 0,
  66811. editType: 'calc+clearAxisTypes',
  66812. anim: true,
  66813. },
  66814. dy: {
  66815. valType: 'number',
  66816. dflt: 1,
  66817. editType: 'calc',
  66818. anim: true,
  66819. },
  66820. stackgroup: {
  66821. valType: 'string',
  66822. dflt: '',
  66823. editType: 'calc',
  66824. },
  66825. orientation: {
  66826. valType: 'enumerated',
  66827. values: ['v', 'h'],
  66828. editType: 'calc',
  66829. },
  66830. groupnorm: {
  66831. valType: 'enumerated',
  66832. values: ['', 'fraction', 'percent'],
  66833. dflt: '',
  66834. editType: 'calc',
  66835. },
  66836. stackgaps: {
  66837. valType: 'enumerated',
  66838. values: ['infer zero', 'interpolate'],
  66839. dflt: 'infer zero',
  66840. editType: 'calc',
  66841. },
  66842. text: {
  66843. valType: 'string',
  66844. dflt: '',
  66845. arrayOk: true,
  66846. editType: 'calc',
  66847. },
  66848. hovertext: {
  66849. valType: 'string',
  66850. dflt: '',
  66851. arrayOk: true,
  66852. editType: 'style',
  66853. },
  66854. mode: {
  66855. valType: 'flaglist',
  66856. flags: ['lines', 'markers', 'text'],
  66857. extras: ['none'],
  66858. editType: 'calc',
  66859. },
  66860. hoveron: {
  66861. valType: 'flaglist',
  66862. flags: ['points', 'fills'],
  66863. editType: 'style',
  66864. },
  66865. hovertemplate: hovertemplateAttrs({}, {
  66866. keys: constants.eventDataKeys
  66867. }),
  66868. line: {
  66869. color: {
  66870. valType: 'color',
  66871. editType: 'style',
  66872. anim: true,
  66873. },
  66874. width: {
  66875. valType: 'number',
  66876. min: 0,
  66877. dflt: 2,
  66878. editType: 'style',
  66879. anim: true,
  66880. },
  66881. shape: {
  66882. valType: 'enumerated',
  66883. values: ['linear', 'spline', 'hv', 'vh', 'hvh', 'vhv'],
  66884. dflt: 'linear',
  66885. editType: 'plot',
  66886. },
  66887. smoothing: {
  66888. valType: 'number',
  66889. min: 0,
  66890. max: 1.3,
  66891. dflt: 1,
  66892. editType: 'plot',
  66893. },
  66894. dash: extendFlat({}, dash, {editType: 'style'}),
  66895. simplify: {
  66896. valType: 'boolean',
  66897. dflt: true,
  66898. editType: 'plot',
  66899. },
  66900. editType: 'plot'
  66901. },
  66902. connectgaps: {
  66903. valType: 'boolean',
  66904. dflt: false,
  66905. editType: 'calc',
  66906. },
  66907. cliponaxis: {
  66908. valType: 'boolean',
  66909. dflt: true,
  66910. editType: 'plot',
  66911. },
  66912. fill: {
  66913. valType: 'enumerated',
  66914. values: ['none', 'tozeroy', 'tozerox', 'tonexty', 'tonextx', 'toself', 'tonext'],
  66915. editType: 'calc',
  66916. },
  66917. fillcolor: {
  66918. valType: 'color',
  66919. editType: 'style',
  66920. anim: true,
  66921. },
  66922. marker: extendFlat({
  66923. symbol: {
  66924. valType: 'enumerated',
  66925. values: Drawing.symbolList,
  66926. dflt: 'circle',
  66927. arrayOk: true,
  66928. editType: 'style',
  66929. },
  66930. opacity: {
  66931. valType: 'number',
  66932. min: 0,
  66933. max: 1,
  66934. arrayOk: true,
  66935. editType: 'style',
  66936. anim: true,
  66937. },
  66938. size: {
  66939. valType: 'number',
  66940. min: 0,
  66941. dflt: 6,
  66942. arrayOk: true,
  66943. editType: 'calc',
  66944. anim: true,
  66945. },
  66946. maxdisplayed: {
  66947. valType: 'number',
  66948. min: 0,
  66949. dflt: 0,
  66950. editType: 'plot',
  66951. },
  66952. sizeref: {
  66953. valType: 'number',
  66954. dflt: 1,
  66955. editType: 'calc',
  66956. },
  66957. sizemin: {
  66958. valType: 'number',
  66959. min: 0,
  66960. dflt: 0,
  66961. editType: 'calc',
  66962. },
  66963. sizemode: {
  66964. valType: 'enumerated',
  66965. values: ['diameter', 'area'],
  66966. dflt: 'diameter',
  66967. editType: 'calc',
  66968. },
  66969. colorbar: colorbarAttrs,
  66970. line: extendFlat({
  66971. width: {
  66972. valType: 'number',
  66973. min: 0,
  66974. arrayOk: true,
  66975. editType: 'style',
  66976. anim: true,
  66977. },
  66978. editType: 'calc'
  66979. },
  66980. colorAttributes('marker.line', {anim: true})
  66981. ),
  66982. gradient: {
  66983. type: {
  66984. valType: 'enumerated',
  66985. values: ['radial', 'horizontal', 'vertical', 'none'],
  66986. arrayOk: true,
  66987. dflt: 'none',
  66988. editType: 'calc',
  66989. },
  66990. color: {
  66991. valType: 'color',
  66992. arrayOk: true,
  66993. editType: 'calc',
  66994. },
  66995. editType: 'calc'
  66996. },
  66997. editType: 'calc'
  66998. },
  66999. colorAttributes('marker', {anim: true})
  67000. ),
  67001. selected: {
  67002. marker: {
  67003. opacity: {
  67004. valType: 'number',
  67005. min: 0,
  67006. max: 1,
  67007. editType: 'style',
  67008. },
  67009. color: {
  67010. valType: 'color',
  67011. editType: 'style',
  67012. },
  67013. size: {
  67014. valType: 'number',
  67015. min: 0,
  67016. editType: 'style',
  67017. },
  67018. editType: 'style'
  67019. },
  67020. textfont: {
  67021. color: {
  67022. valType: 'color',
  67023. editType: 'style',
  67024. },
  67025. editType: 'style'
  67026. },
  67027. editType: 'style'
  67028. },
  67029. unselected: {
  67030. marker: {
  67031. opacity: {
  67032. valType: 'number',
  67033. min: 0,
  67034. max: 1,
  67035. editType: 'style',
  67036. },
  67037. color: {
  67038. valType: 'color',
  67039. editType: 'style',
  67040. },
  67041. size: {
  67042. valType: 'number',
  67043. min: 0,
  67044. editType: 'style',
  67045. },
  67046. editType: 'style'
  67047. },
  67048. textfont: {
  67049. color: {
  67050. valType: 'color',
  67051. editType: 'style',
  67052. },
  67053. editType: 'style'
  67054. },
  67055. editType: 'style'
  67056. },
  67057. textposition: {
  67058. valType: 'enumerated',
  67059. values: [
  67060. 'top left', 'top center', 'top right',
  67061. 'middle left', 'middle center', 'middle right',
  67062. 'bottom left', 'bottom center', 'bottom right'
  67063. ],
  67064. dflt: 'middle center',
  67065. arrayOk: true,
  67066. editType: 'calc',
  67067. },
  67068. textfont: fontAttrs({
  67069. editType: 'calc',
  67070. colorEditType: 'style',
  67071. arrayOk: true,
  67072. }),
  67073. r: {
  67074. valType: 'data_array',
  67075. editType: 'calc',
  67076. },
  67077. t: {
  67078. valType: 'data_array',
  67079. editType: 'calc',
  67080. }
  67081. };
  67082. },{"../../components/colorbar/attributes":52,"../../components/colorscale/attributes":58,"../../components/drawing":72,"../../components/drawing/attributes":71,"../../components/fx/hovertemplate_attributes":89,"../../lib/extend":162,"../../plots/font_attributes":239,"./constants":371}],368:[function(_dereq_,module,exports){
  67083. /**
  67084. * Copyright 2012-2019, Plotly, Inc.
  67085. * All rights reserved.
  67086. *
  67087. * This source code is licensed under the MIT license found in the
  67088. * LICENSE file in the root directory of this source tree.
  67089. */
  67090. 'use strict';
  67091. var isNumeric = _dereq_('fast-isnumeric');
  67092. var Lib = _dereq_('../../lib');
  67093. var Axes = _dereq_('../../plots/cartesian/axes');
  67094. var BADNUM = _dereq_('../../constants/numerical').BADNUM;
  67095. var subTypes = _dereq_('./subtypes');
  67096. var calcColorscale = _dereq_('./colorscale_calc');
  67097. var arraysToCalcdata = _dereq_('./arrays_to_calcdata');
  67098. var calcSelection = _dereq_('./calc_selection');
  67099. function calc(gd, trace) {
  67100. var fullLayout = gd._fullLayout;
  67101. var xa = Axes.getFromId(gd, trace.xaxis || 'x');
  67102. var ya = Axes.getFromId(gd, trace.yaxis || 'y');
  67103. var x = xa.makeCalcdata(trace, 'x');
  67104. var y = ya.makeCalcdata(trace, 'y');
  67105. var serieslen = trace._length;
  67106. var cd = new Array(serieslen);
  67107. var ids = trace.ids;
  67108. var stackGroupOpts = getStackOpts(trace, fullLayout, xa, ya);
  67109. var interpolateGaps = false;
  67110. var isV, i, j, k, interpolate, vali;
  67111. setFirstScatter(fullLayout, trace);
  67112. var xAttr = 'x';
  67113. var yAttr = 'y';
  67114. var posAttr;
  67115. if(stackGroupOpts) {
  67116. stackGroupOpts.traceIndices.push(trace.index);
  67117. isV = stackGroupOpts.orientation === 'v';
  67118. // size, like we use for bar
  67119. if(isV) {
  67120. yAttr = 's';
  67121. posAttr = 'x';
  67122. }
  67123. else {
  67124. xAttr = 's';
  67125. posAttr = 'y';
  67126. }
  67127. interpolate = stackGroupOpts.stackgaps === 'interpolate';
  67128. }
  67129. else {
  67130. var ppad = calcMarkerSize(trace, serieslen);
  67131. calcAxisExpansion(gd, trace, xa, ya, x, y, ppad);
  67132. }
  67133. for(i = 0; i < serieslen; i++) {
  67134. var cdi = cd[i] = {};
  67135. var xValid = isNumeric(x[i]);
  67136. var yValid = isNumeric(y[i]);
  67137. if(xValid && yValid) {
  67138. cdi[xAttr] = x[i];
  67139. cdi[yAttr] = y[i];
  67140. }
  67141. // if we're stacking we need to hold on to all valid positions
  67142. // even with invalid sizes
  67143. else if(stackGroupOpts && (isV ? xValid : yValid)) {
  67144. cdi[posAttr] = isV ? x[i] : y[i];
  67145. cdi.gap = true;
  67146. if(interpolate) {
  67147. cdi.s = BADNUM;
  67148. interpolateGaps = true;
  67149. }
  67150. else {
  67151. cdi.s = 0;
  67152. }
  67153. }
  67154. else {
  67155. cdi[xAttr] = cdi[yAttr] = BADNUM;
  67156. }
  67157. if(ids) {
  67158. cdi.id = String(ids[i]);
  67159. }
  67160. }
  67161. arraysToCalcdata(cd, trace);
  67162. calcColorscale(gd, trace);
  67163. calcSelection(cd, trace);
  67164. if(stackGroupOpts) {
  67165. // remove bad positions and sort
  67166. // note that original indices get added to cd in arraysToCalcdata
  67167. i = 0;
  67168. while(i < cd.length) {
  67169. if(cd[i][posAttr] === BADNUM) {
  67170. cd.splice(i, 1);
  67171. }
  67172. else i++;
  67173. }
  67174. Lib.sort(cd, function(a, b) {
  67175. return (a[posAttr] - b[posAttr]) || (a.i - b.i);
  67176. });
  67177. if(interpolateGaps) {
  67178. // first fill the beginning with constant from the first point
  67179. i = 0;
  67180. while(i < cd.length - 1 && cd[i].gap) {
  67181. i++;
  67182. }
  67183. vali = cd[i].s;
  67184. if(!vali) vali = cd[i].s = 0; // in case of no data AT ALL in this trace - use 0
  67185. for(j = 0; j < i; j++) {
  67186. cd[j].s = vali;
  67187. }
  67188. // then fill the end with constant from the last point
  67189. k = cd.length - 1;
  67190. while(k > i && cd[k].gap) {
  67191. k--;
  67192. }
  67193. vali = cd[k].s;
  67194. for(j = cd.length - 1; j > k; j--) {
  67195. cd[j].s = vali;
  67196. }
  67197. // now interpolate internal gaps linearly
  67198. while(i < k) {
  67199. i++;
  67200. if(cd[i].gap) {
  67201. j = i + 1;
  67202. while(cd[j].gap) {
  67203. j++;
  67204. }
  67205. var pos0 = cd[i - 1][posAttr];
  67206. var size0 = cd[i - 1].s;
  67207. var m = (cd[j].s - size0) / (cd[j][posAttr] - pos0);
  67208. while(i < j) {
  67209. cd[i].s = size0 + (cd[i][posAttr] - pos0) * m;
  67210. i++;
  67211. }
  67212. }
  67213. }
  67214. }
  67215. }
  67216. return cd;
  67217. }
  67218. function calcAxisExpansion(gd, trace, xa, ya, x, y, ppad) {
  67219. var serieslen = trace._length;
  67220. var fullLayout = gd._fullLayout;
  67221. var xId = xa._id;
  67222. var yId = ya._id;
  67223. var firstScatter = fullLayout._firstScatter[firstScatterGroup(trace)] === trace.uid;
  67224. var stackOrientation = (getStackOpts(trace, fullLayout, xa, ya) || {}).orientation;
  67225. var fill = trace.fill;
  67226. // cancel minimum tick spacings (only applies to bars and boxes)
  67227. xa._minDtick = 0;
  67228. ya._minDtick = 0;
  67229. // check whether bounds should be tight, padded, extended to zero...
  67230. // most cases both should be padded on both ends, so start with that.
  67231. var xOptions = {padded: true};
  67232. var yOptions = {padded: true};
  67233. if(ppad) {
  67234. xOptions.ppad = yOptions.ppad = ppad;
  67235. }
  67236. // TODO: text size
  67237. var openEnded = serieslen < 2 || (x[0] !== x[serieslen - 1]) || (y[0] !== y[serieslen - 1]);
  67238. // include zero (tight) and extremes (padded) if fill to zero
  67239. // (unless the shape is closed, then it's just filling the shape regardless)
  67240. if(openEnded && (
  67241. (fill === 'tozerox') ||
  67242. ((fill === 'tonextx') && (firstScatter || stackOrientation === 'h'))
  67243. )) {
  67244. xOptions.tozero = true;
  67245. }
  67246. // if no error bars, markers or text, or fill to y=0 remove x padding
  67247. else if(!(trace.error_y || {}).visible && (
  67248. (fill === 'tonexty' || fill === 'tozeroy') ||
  67249. (!subTypes.hasMarkers(trace) && !subTypes.hasText(trace))
  67250. )) {
  67251. xOptions.padded = false;
  67252. xOptions.ppad = 0;
  67253. }
  67254. // now check for y - rather different logic, though still mostly padded both ends
  67255. // include zero (tight) and extremes (padded) if fill to zero
  67256. // (unless the shape is closed, then it's just filling the shape regardless)
  67257. if(openEnded && (
  67258. (fill === 'tozeroy') ||
  67259. ((fill === 'tonexty') && (firstScatter || stackOrientation === 'v'))
  67260. )) {
  67261. yOptions.tozero = true;
  67262. }
  67263. // tight y: any x fill
  67264. else if(fill === 'tonextx' || fill === 'tozerox') {
  67265. yOptions.padded = false;
  67266. }
  67267. // N.B. asymmetric splom traces call this with blank {} xa or ya
  67268. if(xId) trace._extremes[xId] = Axes.findExtremes(xa, x, xOptions);
  67269. if(yId) trace._extremes[yId] = Axes.findExtremes(ya, y, yOptions);
  67270. }
  67271. function calcMarkerSize(trace, serieslen) {
  67272. if(!subTypes.hasMarkers(trace)) return;
  67273. // Treat size like x or y arrays --- Run d2c
  67274. // this needs to go before ppad computation
  67275. var marker = trace.marker;
  67276. var sizeref = 1.6 * (trace.marker.sizeref || 1);
  67277. var markerTrans;
  67278. if(trace.marker.sizemode === 'area') {
  67279. markerTrans = function(v) {
  67280. return Math.max(Math.sqrt((v || 0) / sizeref), 3);
  67281. };
  67282. } else {
  67283. markerTrans = function(v) {
  67284. return Math.max((v || 0) / sizeref, 3);
  67285. };
  67286. }
  67287. if(Lib.isArrayOrTypedArray(marker.size)) {
  67288. // I tried auto-type but category and dates dont make much sense.
  67289. var ax = {type: 'linear'};
  67290. Axes.setConvert(ax);
  67291. var s = ax.makeCalcdata(trace.marker, 'size');
  67292. var sizeOut = new Array(serieslen);
  67293. for(var i = 0; i < serieslen; i++) {
  67294. sizeOut[i] = markerTrans(s[i]);
  67295. }
  67296. return sizeOut;
  67297. } else {
  67298. return markerTrans(marker.size);
  67299. }
  67300. }
  67301. /**
  67302. * mark the first scatter trace for each subplot
  67303. * note that scatter and scattergl each get their own first trace
  67304. * note also that I'm doing this during calc rather than supplyDefaults
  67305. * so I don't need to worry about transforms, but if we ever do
  67306. * per-trace calc this will get confused.
  67307. */
  67308. function setFirstScatter(fullLayout, trace) {
  67309. var group = firstScatterGroup(trace);
  67310. var firstScatter = fullLayout._firstScatter;
  67311. if(!firstScatter[group]) firstScatter[group] = trace.uid;
  67312. }
  67313. function firstScatterGroup(trace) {
  67314. var stackGroup = trace.stackgroup;
  67315. return trace.xaxis + trace.yaxis + trace.type +
  67316. (stackGroup ? '-' + stackGroup : '');
  67317. }
  67318. function getStackOpts(trace, fullLayout, xa, ya) {
  67319. var stackGroup = trace.stackgroup;
  67320. if(!stackGroup) return;
  67321. var stackOpts = fullLayout._scatterStackOpts[xa._id + ya._id][stackGroup];
  67322. var stackAx = stackOpts.orientation === 'v' ? ya : xa;
  67323. // Allow stacking only on numeric axes
  67324. // calc is a little late to be figuring this out, but during supplyDefaults
  67325. // we don't know the axis type yet
  67326. if(stackAx.type === 'linear' || stackAx.type === 'log') return stackOpts;
  67327. }
  67328. module.exports = {
  67329. calc: calc,
  67330. calcMarkerSize: calcMarkerSize,
  67331. calcAxisExpansion: calcAxisExpansion,
  67332. setFirstScatter: setFirstScatter,
  67333. getStackOpts: getStackOpts
  67334. };
  67335. },{"../../constants/numerical":149,"../../lib":168,"../../plots/cartesian/axes":212,"./arrays_to_calcdata":366,"./calc_selection":369,"./colorscale_calc":370,"./subtypes":391,"fast-isnumeric":18}],369:[function(_dereq_,module,exports){
  67336. /**
  67337. * Copyright 2012-2019, Plotly, Inc.
  67338. * All rights reserved.
  67339. *
  67340. * This source code is licensed under the MIT license found in the
  67341. * LICENSE file in the root directory of this source tree.
  67342. */
  67343. 'use strict';
  67344. var Lib = _dereq_('../../lib');
  67345. module.exports = function calcSelection(cd, trace) {
  67346. if(Lib.isArrayOrTypedArray(trace.selectedpoints)) {
  67347. Lib.tagSelected(cd, trace);
  67348. }
  67349. };
  67350. },{"../../lib":168}],370:[function(_dereq_,module,exports){
  67351. /**
  67352. * Copyright 2012-2019, Plotly, Inc.
  67353. * All rights reserved.
  67354. *
  67355. * This source code is licensed under the MIT license found in the
  67356. * LICENSE file in the root directory of this source tree.
  67357. */
  67358. 'use strict';
  67359. var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
  67360. var calcColorscale = _dereq_('../../components/colorscale/calc');
  67361. var subTypes = _dereq_('./subtypes');
  67362. module.exports = function calcMarkerColorscale(gd, trace) {
  67363. if(subTypes.hasLines(trace) && hasColorscale(trace, 'line')) {
  67364. calcColorscale(gd, trace, {
  67365. vals: trace.line.color,
  67366. containerStr: 'line',
  67367. cLetter: 'c'
  67368. });
  67369. }
  67370. if(subTypes.hasMarkers(trace)) {
  67371. if(hasColorscale(trace, 'marker')) {
  67372. calcColorscale(gd, trace, {
  67373. vals: trace.marker.color,
  67374. containerStr: 'marker',
  67375. cLetter: 'c'
  67376. });
  67377. }
  67378. if(hasColorscale(trace, 'marker.line')) {
  67379. calcColorscale(gd, trace, {
  67380. vals: trace.marker.line.color,
  67381. containerStr: 'marker.line',
  67382. cLetter: 'c'
  67383. });
  67384. }
  67385. }
  67386. };
  67387. },{"../../components/colorscale/calc":59,"../../components/colorscale/helpers":62,"./subtypes":391}],371:[function(_dereq_,module,exports){
  67388. /**
  67389. * Copyright 2012-2019, Plotly, Inc.
  67390. * All rights reserved.
  67391. *
  67392. * This source code is licensed under the MIT license found in the
  67393. * LICENSE file in the root directory of this source tree.
  67394. */
  67395. 'use strict';
  67396. module.exports = {
  67397. PTS_LINESONLY: 20,
  67398. // fixed parameters of clustering and clipping algorithms
  67399. // fraction of clustering tolerance "so close we don't even consider it a new point"
  67400. minTolerance: 0.2,
  67401. // how fast does clustering tolerance increase as you get away from the visible region
  67402. toleranceGrowth: 10,
  67403. // number of viewport sizes away from the visible region
  67404. // at which we clip all lines to the perimeter
  67405. maxScreensAway: 20,
  67406. eventDataKeys: []
  67407. };
  67408. },{}],372:[function(_dereq_,module,exports){
  67409. /**
  67410. * Copyright 2012-2019, Plotly, Inc.
  67411. * All rights reserved.
  67412. *
  67413. * This source code is licensed under the MIT license found in the
  67414. * LICENSE file in the root directory of this source tree.
  67415. */
  67416. 'use strict';
  67417. var calc = _dereq_('./calc');
  67418. /*
  67419. * Scatter stacking & normalization calculations
  67420. * runs per subplot, and can handle multiple stacking groups
  67421. */
  67422. module.exports = function crossTraceCalc(gd, plotinfo) {
  67423. var xa = plotinfo.xaxis;
  67424. var ya = plotinfo.yaxis;
  67425. var subplot = xa._id + ya._id;
  67426. var subplotStackOpts = gd._fullLayout._scatterStackOpts[subplot];
  67427. if(!subplotStackOpts) return;
  67428. var calcTraces = gd.calcdata;
  67429. var i, j, k, i2, cd, cd0, posj, sumj, norm;
  67430. var groupOpts, interpolate, groupnorm, posAttr, valAttr;
  67431. var hasAnyBlanks;
  67432. for(var stackGroup in subplotStackOpts) {
  67433. groupOpts = subplotStackOpts[stackGroup];
  67434. var indices = groupOpts.traceIndices;
  67435. // can get here with no indices if the stack axis is non-numeric
  67436. if(!indices.length) continue;
  67437. interpolate = groupOpts.stackgaps === 'interpolate';
  67438. groupnorm = groupOpts.groupnorm;
  67439. if(groupOpts.orientation === 'v') {
  67440. posAttr = 'x';
  67441. valAttr = 'y';
  67442. }
  67443. else {
  67444. posAttr = 'y';
  67445. valAttr = 'x';
  67446. }
  67447. hasAnyBlanks = new Array(indices.length);
  67448. for(i = 0; i < hasAnyBlanks.length; i++) {
  67449. hasAnyBlanks[i] = false;
  67450. }
  67451. // Collect the complete set of all positions across ALL traces.
  67452. // Start with the first trace, then interleave items from later traces
  67453. // as needed.
  67454. // Fill in mising items as we go.
  67455. cd0 = calcTraces[indices[0]];
  67456. var allPositions = new Array(cd0.length);
  67457. for(i = 0; i < cd0.length; i++) {
  67458. allPositions[i] = cd0[i][posAttr];
  67459. }
  67460. for(i = 1; i < indices.length; i++) {
  67461. cd = calcTraces[indices[i]];
  67462. for(j = k = 0; j < cd.length; j++) {
  67463. posj = cd[j][posAttr];
  67464. for(; posj > allPositions[k] && k < allPositions.length; k++) {
  67465. // the current trace is missing a position from some previous trace(s)
  67466. insertBlank(cd, j, allPositions[k], i, hasAnyBlanks, interpolate, posAttr);
  67467. j++;
  67468. }
  67469. if(posj !== allPositions[k]) {
  67470. // previous trace(s) are missing a position from the current trace
  67471. for(i2 = 0; i2 < i; i2++) {
  67472. insertBlank(calcTraces[indices[i2]], k, posj, i2, hasAnyBlanks, interpolate, posAttr);
  67473. }
  67474. allPositions.splice(k, 0, posj);
  67475. }
  67476. k++;
  67477. }
  67478. for(; k < allPositions.length; k++) {
  67479. insertBlank(cd, j, allPositions[k], i, hasAnyBlanks, interpolate, posAttr);
  67480. j++;
  67481. }
  67482. }
  67483. var serieslen = allPositions.length;
  67484. // stack (and normalize)!
  67485. for(j = 0; j < cd0.length; j++) {
  67486. sumj = cd0[j][valAttr] = cd0[j].s;
  67487. for(i = 1; i < indices.length; i++) {
  67488. cd = calcTraces[indices[i]];
  67489. cd[0].trace._rawLength = cd[0].trace._length;
  67490. cd[0].trace._length = serieslen;
  67491. sumj += cd[j].s;
  67492. cd[j][valAttr] = sumj;
  67493. }
  67494. if(groupnorm) {
  67495. norm = ((groupnorm === 'fraction') ? sumj : (sumj / 100)) || 1;
  67496. for(i = 0; i < indices.length; i++) {
  67497. var cdj = calcTraces[indices[i]][j];
  67498. cdj[valAttr] /= norm;
  67499. cdj.sNorm = cdj.s / norm;
  67500. }
  67501. }
  67502. }
  67503. // autorange
  67504. for(i = 0; i < indices.length; i++) {
  67505. cd = calcTraces[indices[i]];
  67506. var trace = cd[0].trace;
  67507. var ppad = calc.calcMarkerSize(trace, trace._rawLength);
  67508. var arrayPad = Array.isArray(ppad);
  67509. if((ppad && hasAnyBlanks[i]) || arrayPad) {
  67510. var ppadRaw = ppad;
  67511. ppad = new Array(serieslen);
  67512. for(j = 0; j < serieslen; j++) {
  67513. ppad[j] = cd[j].gap ? 0 : (arrayPad ? ppadRaw[cd[j].i] : ppadRaw);
  67514. }
  67515. }
  67516. var x = new Array(serieslen);
  67517. var y = new Array(serieslen);
  67518. for(j = 0; j < serieslen; j++) {
  67519. x[j] = cd[j].x;
  67520. y[j] = cd[j].y;
  67521. }
  67522. calc.calcAxisExpansion(gd, trace, xa, ya, x, y, ppad);
  67523. // while we're here (in a loop over all traces in the stack)
  67524. // record the orientation, so hover can find it easily
  67525. cd[0].t.orientation = groupOpts.orientation;
  67526. }
  67527. }
  67528. };
  67529. function insertBlank(calcTrace, index, position, traceIndex, hasAnyBlanks, interpolate, posAttr) {
  67530. hasAnyBlanks[traceIndex] = true;
  67531. var newEntry = {
  67532. i: null,
  67533. gap: true,
  67534. s: 0
  67535. };
  67536. newEntry[posAttr] = position;
  67537. calcTrace.splice(index, 0, newEntry);
  67538. // Even if we're not interpolating, if one trace has multiple
  67539. // values at the same position and this trace only has one value there,
  67540. // we just duplicate that one value rather than insert a zero.
  67541. // We also make it look like a real point - because it's ambiguous which
  67542. // one really is the real one!
  67543. if(index && position === calcTrace[index - 1][posAttr]) {
  67544. var prevEntry = calcTrace[index - 1];
  67545. newEntry.s = prevEntry.s;
  67546. // TODO is it going to cause any problems to have multiple
  67547. // calcdata points with the same index?
  67548. newEntry.i = prevEntry.i;
  67549. newEntry.gap = prevEntry.gap;
  67550. }
  67551. else if(interpolate) {
  67552. newEntry.s = getInterp(calcTrace, index, position, posAttr);
  67553. }
  67554. if(!index) {
  67555. // t and trace need to stay on the first cd entry
  67556. calcTrace[0].t = calcTrace[1].t;
  67557. calcTrace[0].trace = calcTrace[1].trace;
  67558. delete calcTrace[1].t;
  67559. delete calcTrace[1].trace;
  67560. }
  67561. }
  67562. function getInterp(calcTrace, index, position, posAttr) {
  67563. var pt0 = calcTrace[index - 1];
  67564. var pt1 = calcTrace[index + 1];
  67565. if(!pt1) return pt0.s;
  67566. if(!pt0) return pt1.s;
  67567. return pt0.s + (pt1.s - pt0.s) * (position - pt0[posAttr]) / (pt1[posAttr] - pt0[posAttr]);
  67568. }
  67569. },{"./calc":368}],373:[function(_dereq_,module,exports){
  67570. /**
  67571. * Copyright 2012-2019, Plotly, Inc.
  67572. * All rights reserved.
  67573. *
  67574. * This source code is licensed under the MIT license found in the
  67575. * LICENSE file in the root directory of this source tree.
  67576. */
  67577. 'use strict';
  67578. // remove opacity for any trace that has a fill or is filled to
  67579. module.exports = function crossTraceDefaults(fullData) {
  67580. for(var i = 0; i < fullData.length; i++) {
  67581. var tracei = fullData[i];
  67582. if(tracei.type !== 'scatter') continue;
  67583. var filli = tracei.fill;
  67584. if(filli === 'none' || filli === 'toself') continue;
  67585. tracei.opacity = undefined;
  67586. if(filli === 'tonexty' || filli === 'tonextx') {
  67587. for(var j = i - 1; j >= 0; j--) {
  67588. var tracej = fullData[j];
  67589. if((tracej.type === 'scatter') &&
  67590. (tracej.xaxis === tracei.xaxis) &&
  67591. (tracej.yaxis === tracei.yaxis)) {
  67592. tracej.opacity = undefined;
  67593. break;
  67594. }
  67595. }
  67596. }
  67597. }
  67598. };
  67599. },{}],374:[function(_dereq_,module,exports){
  67600. /**
  67601. * Copyright 2012-2019, Plotly, Inc.
  67602. * All rights reserved.
  67603. *
  67604. * This source code is licensed under the MIT license found in the
  67605. * LICENSE file in the root directory of this source tree.
  67606. */
  67607. 'use strict';
  67608. var Lib = _dereq_('../../lib');
  67609. var Registry = _dereq_('../../registry');
  67610. var attributes = _dereq_('./attributes');
  67611. var constants = _dereq_('./constants');
  67612. var subTypes = _dereq_('./subtypes');
  67613. var handleXYDefaults = _dereq_('./xy_defaults');
  67614. var handleStackDefaults = _dereq_('./stack_defaults');
  67615. var handleMarkerDefaults = _dereq_('./marker_defaults');
  67616. var handleLineDefaults = _dereq_('./line_defaults');
  67617. var handleLineShapeDefaults = _dereq_('./line_shape_defaults');
  67618. var handleTextDefaults = _dereq_('./text_defaults');
  67619. var handleFillColorDefaults = _dereq_('./fillcolor_defaults');
  67620. module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
  67621. function coerce(attr, dflt) {
  67622. return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
  67623. }
  67624. var len = handleXYDefaults(traceIn, traceOut, layout, coerce);
  67625. if(!len) traceOut.visible = false;
  67626. if(!traceOut.visible) return;
  67627. var stackGroupOpts = handleStackDefaults(traceIn, traceOut, layout, coerce);
  67628. var defaultMode = !stackGroupOpts && (len < constants.PTS_LINESONLY) ?
  67629. 'lines+markers' : 'lines';
  67630. coerce('text');
  67631. coerce('hovertext');
  67632. coerce('mode', defaultMode);
  67633. if(subTypes.hasLines(traceOut)) {
  67634. handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
  67635. handleLineShapeDefaults(traceIn, traceOut, coerce);
  67636. coerce('connectgaps');
  67637. coerce('line.simplify');
  67638. }
  67639. if(subTypes.hasMarkers(traceOut)) {
  67640. handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true});
  67641. }
  67642. if(subTypes.hasText(traceOut)) {
  67643. handleTextDefaults(traceIn, traceOut, layout, coerce);
  67644. }
  67645. var dfltHoverOn = [];
  67646. if(subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
  67647. coerce('cliponaxis');
  67648. coerce('marker.maxdisplayed');
  67649. dfltHoverOn.push('points');
  67650. }
  67651. // It's possible for this default to be changed by a later trace.
  67652. // We handle that case in some hacky code inside handleStackDefaults.
  67653. coerce('fill', stackGroupOpts ? stackGroupOpts.fillDflt : 'none');
  67654. if(traceOut.fill !== 'none') {
  67655. handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
  67656. if(!subTypes.hasLines(traceOut)) handleLineShapeDefaults(traceIn, traceOut, coerce);
  67657. }
  67658. var lineColor = (traceOut.line || {}).color;
  67659. var markerColor = (traceOut.marker || {}).color;
  67660. if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') {
  67661. dfltHoverOn.push('fills');
  67662. }
  67663. coerce('hoveron', dfltHoverOn.join('+') || 'points');
  67664. if(traceOut.hoveron !== 'fills') coerce('hovertemplate');
  67665. var errorBarsSupplyDefaults = Registry.getComponentMethod('errorbars', 'supplyDefaults');
  67666. errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {axis: 'y'});
  67667. errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, {axis: 'x', inherit: 'y'});
  67668. Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
  67669. };
  67670. },{"../../lib":168,"../../registry":257,"./attributes":367,"./constants":371,"./fillcolor_defaults":376,"./line_defaults":380,"./line_shape_defaults":382,"./marker_defaults":386,"./stack_defaults":389,"./subtypes":391,"./text_defaults":392,"./xy_defaults":393}],375:[function(_dereq_,module,exports){
  67671. /**
  67672. * Copyright 2012-2019, Plotly, Inc.
  67673. * All rights reserved.
  67674. *
  67675. * This source code is licensed under the MIT license found in the
  67676. * LICENSE file in the root directory of this source tree.
  67677. */
  67678. 'use strict';
  67679. var Lib = _dereq_('../../lib');
  67680. /** Fill hover 'pointData' container with 'correct' hover text value
  67681. *
  67682. * - If trace hoverinfo contains a 'text' flag and hovertext is not set,
  67683. * the text elements will be seen in the hover labels.
  67684. *
  67685. * - If trace hoverinfo contains a 'text' flag and hovertext is set,
  67686. * hovertext takes precedence over text
  67687. * i.e. the hoverinfo elements will be seen in the hover labels
  67688. *
  67689. * @param {object} calcPt
  67690. * @param {object} trace
  67691. * @param {object || array} contOut (mutated here)
  67692. */
  67693. module.exports = function fillHoverText(calcPt, trace, contOut) {
  67694. var fill = Array.isArray(contOut) ?
  67695. function(v) { contOut.push(v); } :
  67696. function(v) { contOut.text = v; };
  67697. var htx = Lib.extractOption(calcPt, trace, 'htx', 'hovertext');
  67698. if(isValid(htx)) return fill(htx);
  67699. var tx = Lib.extractOption(calcPt, trace, 'tx', 'text');
  67700. if(isValid(tx)) return fill(tx);
  67701. };
  67702. // accept all truthy values and 0 (which gets cast to '0' in the hover labels)
  67703. function isValid(v) {
  67704. return v || v === 0;
  67705. }
  67706. },{"../../lib":168}],376:[function(_dereq_,module,exports){
  67707. /**
  67708. * Copyright 2012-2019, Plotly, Inc.
  67709. * All rights reserved.
  67710. *
  67711. * This source code is licensed under the MIT license found in the
  67712. * LICENSE file in the root directory of this source tree.
  67713. */
  67714. 'use strict';
  67715. var Color = _dereq_('../../components/color');
  67716. var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;
  67717. module.exports = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce) {
  67718. var inheritColorFromMarker = false;
  67719. if(traceOut.marker) {
  67720. // don't try to inherit a color array
  67721. var markerColor = traceOut.marker.color;
  67722. var markerLineColor = (traceOut.marker.line || {}).color;
  67723. if(markerColor && !isArrayOrTypedArray(markerColor)) {
  67724. inheritColorFromMarker = markerColor;
  67725. }
  67726. else if(markerLineColor && !isArrayOrTypedArray(markerLineColor)) {
  67727. inheritColorFromMarker = markerLineColor;
  67728. }
  67729. }
  67730. coerce('fillcolor', Color.addOpacity(
  67731. (traceOut.line || {}).color ||
  67732. inheritColorFromMarker ||
  67733. defaultColor, 0.5
  67734. ));
  67735. };
  67736. },{"../../components/color":51,"../../lib":168}],377:[function(_dereq_,module,exports){
  67737. /**
  67738. * Copyright 2012-2019, Plotly, Inc.
  67739. * All rights reserved.
  67740. *
  67741. * This source code is licensed under the MIT license found in the
  67742. * LICENSE file in the root directory of this source tree.
  67743. */
  67744. 'use strict';
  67745. var Color = _dereq_('../../components/color');
  67746. var subtypes = _dereq_('./subtypes');
  67747. module.exports = function getTraceColor(trace, di) {
  67748. var lc, tc;
  67749. // TODO: text modes
  67750. if(trace.mode === 'lines') {
  67751. lc = trace.line.color;
  67752. return (lc && Color.opacity(lc)) ?
  67753. lc : trace.fillcolor;
  67754. }
  67755. else if(trace.mode === 'none') {
  67756. return trace.fill ? trace.fillcolor : '';
  67757. }
  67758. else {
  67759. var mc = di.mcc || (trace.marker || {}).color;
  67760. var mlc = di.mlcc || ((trace.marker || {}).line || {}).color;
  67761. tc = (mc && Color.opacity(mc)) ? mc :
  67762. (mlc && Color.opacity(mlc) &&
  67763. (di.mlw || ((trace.marker || {}).line || {}).width)) ? mlc : '';
  67764. if(tc) {
  67765. // make sure the points aren't TOO transparent
  67766. if(Color.opacity(tc) < 0.3) {
  67767. return Color.addOpacity(tc, 0.3);
  67768. }
  67769. else return tc;
  67770. }
  67771. else {
  67772. lc = (trace.line || {}).color;
  67773. return (lc && Color.opacity(lc) &&
  67774. subtypes.hasLines(trace) && trace.line.width) ?
  67775. lc : trace.fillcolor;
  67776. }
  67777. }
  67778. };
  67779. },{"../../components/color":51,"./subtypes":391}],378:[function(_dereq_,module,exports){
  67780. /**
  67781. * Copyright 2012-2019, Plotly, Inc.
  67782. * All rights reserved.
  67783. *
  67784. * This source code is licensed under the MIT license found in the
  67785. * LICENSE file in the root directory of this source tree.
  67786. */
  67787. 'use strict';
  67788. var Lib = _dereq_('../../lib');
  67789. var Fx = _dereq_('../../components/fx');
  67790. var Registry = _dereq_('../../registry');
  67791. var getTraceColor = _dereq_('./get_trace_color');
  67792. var Color = _dereq_('../../components/color');
  67793. var fillHoverText = _dereq_('./fill_hover_text');
  67794. module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
  67795. var cd = pointData.cd;
  67796. var trace = cd[0].trace;
  67797. var xa = pointData.xa;
  67798. var ya = pointData.ya;
  67799. var xpx = xa.c2p(xval);
  67800. var ypx = ya.c2p(yval);
  67801. var pt = [xpx, ypx];
  67802. var hoveron = trace.hoveron || '';
  67803. var minRad = (trace.mode.indexOf('markers') !== -1) ? 3 : 0.5;
  67804. // look for points to hover on first, then take fills only if we
  67805. // didn't find a point
  67806. if(hoveron.indexOf('points') !== -1) {
  67807. var dx = function(di) {
  67808. // dx and dy are used in compare modes - here we want to always
  67809. // prioritize the closest data point, at least as long as markers are
  67810. // the same size or nonexistent, but still try to prioritize small markers too.
  67811. var rad = Math.max(3, di.mrc || 0);
  67812. var kink = 1 - 1 / rad;
  67813. var dxRaw = Math.abs(xa.c2p(di.x) - xpx);
  67814. var d = (dxRaw < rad) ? (kink * dxRaw / rad) : (dxRaw - rad + kink);
  67815. return d;
  67816. };
  67817. var dy = function(di) {
  67818. var rad = Math.max(3, di.mrc || 0);
  67819. var kink = 1 - 1 / rad;
  67820. var dyRaw = Math.abs(ya.c2p(di.y) - ypx);
  67821. return (dyRaw < rad) ? (kink * dyRaw / rad) : (dyRaw - rad + kink);
  67822. };
  67823. var dxy = function(di) {
  67824. // scatter points: d.mrc is the calculated marker radius
  67825. // adjust the distance so if you're inside the marker it
  67826. // always will show up regardless of point size, but
  67827. // prioritize smaller points
  67828. var rad = Math.max(minRad, di.mrc || 0);
  67829. var dx = xa.c2p(di.x) - xpx;
  67830. var dy = ya.c2p(di.y) - ypx;
  67831. return Math.max(Math.sqrt(dx * dx + dy * dy) - rad, 1 - minRad / rad);
  67832. };
  67833. var distfn = Fx.getDistanceFunction(hovermode, dx, dy, dxy);
  67834. Fx.getClosest(cd, distfn, pointData);
  67835. // skip the rest (for this trace) if we didn't find a close point
  67836. if(pointData.index !== false) {
  67837. // the closest data point
  67838. var di = cd[pointData.index];
  67839. var xc = xa.c2p(di.x, true);
  67840. var yc = ya.c2p(di.y, true);
  67841. var rad = di.mrc || 1;
  67842. // now we're done using the whole `calcdata` array, replace the
  67843. // index with the original index (in case of inserted point from
  67844. // stacked area)
  67845. pointData.index = di.i;
  67846. var orientation = cd[0].t.orientation;
  67847. // TODO: for scatter and bar, option to show (sub)totals and
  67848. // raw data? Currently stacked and/or normalized bars just show
  67849. // the normalized individual sizes, so that's what I'm doing here
  67850. // for now.
  67851. var sizeVal = orientation && (di.sNorm || di.s);
  67852. var xLabelVal = (orientation === 'h') ? sizeVal : di.x;
  67853. var yLabelVal = (orientation === 'v') ? sizeVal : di.y;
  67854. Lib.extendFlat(pointData, {
  67855. color: getTraceColor(trace, di),
  67856. x0: xc - rad,
  67857. x1: xc + rad,
  67858. xLabelVal: xLabelVal,
  67859. y0: yc - rad,
  67860. y1: yc + rad,
  67861. yLabelVal: yLabelVal,
  67862. spikeDistance: dxy(di),
  67863. hovertemplate: trace.hovertemplate
  67864. });
  67865. fillHoverText(di, trace, pointData);
  67866. Registry.getComponentMethod('errorbars', 'hoverInfo')(di, trace, pointData);
  67867. return [pointData];
  67868. }
  67869. }
  67870. // even if hoveron is 'fills', only use it if we have polygons too
  67871. if(hoveron.indexOf('fills') !== -1 && trace._polygons) {
  67872. var polygons = trace._polygons;
  67873. var polygonsIn = [];
  67874. var inside = false;
  67875. var xmin = Infinity;
  67876. var xmax = -Infinity;
  67877. var ymin = Infinity;
  67878. var ymax = -Infinity;
  67879. var i, j, polygon, pts, xCross, x0, x1, y0, y1;
  67880. for(i = 0; i < polygons.length; i++) {
  67881. polygon = polygons[i];
  67882. // TODO: this is not going to work right for curved edges, it will
  67883. // act as though they're straight. That's probably going to need
  67884. // the elements themselves to capture the events. Worth it?
  67885. if(polygon.contains(pt)) {
  67886. inside = !inside;
  67887. // TODO: need better than just the overall bounding box
  67888. polygonsIn.push(polygon);
  67889. ymin = Math.min(ymin, polygon.ymin);
  67890. ymax = Math.max(ymax, polygon.ymax);
  67891. }
  67892. }
  67893. if(inside) {
  67894. // constrain ymin/max to the visible plot, so the label goes
  67895. // at the middle of the piece you can see
  67896. ymin = Math.max(ymin, 0);
  67897. ymax = Math.min(ymax, ya._length);
  67898. // find the overall left-most and right-most points of the
  67899. // polygon(s) we're inside at their combined vertical midpoint.
  67900. // This is where we will draw the hover label.
  67901. // Note that this might not be the vertical midpoint of the
  67902. // whole trace, if it's disjoint.
  67903. var yAvg = (ymin + ymax) / 2;
  67904. for(i = 0; i < polygonsIn.length; i++) {
  67905. pts = polygonsIn[i].pts;
  67906. for(j = 1; j < pts.length; j++) {
  67907. y0 = pts[j - 1][1];
  67908. y1 = pts[j][1];
  67909. if((y0 > yAvg) !== (y1 >= yAvg)) {
  67910. x0 = pts[j - 1][0];
  67911. x1 = pts[j][0];
  67912. if(y1 - y0) {
  67913. xCross = x0 + (x1 - x0) * (yAvg - y0) / (y1 - y0);
  67914. xmin = Math.min(xmin, xCross);
  67915. xmax = Math.max(xmax, xCross);
  67916. }
  67917. }
  67918. }
  67919. }
  67920. // constrain xmin/max to the visible plot now too
  67921. xmin = Math.max(xmin, 0);
  67922. xmax = Math.min(xmax, xa._length);
  67923. // get only fill or line color for the hover color
  67924. var color = Color.defaultLine;
  67925. if(Color.opacity(trace.fillcolor)) color = trace.fillcolor;
  67926. else if(Color.opacity((trace.line || {}).color)) {
  67927. color = trace.line.color;
  67928. }
  67929. Lib.extendFlat(pointData, {
  67930. // never let a 2D override 1D type as closest point
  67931. // also: no spikeDistance, it's not allowed for fills
  67932. distance: pointData.maxHoverDistance,
  67933. x0: xmin,
  67934. x1: xmax,
  67935. y0: yAvg,
  67936. y1: yAvg,
  67937. color: color,
  67938. hovertemplate: '%{name}'
  67939. });
  67940. delete pointData.index;
  67941. if(trace.text && !Array.isArray(trace.text)) {
  67942. pointData.text = String(trace.text);
  67943. }
  67944. else pointData.text = trace.name;
  67945. return [pointData];
  67946. }
  67947. }
  67948. };
  67949. },{"../../components/color":51,"../../components/fx":90,"../../lib":168,"../../registry":257,"./fill_hover_text":375,"./get_trace_color":377}],379:[function(_dereq_,module,exports){
  67950. /**
  67951. * Copyright 2012-2019, Plotly, Inc.
  67952. * All rights reserved.
  67953. *
  67954. * This source code is licensed under the MIT license found in the
  67955. * LICENSE file in the root directory of this source tree.
  67956. */
  67957. 'use strict';
  67958. var Scatter = {};
  67959. var subtypes = _dereq_('./subtypes');
  67960. Scatter.hasLines = subtypes.hasLines;
  67961. Scatter.hasMarkers = subtypes.hasMarkers;
  67962. Scatter.hasText = subtypes.hasText;
  67963. Scatter.isBubble = subtypes.isBubble;
  67964. Scatter.attributes = _dereq_('./attributes');
  67965. Scatter.supplyDefaults = _dereq_('./defaults');
  67966. Scatter.crossTraceDefaults = _dereq_('./cross_trace_defaults');
  67967. Scatter.calc = _dereq_('./calc').calc;
  67968. Scatter.crossTraceCalc = _dereq_('./cross_trace_calc');
  67969. Scatter.arraysToCalcdata = _dereq_('./arrays_to_calcdata');
  67970. Scatter.plot = _dereq_('./plot');
  67971. Scatter.colorbar = _dereq_('./marker_colorbar');
  67972. Scatter.style = _dereq_('./style').style;
  67973. Scatter.styleOnSelect = _dereq_('./style').styleOnSelect;
  67974. Scatter.hoverPoints = _dereq_('./hover');
  67975. Scatter.selectPoints = _dereq_('./select');
  67976. Scatter.animatable = true;
  67977. Scatter.moduleType = 'trace';
  67978. Scatter.name = 'scatter';
  67979. Scatter.basePlotModule = _dereq_('../../plots/cartesian');
  67980. Scatter.categories = [
  67981. 'cartesian', 'svg', 'symbols', 'errorBarsOK', 'showLegend', 'scatter-like',
  67982. 'zoomScale'
  67983. ];
  67984. Scatter.meta = {
  67985. };
  67986. module.exports = Scatter;
  67987. },{"../../plots/cartesian":224,"./arrays_to_calcdata":366,"./attributes":367,"./calc":368,"./cross_trace_calc":372,"./cross_trace_defaults":373,"./defaults":374,"./hover":378,"./marker_colorbar":385,"./plot":387,"./select":388,"./style":390,"./subtypes":391}],380:[function(_dereq_,module,exports){
  67988. /**
  67989. * Copyright 2012-2019, Plotly, Inc.
  67990. * All rights reserved.
  67991. *
  67992. * This source code is licensed under the MIT license found in the
  67993. * LICENSE file in the root directory of this source tree.
  67994. */
  67995. 'use strict';
  67996. var isArrayOrTypedArray = _dereq_('../../lib').isArrayOrTypedArray;
  67997. var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
  67998. var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
  67999. module.exports = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) {
  68000. var markerColor = (traceIn.marker || {}).color;
  68001. coerce('line.color', defaultColor);
  68002. if(hasColorscale(traceIn, 'line')) {
  68003. colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: 'line.', cLetter: 'c'});
  68004. } else {
  68005. var lineColorDflt = (isArrayOrTypedArray(markerColor) ? false : markerColor) || defaultColor;
  68006. coerce('line.color', lineColorDflt);
  68007. }
  68008. coerce('line.width');
  68009. if(!(opts || {}).noDash) coerce('line.dash');
  68010. };
  68011. },{"../../components/colorscale/defaults":61,"../../components/colorscale/helpers":62,"../../lib":168}],381:[function(_dereq_,module,exports){
  68012. /**
  68013. * Copyright 2012-2019, Plotly, Inc.
  68014. * All rights reserved.
  68015. *
  68016. * This source code is licensed under the MIT license found in the
  68017. * LICENSE file in the root directory of this source tree.
  68018. */
  68019. 'use strict';
  68020. var numConstants = _dereq_('../../constants/numerical');
  68021. var BADNUM = numConstants.BADNUM;
  68022. var LOG_CLIP = numConstants.LOG_CLIP;
  68023. var LOG_CLIP_PLUS = LOG_CLIP + 0.5;
  68024. var LOG_CLIP_MINUS = LOG_CLIP - 0.5;
  68025. var Lib = _dereq_('../../lib');
  68026. var segmentsIntersect = Lib.segmentsIntersect;
  68027. var constrain = Lib.constrain;
  68028. var constants = _dereq_('./constants');
  68029. module.exports = function linePoints(d, opts) {
  68030. var xa = opts.xaxis;
  68031. var ya = opts.yaxis;
  68032. var xLog = xa.type === 'log';
  68033. var yLog = ya.type === 'log';
  68034. var xLen = xa._length;
  68035. var yLen = ya._length;
  68036. var connectGaps = opts.connectGaps;
  68037. var baseTolerance = opts.baseTolerance;
  68038. var shape = opts.shape;
  68039. var linear = shape === 'linear';
  68040. var segments = [];
  68041. var minTolerance = constants.minTolerance;
  68042. var pts = new Array(d.length);
  68043. var pti = 0;
  68044. var i;
  68045. // pt variables are pixel coordinates [x,y] of one point
  68046. // these four are the outputs of clustering on a line
  68047. var clusterStartPt, clusterEndPt, clusterHighPt, clusterLowPt;
  68048. // "this" is the next point we're considering adding to the cluster
  68049. var thisPt;
  68050. // did we encounter the high point first, then a low point, or vice versa?
  68051. var clusterHighFirst;
  68052. // the first two points in the cluster determine its unit vector
  68053. // so the second is always in the "High" direction
  68054. var clusterUnitVector;
  68055. // the pixel delta from clusterStartPt
  68056. var thisVector;
  68057. // val variables are (signed) pixel distances along the cluster vector
  68058. var clusterRefDist, clusterHighVal, clusterLowVal, thisVal;
  68059. // deviation variables are (signed) pixel distances normal to the cluster vector
  68060. var clusterMinDeviation, clusterMaxDeviation, thisDeviation;
  68061. // turn one calcdata point into pixel coordinates
  68062. function getPt(index) {
  68063. var di = d[index];
  68064. if(!di) return false;
  68065. var x = xa.c2p(di.x);
  68066. var y = ya.c2p(di.y);
  68067. // if non-positive log values, set them VERY far off-screen
  68068. // so the line looks essentially straight from the previous point.
  68069. if(x === BADNUM) {
  68070. if(xLog) x = xa.c2p(di.x, true);
  68071. if(x === BADNUM) return false;
  68072. // If BOTH were bad log values, make the line follow a constant
  68073. // exponent rather than a constant slope
  68074. if(yLog && y === BADNUM) {
  68075. x *= Math.abs(xa._m * yLen * (xa._m > 0 ? LOG_CLIP_PLUS : LOG_CLIP_MINUS) /
  68076. (ya._m * xLen * (ya._m > 0 ? LOG_CLIP_PLUS : LOG_CLIP_MINUS)));
  68077. }
  68078. x *= 1000;
  68079. }
  68080. if(y === BADNUM) {
  68081. if(yLog) y = ya.c2p(di.y, true);
  68082. if(y === BADNUM) return false;
  68083. y *= 1000;
  68084. }
  68085. return [x, y];
  68086. }
  68087. function crossesViewport(xFrac0, yFrac0, xFrac1, yFrac1) {
  68088. var dx = xFrac1 - xFrac0;
  68089. var dy = yFrac1 - yFrac0;
  68090. var dx0 = 0.5 - xFrac0;
  68091. var dy0 = 0.5 - yFrac0;
  68092. var norm2 = dx * dx + dy * dy;
  68093. var dot = dx * dx0 + dy * dy0;
  68094. if(dot > 0 && dot < norm2) {
  68095. var cross = dx0 * dy - dy0 * dx;
  68096. if(cross * cross < norm2) return true;
  68097. }
  68098. }
  68099. var latestXFrac, latestYFrac;
  68100. // if we're off-screen, increase tolerance over baseTolerance
  68101. function getTolerance(pt, nextPt) {
  68102. var xFrac = pt[0] / xLen;
  68103. var yFrac = pt[1] / yLen;
  68104. var offScreenFraction = Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1);
  68105. if(offScreenFraction && (latestXFrac !== undefined) &&
  68106. crossesViewport(xFrac, yFrac, latestXFrac, latestYFrac)
  68107. ) {
  68108. offScreenFraction = 0;
  68109. }
  68110. if(offScreenFraction && nextPt &&
  68111. crossesViewport(xFrac, yFrac, nextPt[0] / xLen, nextPt[1] / yLen)
  68112. ) {
  68113. offScreenFraction = 0;
  68114. }
  68115. return (1 + constants.toleranceGrowth * offScreenFraction) * baseTolerance;
  68116. }
  68117. function ptDist(pt1, pt2) {
  68118. var dx = pt1[0] - pt2[0];
  68119. var dy = pt1[1] - pt2[1];
  68120. return Math.sqrt(dx * dx + dy * dy);
  68121. }
  68122. // last bit of filtering: clip paths that are VERY far off-screen
  68123. // so we don't get near the browser's hard limit (+/- 2^29 px in Chrome and FF)
  68124. var maxScreensAway = constants.maxScreensAway;
  68125. // find the intersections between the segment from pt1 to pt2
  68126. // and the large rectangle maxScreensAway around the viewport
  68127. // if one of pt1 and pt2 is inside and the other outside, there
  68128. // will be only one intersection.
  68129. // if both are outside there will be 0 or 2 intersections
  68130. // (or 1 if it's right at a corner - we'll treat that like 0)
  68131. // returns an array of intersection pts
  68132. var xEdge0 = -xLen * maxScreensAway;
  68133. var xEdge1 = xLen * (1 + maxScreensAway);
  68134. var yEdge0 = -yLen * maxScreensAway;
  68135. var yEdge1 = yLen * (1 + maxScreensAway);
  68136. var edges = [
  68137. [xEdge0, yEdge0, xEdge1, yEdge0],
  68138. [xEdge1, yEdge0, xEdge1, yEdge1],
  68139. [xEdge1, yEdge1, xEdge0, yEdge1],
  68140. [xEdge0, yEdge1, xEdge0, yEdge0]
  68141. ];
  68142. var xEdge, yEdge, lastXEdge, lastYEdge, lastFarPt, edgePt;
  68143. // for linear line shape, edge intersections should be linearly interpolated
  68144. // spline uses this too, which isn't precisely correct but is actually pretty
  68145. // good, because Catmull-Rom weights far-away points less in creating the curvature
  68146. function getLinearEdgeIntersections(pt1, pt2) {
  68147. var out = [];
  68148. var ptCount = 0;
  68149. for(var i = 0; i < 4; i++) {
  68150. var edge = edges[i];
  68151. var ptInt = segmentsIntersect(pt1[0], pt1[1], pt2[0], pt2[1],
  68152. edge[0], edge[1], edge[2], edge[3]);
  68153. if(ptInt && (!ptCount ||
  68154. Math.abs(ptInt.x - out[0][0]) > 1 ||
  68155. Math.abs(ptInt.y - out[0][1]) > 1
  68156. )) {
  68157. ptInt = [ptInt.x, ptInt.y];
  68158. // if we have 2 intersections, make sure the closest one to pt1 comes first
  68159. if(ptCount && ptDist(ptInt, pt1) < ptDist(out[0], pt1)) out.unshift(ptInt);
  68160. else out.push(ptInt);
  68161. ptCount++;
  68162. }
  68163. }
  68164. return out;
  68165. }
  68166. function onlyConstrainedPoint(pt) {
  68167. if(pt[0] < xEdge0 || pt[0] > xEdge1 || pt[1] < yEdge0 || pt[1] > yEdge1) {
  68168. return [constrain(pt[0], xEdge0, xEdge1), constrain(pt[1], yEdge0, yEdge1)];
  68169. }
  68170. }
  68171. function sameEdge(pt1, pt2) {
  68172. if(pt1[0] === pt2[0] && (pt1[0] === xEdge0 || pt1[0] === xEdge1)) return true;
  68173. if(pt1[1] === pt2[1] && (pt1[1] === yEdge0 || pt1[1] === yEdge1)) return true;
  68174. }
  68175. // for line shapes hv and vh, movement in the two dimensions is decoupled,
  68176. // so all we need to do is constrain each dimension independently
  68177. function getHVEdgeIntersections(pt1, pt2) {
  68178. var out = [];
  68179. var ptInt1 = onlyConstrainedPoint(pt1);
  68180. var ptInt2 = onlyConstrainedPoint(pt2);
  68181. if(ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out;
  68182. if(ptInt1) out.push(ptInt1);
  68183. if(ptInt2) out.push(ptInt2);
  68184. return out;
  68185. }
  68186. // hvh and vhv we sometimes have to move one of the intersection points
  68187. // out BEYOND the clipping rect, by a maximum of a factor of 2, so that
  68188. // the midpoint line is drawn in the right place
  68189. function getABAEdgeIntersections(dim, limit0, limit1) {
  68190. return function(pt1, pt2) {
  68191. var ptInt1 = onlyConstrainedPoint(pt1);
  68192. var ptInt2 = onlyConstrainedPoint(pt2);
  68193. var out = [];
  68194. if(ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out;
  68195. if(ptInt1) out.push(ptInt1);
  68196. if(ptInt2) out.push(ptInt2);
  68197. var midShift = 2 * Lib.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) -
  68198. ((ptInt1 || pt1)[dim] + (ptInt2 || pt2)[dim]);
  68199. if(midShift) {
  68200. var ptToAlter;
  68201. if(ptInt1 && ptInt2) {
  68202. ptToAlter = (midShift > 0 === ptInt1[dim] > ptInt2[dim]) ? ptInt1 : ptInt2;
  68203. }
  68204. else ptToAlter = ptInt1 || ptInt2;
  68205. ptToAlter[dim] += midShift;
  68206. }
  68207. return out;
  68208. };
  68209. }
  68210. var getEdgeIntersections;
  68211. if(shape === 'linear' || shape === 'spline') {
  68212. getEdgeIntersections = getLinearEdgeIntersections;
  68213. }
  68214. else if(shape === 'hv' || shape === 'vh') {
  68215. getEdgeIntersections = getHVEdgeIntersections;
  68216. }
  68217. else if(shape === 'hvh') getEdgeIntersections = getABAEdgeIntersections(0, xEdge0, xEdge1);
  68218. else if(shape === 'vhv') getEdgeIntersections = getABAEdgeIntersections(1, yEdge0, yEdge1);
  68219. // a segment pt1->pt2 entirely outside the nearby region:
  68220. // find the corner it gets closest to touching
  68221. function getClosestCorner(pt1, pt2) {
  68222. var dx = pt2[0] - pt1[0];
  68223. var m = (pt2[1] - pt1[1]) / dx;
  68224. var b = (pt1[1] * pt2[0] - pt2[1] * pt1[0]) / dx;
  68225. if(b > 0) return [m > 0 ? xEdge0 : xEdge1, yEdge1];
  68226. else return [m > 0 ? xEdge1 : xEdge0, yEdge0];
  68227. }
  68228. function updateEdge(pt) {
  68229. var x = pt[0];
  68230. var y = pt[1];
  68231. var xSame = x === pts[pti - 1][0];
  68232. var ySame = y === pts[pti - 1][1];
  68233. // duplicate point?
  68234. if(xSame && ySame) return;
  68235. if(pti > 1) {
  68236. // backtracking along an edge?
  68237. var xSame2 = x === pts[pti - 2][0];
  68238. var ySame2 = y === pts[pti - 2][1];
  68239. if(xSame && (x === xEdge0 || x === xEdge1) && xSame2) {
  68240. if(ySame2) pti--; // backtracking exactly - drop prev pt and don't add
  68241. else pts[pti - 1] = pt; // not exact: replace the prev pt
  68242. }
  68243. else if(ySame && (y === yEdge0 || y === yEdge1) && ySame2) {
  68244. if(xSame2) pti--;
  68245. else pts[pti - 1] = pt;
  68246. }
  68247. else pts[pti++] = pt;
  68248. }
  68249. else pts[pti++] = pt;
  68250. }
  68251. function updateEdgesForReentry(pt) {
  68252. // if we're outside the nearby region and going back in,
  68253. // we may need to loop around a corner point
  68254. if(pts[pti - 1][0] !== pt[0] && pts[pti - 1][1] !== pt[1]) {
  68255. updateEdge([lastXEdge, lastYEdge]);
  68256. }
  68257. updateEdge(pt);
  68258. lastFarPt = null;
  68259. lastXEdge = lastYEdge = 0;
  68260. }
  68261. function addPt(pt) {
  68262. latestXFrac = pt[0] / xLen;
  68263. latestYFrac = pt[1] / yLen;
  68264. // Are we more than maxScreensAway off-screen any direction?
  68265. // if so, clip to this box, but in such a way that on-screen
  68266. // drawing is unchanged
  68267. xEdge = (pt[0] < xEdge0) ? xEdge0 : (pt[0] > xEdge1) ? xEdge1 : 0;
  68268. yEdge = (pt[1] < yEdge0) ? yEdge0 : (pt[1] > yEdge1) ? yEdge1 : 0;
  68269. if(xEdge || yEdge) {
  68270. // to get fills right - if first point is far, push it toward the
  68271. // screen in whichever direction(s) are far
  68272. if(!pti) {
  68273. pts[pti++] = [xEdge || pt[0], yEdge || pt[1]];
  68274. }
  68275. else if(lastFarPt) {
  68276. // both this point and the last are outside the nearby region
  68277. // check if we're crossing the nearby region
  68278. var intersections = getEdgeIntersections(lastFarPt, pt);
  68279. if(intersections.length > 1) {
  68280. updateEdgesForReentry(intersections[0]);
  68281. pts[pti++] = intersections[1];
  68282. }
  68283. }
  68284. // we're leaving the nearby region - add the point where we left it
  68285. else {
  68286. edgePt = getEdgeIntersections(pts[pti - 1], pt)[0];
  68287. pts[pti++] = edgePt;
  68288. }
  68289. var lastPt = pts[pti - 1];
  68290. if(xEdge && yEdge && (lastPt[0] !== xEdge || lastPt[1] !== yEdge)) {
  68291. // we've gone out beyond a new corner: add the corner too
  68292. // so that the next point will take the right winding
  68293. if(lastFarPt) {
  68294. if(lastXEdge !== xEdge && lastYEdge !== yEdge) {
  68295. if(lastXEdge && lastYEdge) {
  68296. // we've gone around to an opposite corner - we
  68297. // need to add the correct extra corner
  68298. // in order to get the right winding
  68299. updateEdge(getClosestCorner(lastFarPt, pt));
  68300. }
  68301. else {
  68302. // we're coming from a far edge - the extra corner
  68303. // we need is determined uniquely by the sectors
  68304. updateEdge([lastXEdge || xEdge, lastYEdge || yEdge]);
  68305. }
  68306. }
  68307. else if(lastXEdge && lastYEdge) {
  68308. updateEdge([lastXEdge, lastYEdge]);
  68309. }
  68310. }
  68311. updateEdge([xEdge, yEdge]);
  68312. }
  68313. else if((lastXEdge - xEdge) && (lastYEdge - yEdge)) {
  68314. // we're coming from an edge or far corner to an edge - again the
  68315. // extra corner we need is uniquely determined by the sectors
  68316. updateEdge([xEdge || lastXEdge, yEdge || lastYEdge]);
  68317. }
  68318. lastFarPt = pt;
  68319. lastXEdge = xEdge;
  68320. lastYEdge = yEdge;
  68321. }
  68322. else {
  68323. if(lastFarPt) {
  68324. // this point is in range but the previous wasn't: add its entry pt first
  68325. updateEdgesForReentry(getEdgeIntersections(lastFarPt, pt)[0]);
  68326. }
  68327. pts[pti++] = pt;
  68328. }
  68329. }
  68330. // loop over ALL points in this trace
  68331. for(i = 0; i < d.length; i++) {
  68332. clusterStartPt = getPt(i);
  68333. if(!clusterStartPt) continue;
  68334. pti = 0;
  68335. lastFarPt = null;
  68336. addPt(clusterStartPt);
  68337. // loop over one segment of the trace
  68338. for(i++; i < d.length; i++) {
  68339. clusterHighPt = getPt(i);
  68340. if(!clusterHighPt) {
  68341. if(connectGaps) continue;
  68342. else break;
  68343. }
  68344. // can't decimate if nonlinear line shape
  68345. // TODO: we *could* decimate [hv]{2,3} shapes if we restricted clusters to horz or vert again
  68346. // but spline would be verrry awkward to decimate
  68347. if(!linear || !opts.simplify) {
  68348. addPt(clusterHighPt);
  68349. continue;
  68350. }
  68351. var nextPt = getPt(i + 1);
  68352. clusterRefDist = ptDist(clusterHighPt, clusterStartPt);
  68353. if(clusterRefDist < getTolerance(clusterHighPt, nextPt) * minTolerance) continue;
  68354. clusterUnitVector = [
  68355. (clusterHighPt[0] - clusterStartPt[0]) / clusterRefDist,
  68356. (clusterHighPt[1] - clusterStartPt[1]) / clusterRefDist
  68357. ];
  68358. clusterLowPt = clusterStartPt;
  68359. clusterHighVal = clusterRefDist;
  68360. clusterLowVal = clusterMinDeviation = clusterMaxDeviation = 0;
  68361. clusterHighFirst = false;
  68362. clusterEndPt = clusterHighPt;
  68363. // loop over one cluster of points that collapse onto one line
  68364. for(i++; i < d.length; i++) {
  68365. thisPt = nextPt;
  68366. nextPt = getPt(i + 1);
  68367. if(!thisPt) {
  68368. if(connectGaps) continue;
  68369. else break;
  68370. }
  68371. thisVector = [
  68372. thisPt[0] - clusterStartPt[0],
  68373. thisPt[1] - clusterStartPt[1]
  68374. ];
  68375. // cross product (or dot with normal to the cluster vector)
  68376. thisDeviation = thisVector[0] * clusterUnitVector[1] - thisVector[1] * clusterUnitVector[0];
  68377. clusterMinDeviation = Math.min(clusterMinDeviation, thisDeviation);
  68378. clusterMaxDeviation = Math.max(clusterMaxDeviation, thisDeviation);
  68379. if(clusterMaxDeviation - clusterMinDeviation > getTolerance(thisPt, nextPt)) break;
  68380. clusterEndPt = thisPt;
  68381. thisVal = thisVector[0] * clusterUnitVector[0] + thisVector[1] * clusterUnitVector[1];
  68382. if(thisVal > clusterHighVal) {
  68383. clusterHighVal = thisVal;
  68384. clusterHighPt = thisPt;
  68385. clusterHighFirst = false;
  68386. } else if(thisVal < clusterLowVal) {
  68387. clusterLowVal = thisVal;
  68388. clusterLowPt = thisPt;
  68389. clusterHighFirst = true;
  68390. }
  68391. }
  68392. // insert this cluster into pts
  68393. // we've already inserted the start pt, now check if we have high and low pts
  68394. if(clusterHighFirst) {
  68395. addPt(clusterHighPt);
  68396. if(clusterEndPt !== clusterLowPt) addPt(clusterLowPt);
  68397. } else {
  68398. if(clusterLowPt !== clusterStartPt) addPt(clusterLowPt);
  68399. if(clusterEndPt !== clusterHighPt) addPt(clusterHighPt);
  68400. }
  68401. // and finally insert the end pt
  68402. addPt(clusterEndPt);
  68403. // have we reached the end of this segment?
  68404. if(i >= d.length || !thisPt) break;
  68405. // otherwise we have an out-of-cluster point to insert as next clusterStartPt
  68406. addPt(thisPt);
  68407. clusterStartPt = thisPt;
  68408. }
  68409. // to get fills right - repeat what we did at the start
  68410. if(lastFarPt) updateEdge([lastXEdge || lastFarPt[0], lastYEdge || lastFarPt[1]]);
  68411. segments.push(pts.slice(0, pti));
  68412. }
  68413. return segments;
  68414. };
  68415. },{"../../constants/numerical":149,"../../lib":168,"./constants":371}],382:[function(_dereq_,module,exports){
  68416. /**
  68417. * Copyright 2012-2019, Plotly, Inc.
  68418. * All rights reserved.
  68419. *
  68420. * This source code is licensed under the MIT license found in the
  68421. * LICENSE file in the root directory of this source tree.
  68422. */
  68423. 'use strict';
  68424. // common to 'scatter' and 'scatterternary'
  68425. module.exports = function handleLineShapeDefaults(traceIn, traceOut, coerce) {
  68426. var shape = coerce('line.shape');
  68427. if(shape === 'spline') coerce('line.smoothing');
  68428. };
  68429. },{}],383:[function(_dereq_,module,exports){
  68430. /**
  68431. * Copyright 2012-2019, Plotly, Inc.
  68432. * All rights reserved.
  68433. *
  68434. * This source code is licensed under the MIT license found in the
  68435. * LICENSE file in the root directory of this source tree.
  68436. */
  68437. 'use strict';
  68438. var LINKEDFILLS = {tonextx: 1, tonexty: 1, tonext: 1};
  68439. module.exports = function linkTraces(gd, plotinfo, cdscatter) {
  68440. var trace, i, group, prevtrace, groupIndex;
  68441. // first sort traces to keep stacks & filled-together groups together
  68442. var groupIndices = {};
  68443. var needsSort = false;
  68444. var prevGroupIndex = -1;
  68445. var nextGroupIndex = 0;
  68446. var prevUnstackedGroupIndex = -1;
  68447. for(i = 0; i < cdscatter.length; i++) {
  68448. trace = cdscatter[i][0].trace;
  68449. group = trace.stackgroup || '';
  68450. if(group) {
  68451. if(group in groupIndices) {
  68452. groupIndex = groupIndices[group];
  68453. }
  68454. else {
  68455. groupIndex = groupIndices[group] = nextGroupIndex;
  68456. nextGroupIndex++;
  68457. }
  68458. }
  68459. else if(trace.fill in LINKEDFILLS && prevUnstackedGroupIndex >= 0) {
  68460. groupIndex = prevUnstackedGroupIndex;
  68461. }
  68462. else {
  68463. groupIndex = prevUnstackedGroupIndex = nextGroupIndex;
  68464. nextGroupIndex++;
  68465. }
  68466. if(groupIndex < prevGroupIndex) needsSort = true;
  68467. trace._groupIndex = prevGroupIndex = groupIndex;
  68468. }
  68469. var cdscatterSorted = cdscatter.slice();
  68470. if(needsSort) {
  68471. cdscatterSorted.sort(function(a, b) {
  68472. var traceA = a[0].trace;
  68473. var traceB = b[0].trace;
  68474. return (traceA._groupIndex - traceB._groupIndex) ||
  68475. (traceA.index - traceB.index);
  68476. });
  68477. }
  68478. // now link traces to each other
  68479. var prevtraces = {};
  68480. for(i = 0; i < cdscatterSorted.length; i++) {
  68481. trace = cdscatterSorted[i][0].trace;
  68482. group = trace.stackgroup || '';
  68483. // Note: The check which ensures all cdscatter here are for the same axis and
  68484. // are either cartesian or scatterternary has been removed. This code assumes
  68485. // the passed scattertraces have been filtered to the proper plot types and
  68486. // the proper subplots.
  68487. if(trace.visible === true) {
  68488. trace._nexttrace = null;
  68489. if(trace.fill in LINKEDFILLS) {
  68490. prevtrace = prevtraces[group];
  68491. trace._prevtrace = prevtrace || null;
  68492. if(prevtrace) {
  68493. prevtrace._nexttrace = trace;
  68494. }
  68495. }
  68496. trace._ownfill = (trace.fill && (
  68497. trace.fill.substr(0, 6) === 'tozero' ||
  68498. trace.fill === 'toself' ||
  68499. (trace.fill.substr(0, 2) === 'to' && !trace._prevtrace)
  68500. ));
  68501. prevtraces[group] = trace;
  68502. } else {
  68503. trace._prevtrace = trace._nexttrace = trace._ownfill = null;
  68504. }
  68505. }
  68506. return cdscatterSorted;
  68507. };
  68508. },{}],384:[function(_dereq_,module,exports){
  68509. /**
  68510. * Copyright 2012-2019, Plotly, Inc.
  68511. * All rights reserved.
  68512. *
  68513. * This source code is licensed under the MIT license found in the
  68514. * LICENSE file in the root directory of this source tree.
  68515. */
  68516. 'use strict';
  68517. var isNumeric = _dereq_('fast-isnumeric');
  68518. // used in the drawing step for 'scatter' and 'scattegeo' and
  68519. // in the convert step for 'scatter3d'
  68520. module.exports = function makeBubbleSizeFn(trace) {
  68521. var marker = trace.marker;
  68522. var sizeRef = marker.sizeref || 1;
  68523. var sizeMin = marker.sizemin || 0;
  68524. // for bubble charts, allow scaling the provided value linearly
  68525. // and by area or diameter.
  68526. // Note this only applies to the array-value sizes
  68527. var baseFn = (marker.sizemode === 'area') ?
  68528. function(v) { return Math.sqrt(v / sizeRef); } :
  68529. function(v) { return v / sizeRef; };
  68530. // TODO add support for position/negative bubbles?
  68531. // TODO add 'sizeoffset' attribute?
  68532. return function(v) {
  68533. var baseSize = baseFn(v / 2);
  68534. // don't show non-numeric and negative sizes
  68535. return (isNumeric(baseSize) && (baseSize > 0)) ?
  68536. Math.max(baseSize, sizeMin) :
  68537. 0;
  68538. };
  68539. };
  68540. },{"fast-isnumeric":18}],385:[function(_dereq_,module,exports){
  68541. /**
  68542. * Copyright 2012-2019, Plotly, Inc.
  68543. * All rights reserved.
  68544. *
  68545. * This source code is licensed under the MIT license found in the
  68546. * LICENSE file in the root directory of this source tree.
  68547. */
  68548. 'use strict';
  68549. module.exports = {
  68550. container: 'marker',
  68551. min: 'cmin',
  68552. max: 'cmax'
  68553. };
  68554. },{}],386:[function(_dereq_,module,exports){
  68555. /**
  68556. * Copyright 2012-2019, Plotly, Inc.
  68557. * All rights reserved.
  68558. *
  68559. * This source code is licensed under the MIT license found in the
  68560. * LICENSE file in the root directory of this source tree.
  68561. */
  68562. 'use strict';
  68563. var Color = _dereq_('../../components/color');
  68564. var hasColorscale = _dereq_('../../components/colorscale/helpers').hasColorscale;
  68565. var colorscaleDefaults = _dereq_('../../components/colorscale/defaults');
  68566. var subTypes = _dereq_('./subtypes');
  68567. /*
  68568. * opts: object of flags to control features not all marker users support
  68569. * noLine: caller does not support marker lines
  68570. * gradient: caller supports gradients
  68571. * noSelect: caller does not support selected/unselected attribute containers
  68572. */
  68573. module.exports = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce, opts) {
  68574. var isBubble = subTypes.isBubble(traceIn);
  68575. var lineColor = (traceIn.line || {}).color;
  68576. var defaultMLC;
  68577. opts = opts || {};
  68578. // marker.color inherit from line.color (even if line.color is an array)
  68579. if(lineColor) defaultColor = lineColor;
  68580. coerce('marker.symbol');
  68581. coerce('marker.opacity', isBubble ? 0.7 : 1);
  68582. coerce('marker.size');
  68583. coerce('marker.color', defaultColor);
  68584. if(hasColorscale(traceIn, 'marker')) {
  68585. colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: 'marker.', cLetter: 'c'});
  68586. }
  68587. if(!opts.noSelect) {
  68588. coerce('selected.marker.color');
  68589. coerce('unselected.marker.color');
  68590. coerce('selected.marker.size');
  68591. coerce('unselected.marker.size');
  68592. }
  68593. if(!opts.noLine) {
  68594. // if there's a line with a different color than the marker, use
  68595. // that line color as the default marker line color
  68596. // (except when it's an array)
  68597. // mostly this is for transparent markers to behave nicely
  68598. if(lineColor && !Array.isArray(lineColor) && (traceOut.marker.color !== lineColor)) {
  68599. defaultMLC = lineColor;
  68600. }
  68601. else if(isBubble) defaultMLC = Color.background;
  68602. else defaultMLC = Color.defaultLine;
  68603. coerce('marker.line.color', defaultMLC);
  68604. if(hasColorscale(traceIn, 'marker.line')) {
  68605. colorscaleDefaults(traceIn, traceOut, layout, coerce, {prefix: 'marker.line.', cLetter: 'c'});
  68606. }
  68607. coerce('marker.line.width', isBubble ? 1 : 0);
  68608. }
  68609. if(isBubble) {
  68610. coerce('marker.sizeref');
  68611. coerce('marker.sizemin');
  68612. coerce('marker.sizemode');
  68613. }
  68614. if(opts.gradient) {
  68615. var gradientType = coerce('marker.gradient.type');
  68616. if(gradientType !== 'none') {
  68617. coerce('marker.gradient.color');
  68618. }
  68619. }
  68620. };
  68621. },{"../../components/color":51,"../../components/colorscale/defaults":61,"../../components/colorscale/helpers":62,"./subtypes":391}],387:[function(_dereq_,module,exports){
  68622. /**
  68623. * Copyright 2012-2019, Plotly, Inc.
  68624. * All rights reserved.
  68625. *
  68626. * This source code is licensed under the MIT license found in the
  68627. * LICENSE file in the root directory of this source tree.
  68628. */
  68629. 'use strict';
  68630. var d3 = _dereq_('d3');
  68631. var Registry = _dereq_('../../registry');
  68632. var Lib = _dereq_('../../lib');
  68633. var ensureSingle = Lib.ensureSingle;
  68634. var identity = Lib.identity;
  68635. var Drawing = _dereq_('../../components/drawing');
  68636. var subTypes = _dereq_('./subtypes');
  68637. var linePoints = _dereq_('./line_points');
  68638. var linkTraces = _dereq_('./link_traces');
  68639. var polygonTester = _dereq_('../../lib/polygon').tester;
  68640. module.exports = function plot(gd, plotinfo, cdscatter, scatterLayer, transitionOpts, makeOnCompleteCallback) {
  68641. var join, onComplete;
  68642. // If transition config is provided, then it is only a partial replot and traces not
  68643. // updated are removed.
  68644. var isFullReplot = !transitionOpts;
  68645. var hasTransition = !!transitionOpts && transitionOpts.duration > 0;
  68646. // Link traces so the z-order of fill layers is correct
  68647. var cdscatterSorted = linkTraces(gd, plotinfo, cdscatter);
  68648. join = scatterLayer.selectAll('g.trace')
  68649. .data(cdscatterSorted, function(d) { return d[0].trace.uid; });
  68650. // Append new traces:
  68651. join.enter().append('g')
  68652. .attr('class', function(d) {
  68653. return 'trace scatter trace' + d[0].trace.uid;
  68654. })
  68655. .style('stroke-miterlimit', 2);
  68656. join.order();
  68657. createFills(gd, join, plotinfo);
  68658. if(hasTransition) {
  68659. if(makeOnCompleteCallback) {
  68660. // If it was passed a callback to register completion, make a callback. If
  68661. // this is created, then it must be executed on completion, otherwise the
  68662. // pos-transition redraw will not execute:
  68663. onComplete = makeOnCompleteCallback();
  68664. }
  68665. var transition = d3.transition()
  68666. .duration(transitionOpts.duration)
  68667. .ease(transitionOpts.easing)
  68668. .each('end', function() {
  68669. onComplete && onComplete();
  68670. })
  68671. .each('interrupt', function() {
  68672. onComplete && onComplete();
  68673. });
  68674. transition.each(function() {
  68675. // Must run the selection again since otherwise enters/updates get grouped together
  68676. // and these get executed out of order. Except we need them in order!
  68677. scatterLayer.selectAll('g.trace').each(function(d, i) {
  68678. plotOne(gd, i, plotinfo, d, cdscatterSorted, this, transitionOpts);
  68679. });
  68680. });
  68681. } else {
  68682. join.each(function(d, i) {
  68683. plotOne(gd, i, plotinfo, d, cdscatterSorted, this, transitionOpts);
  68684. });
  68685. }
  68686. if(isFullReplot) {
  68687. join.exit().remove();
  68688. }
  68689. // remove paths that didn't get used
  68690. scatterLayer.selectAll('path:not([d])').remove();
  68691. };
  68692. function createFills(gd, traceJoin, plotinfo) {
  68693. traceJoin.each(function(d) {
  68694. var fills = ensureSingle(d3.select(this), 'g', 'fills');
  68695. Drawing.setClipUrl(fills, plotinfo.layerClipId, gd);
  68696. var trace = d[0].trace;
  68697. var fillData = [];
  68698. if(trace._ownfill) fillData.push('_ownFill');
  68699. if(trace._nexttrace) fillData.push('_nextFill');
  68700. var fillJoin = fills.selectAll('g').data(fillData, identity);
  68701. fillJoin.enter().append('g');
  68702. fillJoin.exit()
  68703. .each(function(d) { trace[d] = null; })
  68704. .remove();
  68705. fillJoin.order().each(function(d) {
  68706. // make a path element inside the fill group, just so
  68707. // we can give it its own data later on and the group can
  68708. // keep its simple '_*Fill' data
  68709. trace[d] = ensureSingle(d3.select(this), 'path', 'js-fill');
  68710. });
  68711. });
  68712. }
  68713. function plotOne(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) {
  68714. var i;
  68715. // Since this has been reorganized and we're executing this on individual traces,
  68716. // we need to pass it the full list of cdscatter as well as this trace's index (idx)
  68717. // since it does an internal n^2 loop over comparisons with other traces:
  68718. selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll);
  68719. var hasTransition = !!transitionOpts && transitionOpts.duration > 0;
  68720. function transition(selection) {
  68721. return hasTransition ? selection.transition() : selection;
  68722. }
  68723. var xa = plotinfo.xaxis;
  68724. var ya = plotinfo.yaxis;
  68725. var trace = cdscatter[0].trace;
  68726. var line = trace.line;
  68727. var tr = d3.select(element);
  68728. var errorBarGroup = ensureSingle(tr, 'g', 'errorbars');
  68729. var lines = ensureSingle(tr, 'g', 'lines');
  68730. var points = ensureSingle(tr, 'g', 'points');
  68731. var text = ensureSingle(tr, 'g', 'text');
  68732. // error bars are at the bottom
  68733. Registry.getComponentMethod('errorbars', 'plot')(gd, errorBarGroup, plotinfo, transitionOpts);
  68734. if(trace.visible !== true) return;
  68735. transition(tr).style('opacity', trace.opacity);
  68736. // BUILD LINES AND FILLS
  68737. var ownFillEl3, tonext;
  68738. var ownFillDir = trace.fill.charAt(trace.fill.length - 1);
  68739. if(ownFillDir !== 'x' && ownFillDir !== 'y') ownFillDir = '';
  68740. // store node for tweaking by selectPoints
  68741. if(!plotinfo.isRangePlot) cdscatter[0].node3 = tr;
  68742. var prevRevpath = '';
  68743. var prevPolygons = [];
  68744. var prevtrace = trace._prevtrace;
  68745. if(prevtrace) {
  68746. prevRevpath = prevtrace._prevRevpath || '';
  68747. tonext = prevtrace._nextFill;
  68748. prevPolygons = prevtrace._polygons;
  68749. }
  68750. var thispath;
  68751. var thisrevpath;
  68752. // fullpath is all paths for this curve, joined together straight
  68753. // across gaps, for filling
  68754. var fullpath = '';
  68755. // revpath is fullpath reversed, for fill-to-next
  68756. var revpath = '';
  68757. // functions for converting a point array to a path
  68758. var pathfn, revpathbase, revpathfn;
  68759. // variables used before and after the data join
  68760. var pt0, lastSegment, pt1, thisPolygons;
  68761. // initialize line join data / method
  68762. var segments = [];
  68763. var makeUpdate = Lib.noop;
  68764. ownFillEl3 = trace._ownFill;
  68765. if(subTypes.hasLines(trace) || trace.fill !== 'none') {
  68766. if(tonext) {
  68767. // This tells .style which trace to use for fill information:
  68768. tonext.datum(cdscatter);
  68769. }
  68770. if(['hv', 'vh', 'hvh', 'vhv'].indexOf(line.shape) !== -1) {
  68771. pathfn = Drawing.steps(line.shape);
  68772. revpathbase = Drawing.steps(
  68773. line.shape.split('').reverse().join('')
  68774. );
  68775. }
  68776. else if(line.shape === 'spline') {
  68777. pathfn = revpathbase = function(pts) {
  68778. var pLast = pts[pts.length - 1];
  68779. if(pts.length > 1 && pts[0][0] === pLast[0] && pts[0][1] === pLast[1]) {
  68780. // identical start and end points: treat it as a
  68781. // closed curve so we don't get a kink
  68782. return Drawing.smoothclosed(pts.slice(1), line.smoothing);
  68783. }
  68784. else {
  68785. return Drawing.smoothopen(pts, line.smoothing);
  68786. }
  68787. };
  68788. }
  68789. else {
  68790. pathfn = revpathbase = function(pts) {
  68791. return 'M' + pts.join('L');
  68792. };
  68793. }
  68794. revpathfn = function(pts) {
  68795. // note: this is destructive (reverses pts in place) so can't use pts after this
  68796. return revpathbase(pts.reverse());
  68797. };
  68798. segments = linePoints(cdscatter, {
  68799. xaxis: xa,
  68800. yaxis: ya,
  68801. connectGaps: trace.connectgaps,
  68802. baseTolerance: Math.max(line.width || 1, 3) / 4,
  68803. shape: line.shape,
  68804. simplify: line.simplify
  68805. });
  68806. // since we already have the pixel segments here, use them to make
  68807. // polygons for hover on fill
  68808. // TODO: can we skip this if hoveron!=fills? That would mean we
  68809. // need to redraw when you change hoveron...
  68810. thisPolygons = trace._polygons = new Array(segments.length);
  68811. for(i = 0; i < segments.length; i++) {
  68812. trace._polygons[i] = polygonTester(segments[i]);
  68813. }
  68814. if(segments.length) {
  68815. pt0 = segments[0][0];
  68816. lastSegment = segments[segments.length - 1];
  68817. pt1 = lastSegment[lastSegment.length - 1];
  68818. }
  68819. makeUpdate = function(isEnter) {
  68820. return function(pts) {
  68821. thispath = pathfn(pts);
  68822. thisrevpath = revpathfn(pts);
  68823. if(!fullpath) {
  68824. fullpath = thispath;
  68825. revpath = thisrevpath;
  68826. }
  68827. else if(ownFillDir) {
  68828. fullpath += 'L' + thispath.substr(1);
  68829. revpath = thisrevpath + ('L' + revpath.substr(1));
  68830. }
  68831. else {
  68832. fullpath += 'Z' + thispath;
  68833. revpath = thisrevpath + 'Z' + revpath;
  68834. }
  68835. if(subTypes.hasLines(trace) && pts.length > 1) {
  68836. var el = d3.select(this);
  68837. // This makes the coloring work correctly:
  68838. el.datum(cdscatter);
  68839. if(isEnter) {
  68840. transition(el.style('opacity', 0)
  68841. .attr('d', thispath)
  68842. .call(Drawing.lineGroupStyle))
  68843. .style('opacity', 1);
  68844. } else {
  68845. var sel = transition(el);
  68846. sel.attr('d', thispath);
  68847. Drawing.singleLineStyle(cdscatter, sel);
  68848. }
  68849. }
  68850. };
  68851. };
  68852. }
  68853. var lineJoin = lines.selectAll('.js-line').data(segments);
  68854. transition(lineJoin.exit())
  68855. .style('opacity', 0)
  68856. .remove();
  68857. lineJoin.each(makeUpdate(false));
  68858. lineJoin.enter().append('path')
  68859. .classed('js-line', true)
  68860. .style('vector-effect', 'non-scaling-stroke')
  68861. .call(Drawing.lineGroupStyle)
  68862. .each(makeUpdate(true));
  68863. Drawing.setClipUrl(lineJoin, plotinfo.layerClipId, gd);
  68864. function clearFill(selection) {
  68865. transition(selection).attr('d', 'M0,0Z');
  68866. }
  68867. if(segments.length) {
  68868. if(ownFillEl3) {
  68869. ownFillEl3.datum(cdscatter);
  68870. if(pt0 && pt1) {
  68871. if(ownFillDir) {
  68872. if(ownFillDir === 'y') {
  68873. pt0[1] = pt1[1] = ya.c2p(0, true);
  68874. }
  68875. else if(ownFillDir === 'x') {
  68876. pt0[0] = pt1[0] = xa.c2p(0, true);
  68877. }
  68878. // fill to zero: full trace path, plus extension of
  68879. // the endpoints to the appropriate axis
  68880. // For the sake of animations, wrap the points around so that
  68881. // the points on the axes are the first two points. Otherwise
  68882. // animations get a little crazy if the number of points changes.
  68883. transition(ownFillEl3).attr('d', 'M' + pt1 + 'L' + pt0 + 'L' + fullpath.substr(1))
  68884. .call(Drawing.singleFillStyle);
  68885. } else {
  68886. // fill to self: just join the path to itself
  68887. transition(ownFillEl3).attr('d', fullpath + 'Z')
  68888. .call(Drawing.singleFillStyle);
  68889. }
  68890. }
  68891. }
  68892. else if(tonext) {
  68893. if(trace.fill.substr(0, 6) === 'tonext' && fullpath && prevRevpath) {
  68894. // fill to next: full trace path, plus the previous path reversed
  68895. if(trace.fill === 'tonext') {
  68896. // tonext: for use by concentric shapes, like manually constructed
  68897. // contours, we just add the two paths closed on themselves.
  68898. // This makes strange results if one path is *not* entirely
  68899. // inside the other, but then that is a strange usage.
  68900. transition(tonext).attr('d', fullpath + 'Z' + prevRevpath + 'Z')
  68901. .call(Drawing.singleFillStyle);
  68902. }
  68903. else {
  68904. // tonextx/y: for now just connect endpoints with lines. This is
  68905. // the correct behavior if the endpoints are at the same value of
  68906. // y/x, but if they *aren't*, we should ideally do more complicated
  68907. // things depending on whether the new endpoint projects onto the
  68908. // existing curve or off the end of it
  68909. transition(tonext).attr('d', fullpath + 'L' + prevRevpath.substr(1) + 'Z')
  68910. .call(Drawing.singleFillStyle);
  68911. }
  68912. trace._polygons = trace._polygons.concat(prevPolygons);
  68913. }
  68914. else {
  68915. clearFill(tonext);
  68916. trace._polygons = null;
  68917. }
  68918. }
  68919. trace._prevRevpath = revpath;
  68920. trace._prevPolygons = thisPolygons;
  68921. }
  68922. else {
  68923. if(ownFillEl3) clearFill(ownFillEl3);
  68924. else if(tonext) clearFill(tonext);
  68925. trace._polygons = trace._prevRevpath = trace._prevPolygons = null;
  68926. }
  68927. function visFilter(d) {
  68928. return d.filter(function(v) { return !v.gap && v.vis; });
  68929. }
  68930. function visFilterWithGaps(d) {
  68931. return d.filter(function(v) { return v.vis; });
  68932. }
  68933. function gapFilter(d) {
  68934. return d.filter(function(v) { return !v.gap; });
  68935. }
  68936. function keyFunc(d) {
  68937. return d.id;
  68938. }
  68939. // Returns a function if the trace is keyed, otherwise returns undefined
  68940. function getKeyFunc(trace) {
  68941. if(trace.ids) {
  68942. return keyFunc;
  68943. }
  68944. }
  68945. function hideFilter() {
  68946. return false;
  68947. }
  68948. function makePoints(points, text, cdscatter) {
  68949. var join, selection, hasNode;
  68950. var trace = cdscatter[0].trace;
  68951. var showMarkers = subTypes.hasMarkers(trace);
  68952. var showText = subTypes.hasText(trace);
  68953. var keyFunc = getKeyFunc(trace);
  68954. var markerFilter = hideFilter;
  68955. var textFilter = hideFilter;
  68956. if(showMarkers || showText) {
  68957. var showFilter = identity;
  68958. // if we're stacking, "infer zero" gap mode gets markers in the
  68959. // gap points - because we've inferred a zero there - but other
  68960. // modes (currently "interpolate", later "interrupt" hopefully)
  68961. // we don't draw generated markers
  68962. var stackGroup = trace.stackgroup;
  68963. var isInferZero = stackGroup && (
  68964. gd._fullLayout._scatterStackOpts[xa._id + ya._id][stackGroup].stackgaps === 'infer zero');
  68965. if(trace.marker.maxdisplayed || trace._needsCull) {
  68966. showFilter = isInferZero ? visFilterWithGaps : visFilter;
  68967. }
  68968. else if(stackGroup && !isInferZero) {
  68969. showFilter = gapFilter;
  68970. }
  68971. if(showMarkers) markerFilter = showFilter;
  68972. if(showText) textFilter = showFilter;
  68973. }
  68974. // marker points
  68975. selection = points.selectAll('path.point');
  68976. join = selection.data(markerFilter, keyFunc);
  68977. var enter = join.enter().append('path')
  68978. .classed('point', true);
  68979. if(hasTransition) {
  68980. enter
  68981. .call(Drawing.pointStyle, trace, gd)
  68982. .call(Drawing.translatePoints, xa, ya)
  68983. .style('opacity', 0)
  68984. .transition()
  68985. .style('opacity', 1);
  68986. }
  68987. join.order();
  68988. var styleFns;
  68989. if(showMarkers) {
  68990. styleFns = Drawing.makePointStyleFns(trace);
  68991. }
  68992. join.each(function(d) {
  68993. var el = d3.select(this);
  68994. var sel = transition(el);
  68995. hasNode = Drawing.translatePoint(d, sel, xa, ya);
  68996. if(hasNode) {
  68997. Drawing.singlePointStyle(d, sel, trace, styleFns, gd);
  68998. if(plotinfo.layerClipId) {
  68999. Drawing.hideOutsideRangePoint(d, sel, xa, ya, trace.xcalendar, trace.ycalendar);
  69000. }
  69001. if(trace.customdata) {
  69002. el.classed('plotly-customdata', d.data !== null && d.data !== undefined);
  69003. }
  69004. } else {
  69005. sel.remove();
  69006. }
  69007. });
  69008. if(hasTransition) {
  69009. join.exit().transition()
  69010. .style('opacity', 0)
  69011. .remove();
  69012. } else {
  69013. join.exit().remove();
  69014. }
  69015. // text points
  69016. selection = text.selectAll('g');
  69017. join = selection.data(textFilter, keyFunc);
  69018. // each text needs to go in its own 'g' in case
  69019. // it gets converted to mathjax
  69020. join.enter().append('g').classed('textpoint', true).append('text');
  69021. join.order();
  69022. join.each(function(d) {
  69023. var g = d3.select(this);
  69024. var sel = transition(g.select('text'));
  69025. hasNode = Drawing.translatePoint(d, sel, xa, ya);
  69026. if(hasNode) {
  69027. if(plotinfo.layerClipId) {
  69028. Drawing.hideOutsideRangePoint(d, g, xa, ya, trace.xcalendar, trace.ycalendar);
  69029. }
  69030. } else {
  69031. g.remove();
  69032. }
  69033. });
  69034. join.selectAll('text')
  69035. .call(Drawing.textPointStyle, trace, gd)
  69036. .each(function(d) {
  69037. // This just *has* to be totally custom becuase of SVG text positioning :(
  69038. // It's obviously copied from translatePoint; we just can't use that
  69039. var x = xa.c2p(d.x);
  69040. var y = ya.c2p(d.y);
  69041. d3.select(this).selectAll('tspan.line').each(function() {
  69042. transition(d3.select(this)).attr({x: x, y: y});
  69043. });
  69044. });
  69045. join.exit().remove();
  69046. }
  69047. points.datum(cdscatter);
  69048. text.datum(cdscatter);
  69049. makePoints(points, text, cdscatter);
  69050. // lastly, clip points groups of `cliponaxis !== false` traces
  69051. // on `plotinfo._hasClipOnAxisFalse === true` subplots
  69052. var hasClipOnAxisFalse = trace.cliponaxis === false;
  69053. var clipUrl = hasClipOnAxisFalse ? null : plotinfo.layerClipId;
  69054. Drawing.setClipUrl(points, clipUrl, gd);
  69055. Drawing.setClipUrl(text, clipUrl, gd);
  69056. }
  69057. function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) {
  69058. var xa = plotinfo.xaxis;
  69059. var ya = plotinfo.yaxis;
  69060. var xr = d3.extent(Lib.simpleMap(xa.range, xa.r2c));
  69061. var yr = d3.extent(Lib.simpleMap(ya.range, ya.r2c));
  69062. var trace = cdscatter[0].trace;
  69063. if(!subTypes.hasMarkers(trace)) return;
  69064. // if marker.maxdisplayed is used, select a maximum of
  69065. // mnum markers to show, from the set that are in the viewport
  69066. var mnum = trace.marker.maxdisplayed;
  69067. // TODO: remove some as we get away from the viewport?
  69068. if(mnum === 0) return;
  69069. var cd = cdscatter.filter(function(v) {
  69070. return v.x >= xr[0] && v.x <= xr[1] && v.y >= yr[0] && v.y <= yr[1];
  69071. });
  69072. var inc = Math.ceil(cd.length / mnum);
  69073. var tnum = 0;
  69074. cdscatterAll.forEach(function(cdj, j) {
  69075. var tracei = cdj[0].trace;
  69076. if(subTypes.hasMarkers(tracei) &&
  69077. tracei.marker.maxdisplayed > 0 && j < idx) {
  69078. tnum++;
  69079. }
  69080. });
  69081. // if multiple traces use maxdisplayed, stagger which markers we
  69082. // display this formula offsets successive traces by 1/3 of the
  69083. // increment, adding an extra small amount after each triplet so
  69084. // it's not quite periodic
  69085. var i0 = Math.round(tnum * inc / 3 + Math.floor(tnum / 3) * inc / 7.1);
  69086. // for error bars: save in cd which markers to show
  69087. // so we don't have to repeat this
  69088. cdscatter.forEach(function(v) { delete v.vis; });
  69089. cd.forEach(function(v, i) {
  69090. if(Math.round((i + i0) % inc) === 0) v.vis = true;
  69091. });
  69092. }
  69093. },{"../../components/drawing":72,"../../lib":168,"../../lib/polygon":180,"../../registry":257,"./line_points":381,"./link_traces":383,"./subtypes":391,"d3":16}],388:[function(_dereq_,module,exports){
  69094. /**
  69095. * Copyright 2012-2019, Plotly, Inc.
  69096. * All rights reserved.
  69097. *
  69098. * This source code is licensed under the MIT license found in the
  69099. * LICENSE file in the root directory of this source tree.
  69100. */
  69101. 'use strict';
  69102. var subtypes = _dereq_('./subtypes');
  69103. module.exports = function selectPoints(searchInfo, selectionTester) {
  69104. var cd = searchInfo.cd;
  69105. var xa = searchInfo.xaxis;
  69106. var ya = searchInfo.yaxis;
  69107. var selection = [];
  69108. var trace = cd[0].trace;
  69109. var i;
  69110. var di;
  69111. var x;
  69112. var y;
  69113. var hasOnlyLines = (!subtypes.hasMarkers(trace) && !subtypes.hasText(trace));
  69114. if(hasOnlyLines) return [];
  69115. if(selectionTester === false) { // clear selection
  69116. for(i = 0; i < cd.length; i++) {
  69117. cd[i].selected = 0;
  69118. }
  69119. }
  69120. else {
  69121. for(i = 0; i < cd.length; i++) {
  69122. di = cd[i];
  69123. x = xa.c2p(di.x);
  69124. y = ya.c2p(di.y);
  69125. if((di.i !== null) && selectionTester.contains([x, y], false, i, searchInfo)) {
  69126. selection.push({
  69127. pointNumber: di.i,
  69128. x: xa.c2d(di.x),
  69129. y: ya.c2d(di.y)
  69130. });
  69131. di.selected = 1;
  69132. } else {
  69133. di.selected = 0;
  69134. }
  69135. }
  69136. }
  69137. return selection;
  69138. };
  69139. },{"./subtypes":391}],389:[function(_dereq_,module,exports){
  69140. /**
  69141. * Copyright 2012-2019, Plotly, Inc.
  69142. * All rights reserved.
  69143. *
  69144. * This source code is licensed under the MIT license found in the
  69145. * LICENSE file in the root directory of this source tree.
  69146. */
  69147. 'use strict';
  69148. var perStackAttrs = ['orientation', 'groupnorm', 'stackgaps'];
  69149. module.exports = function handleStackDefaults(traceIn, traceOut, layout, coerce) {
  69150. var stackOpts = layout._scatterStackOpts;
  69151. var stackGroup = coerce('stackgroup');
  69152. if(stackGroup) {
  69153. // use independent stacking options per subplot
  69154. var subplot = traceOut.xaxis + traceOut.yaxis;
  69155. var subplotStackOpts = stackOpts[subplot];
  69156. if(!subplotStackOpts) subplotStackOpts = stackOpts[subplot] = {};
  69157. var groupOpts = subplotStackOpts[stackGroup];
  69158. var firstTrace = false;
  69159. if(groupOpts) {
  69160. groupOpts.traces.push(traceOut);
  69161. }
  69162. else {
  69163. groupOpts = subplotStackOpts[stackGroup] = {
  69164. // keep track of trace indices for use during stacking calculations
  69165. // this will be filled in during `calc` and used during `crossTraceCalc`
  69166. // so it's OK if we don't recreate it during a non-calc edit
  69167. traceIndices: [],
  69168. // Hold on to the whole set of prior traces
  69169. // First one is most important, so we can clear defaults
  69170. // there if we find explicit values only in later traces.
  69171. // We're only going to *use* the values stored in groupOpts,
  69172. // but for the editor and validate we want things self-consistent
  69173. // The full set of traces is used only to fix `fill` default if
  69174. // we find `orientation: 'h'` beyond the first trace
  69175. traces: [traceOut]
  69176. };
  69177. firstTrace = true;
  69178. }
  69179. // TODO: how is this going to work with groupby transforms?
  69180. // in principle it should be OK I guess, as long as explicit group styles
  69181. // don't override explicit base-trace styles?
  69182. var dflts = {
  69183. orientation: (traceOut.x && !traceOut.y) ? 'h' : 'v'
  69184. };
  69185. for(var i = 0; i < perStackAttrs.length; i++) {
  69186. var attr = perStackAttrs[i];
  69187. var attrFound = attr + 'Found';
  69188. if(!groupOpts[attrFound]) {
  69189. var traceHasAttr = traceIn[attr] !== undefined;
  69190. var isOrientation = attr === 'orientation';
  69191. if(traceHasAttr || firstTrace) {
  69192. groupOpts[attr] = coerce(attr, dflts[attr]);
  69193. if(isOrientation) {
  69194. groupOpts.fillDflt = groupOpts[attr] === 'h' ?
  69195. 'tonextx' : 'tonexty';
  69196. }
  69197. if(traceHasAttr) {
  69198. // Note: this will show a value here even if it's invalid
  69199. // in which case it will revert to default.
  69200. groupOpts[attrFound] = true;
  69201. // Note: only one trace in the stack will get a _fullData
  69202. // entry for a given stack-wide attribute. If no traces
  69203. // (or the first trace) specify that attribute, the
  69204. // first trace will get it. If the first trace does NOT
  69205. // specify it but some later trace does, then it gets
  69206. // removed from the first trace and only included in the
  69207. // one that specified it. This is mostly important for
  69208. // editors (that want to see the full values to know
  69209. // what settings are available) and Plotly.react diffing.
  69210. // Editors may want to use fullLayout._scatterStackOpts
  69211. // directly and make these settings available from all
  69212. // traces in the stack... then set the new value into
  69213. // the first trace, and clear all later traces.
  69214. if(!firstTrace) {
  69215. delete groupOpts.traces[0][attr];
  69216. // orientation can affect default fill of previous traces
  69217. if(isOrientation) {
  69218. for(var j = 0; j < groupOpts.traces.length - 1; j++) {
  69219. var trace2 = groupOpts.traces[j];
  69220. if(trace2._input.fill !== trace2.fill) {
  69221. trace2.fill = groupOpts.fillDflt;
  69222. }
  69223. }
  69224. }
  69225. }
  69226. }
  69227. }
  69228. }
  69229. }
  69230. return groupOpts;
  69231. }
  69232. };
  69233. },{}],390:[function(_dereq_,module,exports){
  69234. /**
  69235. * Copyright 2012-2019, Plotly, Inc.
  69236. * All rights reserved.
  69237. *
  69238. * This source code is licensed under the MIT license found in the
  69239. * LICENSE file in the root directory of this source tree.
  69240. */
  69241. 'use strict';
  69242. var d3 = _dereq_('d3');
  69243. var Drawing = _dereq_('../../components/drawing');
  69244. var Registry = _dereq_('../../registry');
  69245. function style(gd, cd) {
  69246. var s = cd ? cd[0].node3 : d3.select(gd).selectAll('g.trace.scatter');
  69247. s.style('opacity', function(d) {
  69248. return d[0].trace.opacity;
  69249. });
  69250. s.selectAll('g.points').each(function(d) {
  69251. var sel = d3.select(this);
  69252. var trace = d.trace || d[0].trace;
  69253. stylePoints(sel, trace, gd);
  69254. });
  69255. s.selectAll('g.text').each(function(d) {
  69256. var sel = d3.select(this);
  69257. var trace = d.trace || d[0].trace;
  69258. styleText(sel, trace, gd);
  69259. });
  69260. s.selectAll('g.trace path.js-line')
  69261. .call(Drawing.lineGroupStyle);
  69262. s.selectAll('g.trace path.js-fill')
  69263. .call(Drawing.fillGroupStyle);
  69264. Registry.getComponentMethod('errorbars', 'style')(s);
  69265. }
  69266. function stylePoints(sel, trace, gd) {
  69267. Drawing.pointStyle(sel.selectAll('path.point'), trace, gd);
  69268. }
  69269. function styleText(sel, trace, gd) {
  69270. Drawing.textPointStyle(sel.selectAll('text'), trace, gd);
  69271. }
  69272. function styleOnSelect(gd, cd) {
  69273. var s = cd[0].node3;
  69274. var trace = cd[0].trace;
  69275. if(trace.selectedpoints) {
  69276. Drawing.selectedPointStyle(s.selectAll('path.point'), trace);
  69277. Drawing.selectedTextStyle(s.selectAll('text'), trace);
  69278. } else {
  69279. stylePoints(s, trace, gd);
  69280. styleText(s, trace, gd);
  69281. }
  69282. }
  69283. module.exports = {
  69284. style: style,
  69285. stylePoints: stylePoints,
  69286. styleText: styleText,
  69287. styleOnSelect: styleOnSelect
  69288. };
  69289. },{"../../components/drawing":72,"../../registry":257,"d3":16}],391:[function(_dereq_,module,exports){
  69290. /**
  69291. * Copyright 2012-2019, Plotly, Inc.
  69292. * All rights reserved.
  69293. *
  69294. * This source code is licensed under the MIT license found in the
  69295. * LICENSE file in the root directory of this source tree.
  69296. */
  69297. 'use strict';
  69298. var Lib = _dereq_('../../lib');
  69299. module.exports = {
  69300. hasLines: function(trace) {
  69301. return trace.visible && trace.mode &&
  69302. trace.mode.indexOf('lines') !== -1;
  69303. },
  69304. hasMarkers: function(trace) {
  69305. return trace.visible && (
  69306. (trace.mode && trace.mode.indexOf('markers') !== -1) ||
  69307. // until splom implements 'mode'
  69308. trace.type === 'splom'
  69309. );
  69310. },
  69311. hasText: function(trace) {
  69312. return trace.visible && trace.mode &&
  69313. trace.mode.indexOf('text') !== -1;
  69314. },
  69315. isBubble: function(trace) {
  69316. return Lib.isPlainObject(trace.marker) &&
  69317. Lib.isArrayOrTypedArray(trace.marker.size);
  69318. }
  69319. };
  69320. },{"../../lib":168}],392:[function(_dereq_,module,exports){
  69321. /**
  69322. * Copyright 2012-2019, Plotly, Inc.
  69323. * All rights reserved.
  69324. *
  69325. * This source code is licensed under the MIT license found in the
  69326. * LICENSE file in the root directory of this source tree.
  69327. */
  69328. 'use strict';
  69329. var Lib = _dereq_('../../lib');
  69330. /*
  69331. * opts: object of flags to control features not all text users support
  69332. * noSelect: caller does not support selected/unselected attribute containers
  69333. */
  69334. module.exports = function(traceIn, traceOut, layout, coerce, opts) {
  69335. opts = opts || {};
  69336. coerce('textposition');
  69337. Lib.coerceFont(coerce, 'textfont', layout.font);
  69338. if(!opts.noSelect) {
  69339. coerce('selected.textfont.color');
  69340. coerce('unselected.textfont.color');
  69341. }
  69342. };
  69343. },{"../../lib":168}],393:[function(_dereq_,module,exports){
  69344. /**
  69345. * Copyright 2012-2019, Plotly, Inc.
  69346. * All rights reserved.
  69347. *
  69348. * This source code is licensed under the MIT license found in the
  69349. * LICENSE file in the root directory of this source tree.
  69350. */
  69351. 'use strict';
  69352. var Lib = _dereq_('../../lib');
  69353. var Registry = _dereq_('../../registry');
  69354. module.exports = function handleXYDefaults(traceIn, traceOut, layout, coerce) {
  69355. var x = coerce('x');
  69356. var y = coerce('y');
  69357. var len;
  69358. var handleCalendarDefaults = Registry.getComponentMethod('calendars', 'handleTraceDefaults');
  69359. handleCalendarDefaults(traceIn, traceOut, ['x', 'y'], layout);
  69360. if(x) {
  69361. var xlen = Lib.minRowLength(x);
  69362. if(y) {
  69363. len = Math.min(xlen, Lib.minRowLength(y));
  69364. } else {
  69365. len = xlen;
  69366. coerce('y0');
  69367. coerce('dy');
  69368. }
  69369. } else {
  69370. if(!y) return 0;
  69371. len = Lib.minRowLength(y);
  69372. coerce('x0');
  69373. coerce('dx');
  69374. }
  69375. traceOut._length = len;
  69376. return len;
  69377. };
  69378. },{"../../lib":168,"../../registry":257}],394:[function(_dereq_,module,exports){
  69379. /**
  69380. * Copyright 2012-2019, Plotly, Inc.
  69381. * All rights reserved.
  69382. *
  69383. * This source code is licensed under the MIT license found in the
  69384. * LICENSE file in the root directory of this source tree.
  69385. */
  69386. 'use strict';
  69387. var hovertemplateAttrs = _dereq_('../../components/fx/hovertemplate_attributes');
  69388. var scatterAttrs = _dereq_('../scatter/attributes');
  69389. var plotAttrs = _dereq_('../../plots/attributes');
  69390. var colorAttributes = _dereq_('../../components/colorscale/attributes');
  69391. var colorbarAttrs = _dereq_('../../components/colorbar/attributes');
  69392. var dash = _dereq_('../../components/drawing/attributes').dash;
  69393. var extendFlat = _dereq_('../../lib/extend').extendFlat;
  69394. var scatterMarkerAttrs = scatterAttrs.marker;
  69395. var scatterLineAttrs = scatterAttrs.line;
  69396. var scatterMarkerLineAttrs = scatterMarkerAttrs.line;
  69397. module.exports = {
  69398. a: {
  69399. valType: 'data_array',
  69400. editType: 'calc',
  69401. },
  69402. b: {
  69403. valType: 'data_array',
  69404. editType: 'calc',
  69405. },
  69406. c: {
  69407. valType: 'data_array',
  69408. editType: 'calc',
  69409. },
  69410. sum: {
  69411. valType: 'number',
  69412. dflt: 0,
  69413. min: 0,
  69414. editType: 'calc',
  69415. },
  69416. mode: extendFlat({}, scatterAttrs.mode, {dflt: 'markers'}),
  69417. text: extendFlat({}, scatterAttrs.text, {
  69418. }),
  69419. hovertext: extendFlat({}, scatterAttrs.hovertext, {
  69420. }),
  69421. line: {
  69422. color: scatterLineAttrs.color,
  69423. width: scatterLineAttrs.width,
  69424. dash: dash,
  69425. shape: extendFlat({}, scatterLineAttrs.shape,
  69426. {values: ['linear', 'spline']}),
  69427. smoothing: scatterLineAttrs.smoothing,
  69428. editType: 'calc'
  69429. },
  69430. connectgaps: scatterAttrs.connectgaps,
  69431. cliponaxis: scatterAttrs.cliponaxis,
  69432. fill: extendFlat({}, scatterAttrs.fill, {
  69433. values: ['none', 'toself', 'tonext'],
  69434. dflt: 'none',
  69435. }),
  69436. fillcolor: scatterAttrs.fillcolor,
  69437. marker: extendFlat({
  69438. symbol: scatterMarkerAttrs.symbol,
  69439. opacity: scatterMarkerAttrs.opacity,
  69440. maxdisplayed: scatterMarkerAttrs.maxdisplayed,
  69441. size: scatterMarkerAttrs.size,
  69442. sizeref: scatterMarkerAttrs.sizeref,
  69443. sizemin: scatterMarkerAttrs.sizemin,
  69444. sizemode: scatterMarkerAttrs.sizemode,
  69445. line: extendFlat({
  69446. width: scatterMarkerLineAttrs.width,
  69447. editType: 'calc'
  69448. },
  69449. colorAttributes('marker.line')
  69450. ),
  69451. gradient: scatterMarkerAttrs.gradient,
  69452. editType: 'calc'
  69453. }, colorAttributes('marker'), {
  69454. colorbar: colorbarAttrs
  69455. }),
  69456. textfont: scatterAttrs.textfont,
  69457. textposition: scatterAttrs.textposition,
  69458. selected: scatterAttrs.selected,
  69459. unselected: scatterAttrs.unselected,
  69460. hoverinfo: extendFlat({}, plotAttrs.hoverinfo, {
  69461. flags: ['a', 'b', 'c', 'text', 'name']
  69462. }),
  69463. hoveron: scatterAttrs.hoveron,
  69464. hovertemplate: hovertemplateAttrs(),
  69465. };
  69466. },{"../../components/colorbar/attributes":52,"../../components/colorscale/attributes":58,"../../components/drawing/attributes":71,"../../components/fx/hovertemplate_attributes":89,"../../lib/extend":162,"../../plots/attributes":209,"../scatter/attributes":367}],395:[function(_dereq_,module,exports){
  69467. /**
  69468. * Copyright 2012-2019, Plotly, Inc.
  69469. * All rights reserved.
  69470. *
  69471. * This source code is licensed under the MIT license found in the
  69472. * LICENSE file in the root directory of this source tree.
  69473. */
  69474. 'use strict';
  69475. var isNumeric = _dereq_('fast-isnumeric');
  69476. var calcColorscale = _dereq_('../scatter/colorscale_calc');
  69477. var arraysToCalcdata = _dereq_('../scatter/arrays_to_calcdata');
  69478. var calcSelection = _dereq_('../scatter/calc_selection');
  69479. var calcMarkerSize = _dereq_('../scatter/calc').calcMarkerSize;
  69480. var dataArrays = ['a', 'b', 'c'];
  69481. var arraysToFill = {a: ['b', 'c'], b: ['a', 'c'], c: ['a', 'b']};
  69482. module.exports = function calc(gd, trace) {
  69483. var ternary = gd._fullLayout[trace.subplot];
  69484. var displaySum = ternary.sum;
  69485. var normSum = trace.sum || displaySum;
  69486. var arrays = {a: trace.a, b: trace.b, c: trace.c};
  69487. var i, j, dataArray, newArray, fillArray1, fillArray2;
  69488. // fill in one missing component
  69489. for(i = 0; i < dataArrays.length; i++) {
  69490. dataArray = dataArrays[i];
  69491. if(arrays[dataArray]) continue;
  69492. fillArray1 = arrays[arraysToFill[dataArray][0]];
  69493. fillArray2 = arrays[arraysToFill[dataArray][1]];
  69494. newArray = new Array(fillArray1.length);
  69495. for(j = 0; j < fillArray1.length; j++) {
  69496. newArray[j] = normSum - fillArray1[j] - fillArray2[j];
  69497. }
  69498. arrays[dataArray] = newArray;
  69499. }
  69500. // make the calcdata array
  69501. var serieslen = trace._length;
  69502. var cd = new Array(serieslen);
  69503. var a, b, c, norm, x, y;
  69504. for(i = 0; i < serieslen; i++) {
  69505. a = arrays.a[i];
  69506. b = arrays.b[i];
  69507. c = arrays.c[i];
  69508. if(isNumeric(a) && isNumeric(b) && isNumeric(c)) {
  69509. a = +a;
  69510. b = +b;
  69511. c = +c;
  69512. norm = displaySum / (a + b + c);
  69513. if(norm !== 1) {
  69514. a *= norm;
  69515. b *= norm;
  69516. c *= norm;
  69517. }
  69518. // map a, b, c onto x and y where the full scale of y
  69519. // is [0, sum], and x is [-sum, sum]
  69520. // TODO: this makes `a` always the top, `b` the bottom left,
  69521. // and `c` the bottom right. Do we want options to rearrange
  69522. // these?
  69523. y = a;
  69524. x = c - b;
  69525. cd[i] = {x: x, y: y, a: a, b: b, c: c};
  69526. }
  69527. else cd[i] = {x: false, y: false};
  69528. }
  69529. calcMarkerSize(trace, serieslen);
  69530. calcColorscale(gd, trace);
  69531. arraysToCalcdata(cd, trace);
  69532. calcSelection(cd, trace);
  69533. return cd;
  69534. };
  69535. },{"../scatter/arrays_to_calcdata":366,"../scatter/calc":368,"../scatter/calc_selection":369,"../scatter/colorscale_calc":370,"fast-isnumeric":18}],396:[function(_dereq_,module,exports){
  69536. /**
  69537. * Copyright 2012-2019, Plotly, Inc.
  69538. * All rights reserved.
  69539. *
  69540. * This source code is licensed under the MIT license found in the
  69541. * LICENSE file in the root directory of this source tree.
  69542. */
  69543. 'use strict';
  69544. var Lib = _dereq_('../../lib');
  69545. var constants = _dereq_('../scatter/constants');
  69546. var subTypes = _dereq_('../scatter/subtypes');
  69547. var handleMarkerDefaults = _dereq_('../scatter/marker_defaults');
  69548. var handleLineDefaults = _dereq_('../scatter/line_defaults');
  69549. var handleLineShapeDefaults = _dereq_('../scatter/line_shape_defaults');
  69550. var handleTextDefaults = _dereq_('../scatter/text_defaults');
  69551. var handleFillColorDefaults = _dereq_('../scatter/fillcolor_defaults');
  69552. var attributes = _dereq_('./attributes');
  69553. module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
  69554. function coerce(attr, dflt) {
  69555. return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
  69556. }
  69557. var a = coerce('a');
  69558. var b = coerce('b');
  69559. var c = coerce('c');
  69560. var len;
  69561. // allow any one array to be missing, len is the minimum length of those
  69562. // present. Note that after coerce data_array's are either Arrays (which
  69563. // are truthy even if empty) or undefined. As in scatter, an empty array
  69564. // is different from undefined, because it can signify that this data is
  69565. // not known yet but expected in the future
  69566. if(a) {
  69567. len = a.length;
  69568. if(b) {
  69569. len = Math.min(len, b.length);
  69570. if(c) len = Math.min(len, c.length);
  69571. }
  69572. else if(c) len = Math.min(len, c.length);
  69573. else len = 0;
  69574. }
  69575. else if(b && c) {
  69576. len = Math.min(b.length, c.length);
  69577. }
  69578. if(!len) {
  69579. traceOut.visible = false;
  69580. return;
  69581. }
  69582. traceOut._length = len;
  69583. coerce('sum');
  69584. coerce('text');
  69585. coerce('hovertext');
  69586. if(traceOut.hoveron !== 'fills') coerce('hovertemplate');
  69587. var defaultMode = len < constants.PTS_LINESONLY ? 'lines+markers' : 'lines';
  69588. coerce('mode', defaultMode);
  69589. if(subTypes.hasLines(traceOut)) {
  69590. handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce);
  69591. handleLineShapeDefaults(traceIn, traceOut, coerce);
  69592. coerce('connectgaps');
  69593. }
  69594. if(subTypes.hasMarkers(traceOut)) {
  69595. handleMarkerDefaults(traceIn, traceOut, defaultColor, layout, coerce, {gradient: true});
  69596. }
  69597. if(subTypes.hasText(traceOut)) {
  69598. handleTextDefaults(traceIn, traceOut, layout, coerce);
  69599. }
  69600. var dfltHoverOn = [];
  69601. if(subTypes.hasMarkers(traceOut) || subTypes.hasText(traceOut)) {
  69602. coerce('cliponaxis');
  69603. coerce('marker.maxdisplayed');
  69604. dfltHoverOn.push('points');
  69605. }
  69606. coerce('fill');
  69607. if(traceOut.fill !== 'none') {
  69608. handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce);
  69609. if(!subTypes.hasLines(traceOut)) handleLineShapeDefaults(traceIn, traceOut, coerce);
  69610. }
  69611. if(traceOut.fill === 'tonext' || traceOut.fill === 'toself') {
  69612. dfltHoverOn.push('fills');
  69613. }
  69614. coerce('hoveron', dfltHoverOn.join('+') || 'points');
  69615. Lib.coerceSelectionMarkerOpacity(traceOut, coerce);
  69616. };
  69617. },{"../../lib":168,"../scatter/constants":371,"../scatter/fillcolor_defaults":376,"../scatter/line_defaults":380,"../scatter/line_shape_defaults":382,"../scatter/marker_defaults":386,"../scatter/subtypes":391,"../scatter/text_defaults":392,"./attributes":394}],397:[function(_dereq_,module,exports){
  69618. /**
  69619. * Copyright 2012-2019, Plotly, Inc.
  69620. * All rights reserved.
  69621. *
  69622. * This source code is licensed under the MIT license found in the
  69623. * LICENSE file in the root directory of this source tree.
  69624. */
  69625. 'use strict';
  69626. module.exports = function eventData(out, pt, trace, cd, pointNumber) {
  69627. if(pt.xa) out.xaxis = pt.xa;
  69628. if(pt.ya) out.yaxis = pt.ya;
  69629. if(cd[pointNumber]) {
  69630. var cdi = cd[pointNumber];
  69631. // N.B. These are the normalized coordinates.
  69632. out.a = cdi.a;
  69633. out.b = cdi.b;
  69634. out.c = cdi.c;
  69635. } else {
  69636. // for fill-hover only
  69637. out.a = pt.a;
  69638. out.b = pt.b;
  69639. out.c = pt.c;
  69640. }
  69641. return out;
  69642. };
  69643. },{}],398:[function(_dereq_,module,exports){
  69644. /**
  69645. * Copyright 2012-2019, Plotly, Inc.
  69646. * All rights reserved.
  69647. *
  69648. * This source code is licensed under the MIT license found in the
  69649. * LICENSE file in the root directory of this source tree.
  69650. */
  69651. 'use strict';
  69652. var scatterHover = _dereq_('../scatter/hover');
  69653. var Axes = _dereq_('../../plots/cartesian/axes');
  69654. module.exports = function hoverPoints(pointData, xval, yval, hovermode) {
  69655. var scatterPointData = scatterHover(pointData, xval, yval, hovermode);
  69656. if(!scatterPointData || scatterPointData[0].index === false) return;
  69657. var newPointData = scatterPointData[0];
  69658. // if hovering on a fill, we don't show any point data so the label is
  69659. // unchanged from what scatter gives us - except that it needs to
  69660. // be constrained to the trianglular plot area, not just the rectangular
  69661. // area defined by the synthetic x and y axes
  69662. // TODO: in some cases the vertical middle of the shape is not within
  69663. // the triangular viewport at all, so the label can become disconnected
  69664. // from the shape entirely. But calculating what portion of the shape
  69665. // is actually visible, as constrained by the diagonal axis lines, is not
  69666. // so easy and anyway we lost the information we would have needed to do
  69667. // this inside scatterHover.
  69668. if(newPointData.index === undefined) {
  69669. var yFracUp = 1 - (newPointData.y0 / pointData.ya._length);
  69670. var xLen = pointData.xa._length;
  69671. var xMin = xLen * yFracUp / 2;
  69672. var xMax = xLen - xMin;
  69673. newPointData.x0 = Math.max(Math.min(newPointData.x0, xMax), xMin);
  69674. newPointData.x1 = Math.max(Math.min(newPointData.x1, xMax), xMin);
  69675. return scatterPointData;
  69676. }
  69677. var cdi = newPointData.cd[newPointData.index];
  69678. newPointData.a = cdi.a;
  69679. newPointData.b = cdi.b;
  69680. newPointData.c = cdi.c;
  69681. newPointData.xLabelVal = undefined;
  69682. newPointData.yLabelVal = undefined;
  69683. // TODO: nice formatting, and label by axis title, for a, b, and c?
  69684. var trace = newPointData.trace;
  69685. var ternary = newPointData.subplot;
  69686. var hoverinfo = cdi.hi || trace.hoverinfo;
  69687. var text = [];
  69688. function textPart(ax, val) {
  69689. text.push(ax._hovertitle + ': ' + Axes.tickText(ax, val, 'hover').text);
  69690. }
  69691. if(!trace.hovertemplate) {
  69692. var parts = hoverinfo.split('+');
  69693. if(parts.indexOf('all') !== -1) parts = ['a', 'b', 'c'];
  69694. if(parts.indexOf('a') !== -1) textPart(ternary.aaxis, cdi.a);
  69695. if(parts.indexOf('b') !== -1) textPart(ternary.baxis, cdi.b);
  69696. if(parts.indexOf('c') !== -1) textPart(ternary.caxis, cdi.c);
  69697. }
  69698. newPointData.extraText = text.join('<br>');
  69699. newPointData.hovertemplate = trace.hovertemplate;
  69700. return scatterPointData;
  69701. };
  69702. },{"../../plots/cartesian/axes":212,"../scatter/hover":378}],399:[function(_dereq_,module,exports){
  69703. /**
  69704. * Copyright 2012-2019, Plotly, Inc.
  69705. * All rights reserved.
  69706. *
  69707. * This source code is licensed under the MIT license found in the
  69708. * LICENSE file in the root directory of this source tree.
  69709. */
  69710. 'use strict';
  69711. var ScatterTernary = {};
  69712. ScatterTernary.attributes = _dereq_('./attributes');
  69713. ScatterTernary.supplyDefaults = _dereq_('./defaults');
  69714. ScatterTernary.colorbar = _dereq_('../scatter/marker_colorbar');
  69715. ScatterTernary.calc = _dereq_('./calc');
  69716. ScatterTernary.plot = _dereq_('./plot');
  69717. ScatterTernary.style = _dereq_('../scatter/style').style;
  69718. ScatterTernary.styleOnSelect = _dereq_('../scatter/style').styleOnSelect;
  69719. ScatterTernary.hoverPoints = _dereq_('./hover');
  69720. ScatterTernary.selectPoints = _dereq_('../scatter/select');
  69721. ScatterTernary.eventData = _dereq_('./event_data');
  69722. ScatterTernary.moduleType = 'trace';
  69723. ScatterTernary.name = 'scatterternary';
  69724. ScatterTernary.basePlotModule = _dereq_('../../plots/ternary');
  69725. ScatterTernary.categories = ['ternary', 'symbols', 'showLegend', 'scatter-like'];
  69726. ScatterTernary.meta = {
  69727. };
  69728. module.exports = ScatterTernary;
  69729. },{"../../plots/ternary":253,"../scatter/marker_colorbar":385,"../scatter/select":388,"../scatter/style":390,"./attributes":394,"./calc":395,"./defaults":396,"./event_data":397,"./hover":398,"./plot":400}],400:[function(_dereq_,module,exports){
  69730. /**
  69731. * Copyright 2012-2019, Plotly, Inc.
  69732. * All rights reserved.
  69733. *
  69734. * This source code is licensed under the MIT license found in the
  69735. * LICENSE file in the root directory of this source tree.
  69736. */
  69737. 'use strict';
  69738. var scatterPlot = _dereq_('../scatter/plot');
  69739. module.exports = function plot(gd, ternary, moduleCalcData) {
  69740. var plotContainer = ternary.plotContainer;
  69741. // remove all nodes inside the scatter layer
  69742. plotContainer.select('.scatterlayer').selectAll('*').remove();
  69743. // mimic cartesian plotinfo
  69744. var plotinfo = {
  69745. xaxis: ternary.xaxis,
  69746. yaxis: ternary.yaxis,
  69747. plot: plotContainer,
  69748. layerClipId: ternary._hasClipOnAxisFalse ? ternary.clipIdRelative : null
  69749. };
  69750. var scatterLayer = ternary.layers.frontplot.select('g.scatterlayer');
  69751. scatterPlot(gd, plotinfo, moduleCalcData, scatterLayer);
  69752. };
  69753. },{"../scatter/plot":387}],401:[function(_dereq_,module,exports){
  69754. /**
  69755. * Copyright 2012-2019, Plotly, Inc.
  69756. * All rights reserved.
  69757. *
  69758. * This source code is licensed under the MIT license found in the
  69759. * LICENSE file in the root directory of this source tree.
  69760. */
  69761. 'use strict';
  69762. var boxAttrs = _dereq_('../box/attributes');
  69763. var extendFlat = _dereq_('../../lib/extend').extendFlat;
  69764. module.exports = {
  69765. y: boxAttrs.y,
  69766. x: boxAttrs.x,
  69767. x0: boxAttrs.x0,
  69768. y0: boxAttrs.y0,
  69769. name: boxAttrs.name,
  69770. orientation: extendFlat({}, boxAttrs.orientation, {
  69771. }),
  69772. bandwidth: {
  69773. valType: 'number',
  69774. min: 0,
  69775. editType: 'calc',
  69776. },
  69777. scalegroup: {
  69778. valType: 'string',
  69779. dflt: '',
  69780. editType: 'calc',
  69781. },
  69782. scalemode: {
  69783. valType: 'enumerated',
  69784. values: ['width', 'count'],
  69785. dflt: 'width',
  69786. editType: 'calc',
  69787. },
  69788. spanmode: {
  69789. valType: 'enumerated',
  69790. values: ['soft', 'hard', 'manual'],
  69791. dflt: 'soft',
  69792. editType: 'calc',
  69793. },
  69794. span: {
  69795. valType: 'info_array',
  69796. items: [
  69797. {valType: 'any', editType: 'calc'},
  69798. {valType: 'any', editType: 'calc'}
  69799. ],
  69800. editType: 'calc',
  69801. },
  69802. line: {
  69803. color: {
  69804. valType: 'color',
  69805. editType: 'style',
  69806. },
  69807. width: {
  69808. valType: 'number',
  69809. min: 0,
  69810. dflt: 2,
  69811. editType: 'style',
  69812. },
  69813. editType: 'plot'
  69814. },
  69815. fillcolor: boxAttrs.fillcolor,
  69816. points: extendFlat({}, boxAttrs.boxpoints, {
  69817. }),
  69818. jitter: extendFlat({}, boxAttrs.jitter, {
  69819. }),
  69820. pointpos: extendFlat({}, boxAttrs.pointpos, {
  69821. }),
  69822. width: extendFlat({}, boxAttrs.width, {
  69823. }),
  69824. marker: boxAttrs.marker,
  69825. text: boxAttrs.text,
  69826. box: {
  69827. visible: {
  69828. valType: 'boolean',
  69829. dflt: false,
  69830. editType: 'plot',
  69831. },
  69832. width: {
  69833. valType: 'number',
  69834. min: 0,
  69835. max: 1,
  69836. dflt: 0.25,
  69837. editType: 'plot',
  69838. },
  69839. fillcolor: {
  69840. valType: 'color',
  69841. editType: 'style',
  69842. },
  69843. line: {
  69844. color: {
  69845. valType: 'color',
  69846. editType: 'style',
  69847. },
  69848. width: {
  69849. valType: 'number',
  69850. min: 0,
  69851. editType: 'style',
  69852. },
  69853. editType: 'style'
  69854. },
  69855. editType: 'plot'
  69856. },
  69857. meanline: {
  69858. visible: {
  69859. valType: 'boolean',
  69860. dflt: false,
  69861. editType: 'plot',
  69862. },
  69863. color: {
  69864. valType: 'color',
  69865. editType: 'style',
  69866. },
  69867. width: {
  69868. valType: 'number',
  69869. min: 0,
  69870. editType: 'style',
  69871. },
  69872. editType: 'plot'
  69873. },
  69874. side: {
  69875. valType: 'enumerated',
  69876. values: ['both', 'positive', 'negative'],
  69877. dflt: 'both',
  69878. editType: 'calc',
  69879. },
  69880. selected: boxAttrs.selected,
  69881. unselected: boxAttrs.unselected,
  69882. hoveron: {
  69883. valType: 'flaglist',
  69884. flags: ['violins', 'points', 'kde'],
  69885. dflt: 'violins+points+kde',
  69886. extras: ['all'],
  69887. editType: 'style',
  69888. }
  69889. };
  69890. },{"../../lib/extend":162,"../box/attributes":282}],402:[function(_dereq_,module,exports){
  69891. /**
  69892. * Copyright 2012-2019, Plotly, Inc.
  69893. * All rights reserved.
  69894. *
  69895. * This source code is licensed under the MIT license found in the
  69896. * LICENSE file in the root directory of this source tree.
  69897. */
  69898. 'use strict';
  69899. var Lib = _dereq_('../../lib');
  69900. var Axes = _dereq_('../../plots/cartesian/axes');
  69901. var boxCalc = _dereq_('../box/calc');
  69902. var helpers = _dereq_('./helpers');
  69903. var BADNUM = _dereq_('../../constants/numerical').BADNUM;
  69904. module.exports = function calc(gd, trace) {
  69905. var cd = boxCalc(gd, trace);
  69906. if(cd[0].t.empty) return cd;
  69907. var fullLayout = gd._fullLayout;
  69908. var valAxis = Axes.getFromId(
  69909. gd,
  69910. trace[trace.orientation === 'h' ? 'xaxis' : 'yaxis']
  69911. );
  69912. var spanMin = Infinity;
  69913. var spanMax = -Infinity;
  69914. var maxKDE = 0;
  69915. var maxCount = 0;
  69916. for(var i = 0; i < cd.length; i++) {
  69917. var cdi = cd[i];
  69918. var vals = cdi.pts.map(helpers.extractVal);
  69919. var bandwidth = cdi.bandwidth = calcBandwidth(trace, cdi, vals);
  69920. var span = cdi.span = calcSpan(trace, cdi, valAxis, bandwidth);
  69921. // step that well covers the bandwidth and is multiple of span distance
  69922. var dist = span[1] - span[0];
  69923. var n = Math.ceil(dist / (bandwidth / 3));
  69924. var step = dist / n;
  69925. if(!isFinite(step) || !isFinite(n)) {
  69926. Lib.error('Something went wrong with computing the violin span');
  69927. cd[0].t.empty = true;
  69928. return cd;
  69929. }
  69930. var kde = helpers.makeKDE(cdi, trace, vals);
  69931. cdi.density = new Array(n);
  69932. for(var k = 0, t = span[0]; t < (span[1] + step / 2); k++, t += step) {
  69933. var v = kde(t);
  69934. cdi.density[k] = {v: v, t: t};
  69935. maxKDE = Math.max(maxKDE, v);
  69936. }
  69937. maxCount = Math.max(maxCount, vals.length);
  69938. spanMin = Math.min(spanMin, span[0]);
  69939. spanMax = Math.max(spanMax, span[1]);
  69940. }
  69941. var extremes = Axes.findExtremes(valAxis, [spanMin, spanMax], {padded: true});
  69942. trace._extremes[valAxis._id] = extremes;
  69943. if(trace.width) {
  69944. cd[0].t.maxKDE = maxKDE;
  69945. } else {
  69946. var violinScaleGroupStats = fullLayout._violinScaleGroupStats;
  69947. var scaleGroup = trace.scalegroup;
  69948. var groupStats = violinScaleGroupStats[scaleGroup];
  69949. if(groupStats) {
  69950. groupStats.maxKDE = Math.max(groupStats.maxKDE, maxKDE);
  69951. groupStats.maxCount = Math.max(groupStats.maxCount, maxCount);
  69952. } else {
  69953. violinScaleGroupStats[scaleGroup] = {
  69954. maxKDE: maxKDE,
  69955. maxCount: maxCount
  69956. };
  69957. }
  69958. }
  69959. cd[0].t.labels.kde = Lib._(gd, 'kde:');
  69960. return cd;
  69961. };
  69962. // Default to Silveman's rule of thumb
  69963. // - https://stats.stackexchange.com/a/6671
  69964. // - https://en.wikipedia.org/wiki/Kernel_density_estimation#A_rule-of-thumb_bandwidth_estimator
  69965. // - https://github.com/statsmodels/statsmodels/blob/master/statsmodels/nonparametric/bandwidths.py
  69966. function silvermanRule(len, ssd, iqr) {
  69967. var a = Math.min(ssd, iqr / 1.349);
  69968. return 1.059 * a * Math.pow(len, -0.2);
  69969. }
  69970. function calcBandwidth(trace, cdi, vals) {
  69971. var span = cdi.max - cdi.min;
  69972. // plot single-value violin with bandwidth of 1
  69973. if(!span) return 1;
  69974. // Limit how small the bandwidth can be.
  69975. //
  69976. // Silverman's rule of thumb can be "very" small
  69977. // when IQR does a poor job at describing the spread
  69978. // of the distribution.
  69979. // We also want to limit custom bandwidths
  69980. // to not blow up kde computations.
  69981. if(trace.bandwidth) {
  69982. return Math.max(trace.bandwidth, span / 1e4);
  69983. } else {
  69984. var len = vals.length;
  69985. var ssd = Lib.stdev(vals, len - 1, cdi.mean);
  69986. return Math.max(
  69987. silvermanRule(len, ssd, cdi.q3 - cdi.q1),
  69988. span / 100
  69989. );
  69990. }
  69991. }
  69992. function calcSpan(trace, cdi, valAxis, bandwidth) {
  69993. var spanmode = trace.spanmode;
  69994. var spanIn = trace.span || [];
  69995. var spanTight = [cdi.min, cdi.max];
  69996. var spanLoose = [cdi.min - 2 * bandwidth, cdi.max + 2 * bandwidth];
  69997. var spanOut;
  69998. function calcSpanItem(index) {
  69999. var s = spanIn[index];
  70000. var sc = valAxis.type === 'multicategory' ?
  70001. valAxis.r2c(s) :
  70002. valAxis.d2c(s, 0, trace[cdi.valLetter + 'calendar']);
  70003. return sc === BADNUM ? spanLoose[index] : sc;
  70004. }
  70005. if(spanmode === 'soft') {
  70006. spanOut = spanLoose;
  70007. } else if(spanmode === 'hard') {
  70008. spanOut = spanTight;
  70009. } else {
  70010. spanOut = [calcSpanItem(0), calcSpanItem(1)];
  70011. }
  70012. // to reuse the equal-range-item block
  70013. var dummyAx = {
  70014. type: 'linear',
  70015. range: spanOut
  70016. };
  70017. Axes.setConvert(dummyAx);
  70018. dummyAx.cleanRange();
  70019. return spanOut;
  70020. }
  70021. },{"../../constants/numerical":149,"../../lib":168,"../../plots/cartesian/axes":212,"../box/calc":283,"./helpers":405}],403:[function(_dereq_,module,exports){
  70022. /**
  70023. * Copyright 2012-2019, Plotly, Inc.
  70024. * All rights reserved.
  70025. *
  70026. * This source code is licensed under the MIT license found in the
  70027. * LICENSE file in the root directory of this source tree.
  70028. */
  70029. 'use strict';
  70030. var setPositionOffset = _dereq_('../box/cross_trace_calc').setPositionOffset;
  70031. var orientations = ['v', 'h'];
  70032. module.exports = function crossTraceCalc(gd, plotinfo) {
  70033. var calcdata = gd.calcdata;
  70034. var xa = plotinfo.xaxis;
  70035. var ya = plotinfo.yaxis;
  70036. for(var i = 0; i < orientations.length; i++) {
  70037. var orientation = orientations[i];
  70038. var posAxis = orientation === 'h' ? ya : xa;
  70039. var violinList = [];
  70040. for(var j = 0; j < calcdata.length; j++) {
  70041. var cd = calcdata[j];
  70042. var t = cd[0].t;
  70043. var trace = cd[0].trace;
  70044. if(trace.visible === true && trace.type === 'violin' &&
  70045. !t.empty &&
  70046. trace.orientation === orientation &&
  70047. trace.xaxis === xa._id &&
  70048. trace.yaxis === ya._id
  70049. ) {
  70050. violinList.push(j);
  70051. }
  70052. }
  70053. setPositionOffset('violin', gd, violinList, posAxis);
  70054. }
  70055. };
  70056. },{"../box/cross_trace_calc":284}],404:[function(_dereq_,module,exports){
  70057. /**
  70058. * Copyright 2012-2019, Plotly, Inc.
  70059. * All rights reserved.
  70060. *
  70061. * This source code is licensed under the MIT license found in the
  70062. * LICENSE file in the root directory of this source tree.
  70063. */
  70064. 'use strict';
  70065. var Lib = _dereq_('../../lib');
  70066. var Color = _dereq_('../../components/color');
  70067. var boxDefaults = _dereq_('../box/defaults');
  70068. var attributes = _dereq_('./attributes');
  70069. module.exports = function supplyDefaults(traceIn, traceOut, defaultColor, layout) {
  70070. function coerce(attr, dflt) {
  70071. return Lib.coerce(traceIn, traceOut, attributes, attr, dflt);
  70072. }
  70073. function coerce2(attr, dflt) {
  70074. return Lib.coerce2(traceIn, traceOut, attributes, attr, dflt);
  70075. }
  70076. boxDefaults.handleSampleDefaults(traceIn, traceOut, coerce, layout);
  70077. if(traceOut.visible === false) return;
  70078. coerce('bandwidth');
  70079. coerce('side');
  70080. var width = coerce('width');
  70081. if(!width) {
  70082. coerce('scalegroup', traceOut.name);
  70083. coerce('scalemode');
  70084. }
  70085. var span = coerce('span');
  70086. var spanmodeDflt;
  70087. if(Array.isArray(span)) spanmodeDflt = 'manual';
  70088. coerce('spanmode', spanmodeDflt);
  70089. var lineColor = coerce('line.color', (traceIn.marker || {}).color || defaultColor);
  70090. var lineWidth = coerce('line.width');
  70091. var fillColor = coerce('fillcolor', Color.addOpacity(traceOut.line.color, 0.5));
  70092. boxDefaults.handlePointsDefaults(traceIn, traceOut, coerce, {prefix: ''});
  70093. var boxWidth = coerce2('box.width');
  70094. var boxFillColor = coerce2('box.fillcolor', fillColor);
  70095. var boxLineColor = coerce2('box.line.color', lineColor);
  70096. var boxLineWidth = coerce2('box.line.width', lineWidth);
  70097. var boxVisible = coerce('box.visible', Boolean(boxWidth || boxFillColor || boxLineColor || boxLineWidth));
  70098. if(!boxVisible) traceOut.box = {visible: false};
  70099. var meanLineColor = coerce2('meanline.color', lineColor);
  70100. var meanLineWidth = coerce2('meanline.width', lineWidth);
  70101. var meanLineVisible = coerce('meanline.visible', Boolean(meanLineColor || meanLineWidth));
  70102. if(!meanLineVisible) traceOut.meanline = {visible: false};
  70103. };
  70104. },{"../../components/color":51,"../../lib":168,"../box/defaults":285,"./attributes":401}],405:[function(_dereq_,module,exports){
  70105. /**
  70106. * Copyright 2012-2019, Plotly, Inc.
  70107. * All rights reserved.
  70108. *
  70109. * This source code is licensed under the MIT license found in the
  70110. * LICENSE file in the root directory of this source tree.
  70111. */
  70112. 'use strict';
  70113. var Lib = _dereq_('../../lib');
  70114. // Maybe add kernels more down the road,
  70115. // but note that the default `spanmode: 'soft'` bounds might have
  70116. // to become kernel-dependent
  70117. var kernels = {
  70118. gaussian: function(v) {
  70119. return (1 / Math.sqrt(2 * Math.PI)) * Math.exp(-0.5 * v * v);
  70120. }
  70121. };
  70122. exports.makeKDE = function(calcItem, trace, vals) {
  70123. var len = vals.length;
  70124. var kernel = kernels.gaussian;
  70125. var bandwidth = calcItem.bandwidth;
  70126. var factor = 1 / (len * bandwidth);
  70127. // don't use Lib.aggNums to skip isNumeric checks
  70128. return function(x) {
  70129. var sum = 0;
  70130. for(var i = 0; i < len; i++) {
  70131. sum += kernel((x - vals[i]) / bandwidth);
  70132. }
  70133. return factor * sum;
  70134. };
  70135. };
  70136. exports.getPositionOnKdePath = function(calcItem, trace, valuePx) {
  70137. var posLetter, valLetter;
  70138. if(trace.orientation === 'h') {
  70139. posLetter = 'y';
  70140. valLetter = 'x';
  70141. } else {
  70142. posLetter = 'x';
  70143. valLetter = 'y';
  70144. }
  70145. var pointOnPath = Lib.findPointOnPath(
  70146. calcItem.path,
  70147. valuePx,
  70148. valLetter,
  70149. {pathLength: calcItem.pathLength}
  70150. );
  70151. var posCenterPx = calcItem.posCenterPx;
  70152. var posOnPath0 = pointOnPath[posLetter];
  70153. var posOnPath1 = trace.side === 'both' ?
  70154. 2 * posCenterPx - posOnPath0 :
  70155. posCenterPx;
  70156. return [posOnPath0, posOnPath1];
  70157. };
  70158. exports.getKdeValue = function(calcItem, trace, valueDist) {
  70159. var vals = calcItem.pts.map(exports.extractVal);
  70160. var kde = exports.makeKDE(calcItem, trace, vals);
  70161. return kde(valueDist) / calcItem.posDensityScale;
  70162. };
  70163. exports.extractVal = function(o) { return o.v; };
  70164. },{"../../lib":168}],406:[function(_dereq_,module,exports){
  70165. /**
  70166. * Copyright 2012-2019, Plotly, Inc.
  70167. * All rights reserved.
  70168. *
  70169. * This source code is licensed under the MIT license found in the
  70170. * LICENSE file in the root directory of this source tree.
  70171. */
  70172. 'use strict';
  70173. var Lib = _dereq_('../../lib');
  70174. var Axes = _dereq_('../../plots/cartesian/axes');
  70175. var boxHoverPoints = _dereq_('../box/hover');
  70176. var helpers = _dereq_('./helpers');
  70177. module.exports = function hoverPoints(pointData, xval, yval, hovermode, hoverLayer) {
  70178. var cd = pointData.cd;
  70179. var trace = cd[0].trace;
  70180. var hoveron = trace.hoveron;
  70181. var hasHoveronViolins = hoveron.indexOf('violins') !== -1;
  70182. var hasHoveronKDE = hoveron.indexOf('kde') !== -1;
  70183. var closeData = [];
  70184. var closePtData;
  70185. var violinLineAttrs;
  70186. if(hasHoveronViolins || hasHoveronKDE) {
  70187. var closeBoxData = boxHoverPoints.hoverOnBoxes(pointData, xval, yval, hovermode);
  70188. if(hasHoveronViolins) {
  70189. closeData = closeData.concat(closeBoxData);
  70190. }
  70191. if(hasHoveronKDE && closeBoxData.length > 0) {
  70192. var xa = pointData.xa;
  70193. var ya = pointData.ya;
  70194. var pLetter, vLetter, pAxis, vAxis, vVal;
  70195. if(trace.orientation === 'h') {
  70196. vVal = xval;
  70197. pLetter = 'y';
  70198. pAxis = ya;
  70199. vLetter = 'x';
  70200. vAxis = xa;
  70201. } else {
  70202. vVal = yval;
  70203. pLetter = 'x';
  70204. pAxis = xa;
  70205. vLetter = 'y';
  70206. vAxis = ya;
  70207. }
  70208. var di = cd[pointData.index];
  70209. if(vVal >= di.span[0] && vVal <= di.span[1]) {
  70210. var kdePointData = Lib.extendFlat({}, pointData);
  70211. var vValPx = vAxis.c2p(vVal, true);
  70212. var kdeVal = helpers.getKdeValue(di, trace, vVal);
  70213. var pOnPath = helpers.getPositionOnKdePath(di, trace, vValPx);
  70214. var paOffset = pAxis._offset;
  70215. var paLength = pAxis._length;
  70216. kdePointData[pLetter + '0'] = pOnPath[0];
  70217. kdePointData[pLetter + '1'] = pOnPath[1];
  70218. kdePointData[vLetter + '0'] = kdePointData[vLetter + '1'] = vValPx;
  70219. kdePointData[vLetter + 'Label'] = vLetter + ': ' + Axes.hoverLabelText(vAxis, vVal) + ', ' + cd[0].t.labels.kde + ' ' + kdeVal.toFixed(3);
  70220. // move the spike to the KDE point
  70221. kdePointData.spikeDistance = closeBoxData[0].spikeDistance;
  70222. var spikePosAttr = pLetter + 'Spike';
  70223. kdePointData[spikePosAttr] = closeBoxData[0][spikePosAttr];
  70224. closeBoxData[0].spikeDistance = undefined;
  70225. closeBoxData[0][spikePosAttr] = undefined;
  70226. closeData.push(kdePointData);
  70227. violinLineAttrs = {stroke: pointData.color};
  70228. violinLineAttrs[pLetter + '1'] = Lib.constrain(paOffset + pOnPath[0], paOffset, paOffset + paLength);
  70229. violinLineAttrs[pLetter + '2'] = Lib.constrain(paOffset + pOnPath[1], paOffset, paOffset + paLength);
  70230. violinLineAttrs[vLetter + '1'] = violinLineAttrs[vLetter + '2'] = vAxis._offset + vValPx;
  70231. }
  70232. }
  70233. }
  70234. if(hoveron.indexOf('points') !== -1) {
  70235. closePtData = boxHoverPoints.hoverOnPoints(pointData, xval, yval);
  70236. }
  70237. // update violin line (if any)
  70238. var violinLine = hoverLayer.selectAll('.violinline-' + trace.uid)
  70239. .data(violinLineAttrs ? [0] : []);
  70240. violinLine.enter().append('line')
  70241. .classed('violinline-' + trace.uid, true)
  70242. .attr('stroke-width', 1.5);
  70243. violinLine.exit().remove();
  70244. violinLine.attr(violinLineAttrs);
  70245. // same combine logic as box hoverPoints
  70246. if(hovermode === 'closest') {
  70247. if(closePtData) return [closePtData];
  70248. return closeData;
  70249. }
  70250. if(closePtData) {
  70251. closeData.push(closePtData);
  70252. return closeData;
  70253. }
  70254. return closeData;
  70255. };
  70256. },{"../../lib":168,"../../plots/cartesian/axes":212,"../box/hover":287,"./helpers":405}],407:[function(_dereq_,module,exports){
  70257. /**
  70258. * Copyright 2012-2019, Plotly, Inc.
  70259. * All rights reserved.
  70260. *
  70261. * This source code is licensed under the MIT license found in the
  70262. * LICENSE file in the root directory of this source tree.
  70263. */
  70264. 'use strict';
  70265. module.exports = {
  70266. attributes: _dereq_('./attributes'),
  70267. layoutAttributes: _dereq_('./layout_attributes'),
  70268. supplyDefaults: _dereq_('./defaults'),
  70269. supplyLayoutDefaults: _dereq_('./layout_defaults'),
  70270. calc: _dereq_('./calc'),
  70271. crossTraceCalc: _dereq_('./cross_trace_calc'),
  70272. plot: _dereq_('./plot'),
  70273. style: _dereq_('./style'),
  70274. styleOnSelect: _dereq_('../scatter/style').styleOnSelect,
  70275. hoverPoints: _dereq_('./hover'),
  70276. selectPoints: _dereq_('../box/select'),
  70277. moduleType: 'trace',
  70278. name: 'violin',
  70279. basePlotModule: _dereq_('../../plots/cartesian'),
  70280. categories: ['cartesian', 'svg', 'symbols', 'oriented', 'box-violin', 'showLegend', 'violinLayout', 'zoomScale'],
  70281. meta: {
  70282. }
  70283. };
  70284. },{"../../plots/cartesian":224,"../box/select":292,"../scatter/style":390,"./attributes":401,"./calc":402,"./cross_trace_calc":403,"./defaults":404,"./hover":406,"./layout_attributes":408,"./layout_defaults":409,"./plot":410,"./style":411}],408:[function(_dereq_,module,exports){
  70285. /**
  70286. * Copyright 2012-2019, Plotly, Inc.
  70287. * All rights reserved.
  70288. *
  70289. * This source code is licensed under the MIT license found in the
  70290. * LICENSE file in the root directory of this source tree.
  70291. */
  70292. 'use strict';
  70293. var boxLayoutAttrs = _dereq_('../box/layout_attributes');
  70294. var extendFlat = _dereq_('../../lib').extendFlat;
  70295. module.exports = {
  70296. violinmode: extendFlat({}, boxLayoutAttrs.boxmode, {
  70297. }),
  70298. violingap: extendFlat({}, boxLayoutAttrs.boxgap, {
  70299. }),
  70300. violingroupgap: extendFlat({}, boxLayoutAttrs.boxgroupgap, {
  70301. })
  70302. };
  70303. },{"../../lib":168,"../box/layout_attributes":289}],409:[function(_dereq_,module,exports){
  70304. /**
  70305. * Copyright 2012-2019, Plotly, Inc.
  70306. * All rights reserved.
  70307. *
  70308. * This source code is licensed under the MIT license found in the
  70309. * LICENSE file in the root directory of this source tree.
  70310. */
  70311. 'use strict';
  70312. var Lib = _dereq_('../../lib');
  70313. var layoutAttributes = _dereq_('./layout_attributes');
  70314. var boxLayoutDefaults = _dereq_('../box/layout_defaults');
  70315. module.exports = function supplyLayoutDefaults(layoutIn, layoutOut, fullData) {
  70316. function coerce(attr, dflt) {
  70317. return Lib.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt);
  70318. }
  70319. boxLayoutDefaults._supply(layoutIn, layoutOut, fullData, coerce, 'violin');
  70320. };
  70321. },{"../../lib":168,"../box/layout_defaults":290,"./layout_attributes":408}],410:[function(_dereq_,module,exports){
  70322. /**
  70323. * Copyright 2012-2019, Plotly, Inc.
  70324. * All rights reserved.
  70325. *
  70326. * This source code is licensed under the MIT license found in the
  70327. * LICENSE file in the root directory of this source tree.
  70328. */
  70329. 'use strict';
  70330. var d3 = _dereq_('d3');
  70331. var Lib = _dereq_('../../lib');
  70332. var Drawing = _dereq_('../../components/drawing');
  70333. var boxPlot = _dereq_('../box/plot');
  70334. var linePoints = _dereq_('../scatter/line_points');
  70335. var helpers = _dereq_('./helpers');
  70336. module.exports = function plot(gd, plotinfo, cdViolins, violinLayer) {
  70337. var fullLayout = gd._fullLayout;
  70338. var xa = plotinfo.xaxis;
  70339. var ya = plotinfo.yaxis;
  70340. function makePath(pts) {
  70341. var segments = linePoints(pts, {
  70342. xaxis: xa,
  70343. yaxis: ya,
  70344. connectGaps: true,
  70345. baseTolerance: 0.75,
  70346. shape: 'spline',
  70347. simplify: true
  70348. });
  70349. return Drawing.smoothopen(segments[0], 1);
  70350. }
  70351. Lib.makeTraceGroups(violinLayer, cdViolins, 'trace violins').each(function(cd) {
  70352. var plotGroup = d3.select(this);
  70353. var cd0 = cd[0];
  70354. var t = cd0.t;
  70355. var trace = cd0.trace;
  70356. if(!plotinfo.isRangePlot) cd0.node3 = plotGroup;
  70357. if(trace.visible !== true || t.empty) {
  70358. plotGroup.remove();
  70359. return;
  70360. }
  70361. var bPos = t.bPos;
  70362. var bdPos = t.bdPos;
  70363. var valAxis = plotinfo[t.valLetter + 'axis'];
  70364. var posAxis = plotinfo[t.posLetter + 'axis'];
  70365. var hasBothSides = trace.side === 'both';
  70366. var hasPositiveSide = hasBothSides || trace.side === 'positive';
  70367. var hasNegativeSide = hasBothSides || trace.side === 'negative';
  70368. var violins = plotGroup.selectAll('path.violin').data(Lib.identity);
  70369. violins.enter().append('path')
  70370. .style('vector-effect', 'non-scaling-stroke')
  70371. .attr('class', 'violin');
  70372. violins.exit().remove();
  70373. violins.each(function(d) {
  70374. var pathSel = d3.select(this);
  70375. var density = d.density;
  70376. var len = density.length;
  70377. var posCenter = d.pos + bPos;
  70378. var posCenterPx = posAxis.c2p(posCenter);
  70379. var scale;
  70380. if(trace.width) {
  70381. scale = t.maxKDE / bdPos;
  70382. } else {
  70383. var groupStats = fullLayout._violinScaleGroupStats[trace.scalegroup];
  70384. scale = trace.scalemode === 'count' ?
  70385. (groupStats.maxKDE / bdPos) * (groupStats.maxCount / d.pts.length) :
  70386. groupStats.maxKDE / bdPos;
  70387. }
  70388. var pathPos, pathNeg, path;
  70389. var i, k, pts, pt;
  70390. if(hasPositiveSide) {
  70391. pts = new Array(len);
  70392. for(i = 0; i < len; i++) {
  70393. pt = pts[i] = {};
  70394. pt[t.posLetter] = posCenter + (density[i].v / scale);
  70395. pt[t.valLetter] = density[i].t;
  70396. }
  70397. pathPos = makePath(pts);
  70398. }
  70399. if(hasNegativeSide) {
  70400. pts = new Array(len);
  70401. for(k = 0, i = len - 1; k < len; k++, i--) {
  70402. pt = pts[k] = {};
  70403. pt[t.posLetter] = posCenter - (density[i].v / scale);
  70404. pt[t.valLetter] = density[i].t;
  70405. }
  70406. pathNeg = makePath(pts);
  70407. }
  70408. if(hasBothSides) {
  70409. path = pathPos + 'L' + pathNeg.substr(1) + 'Z';
  70410. }
  70411. else {
  70412. var startPt = [posCenterPx, valAxis.c2p(density[0].t)];
  70413. var endPt = [posCenterPx, valAxis.c2p(density[len - 1].t)];
  70414. if(trace.orientation === 'h') {
  70415. startPt.reverse();
  70416. endPt.reverse();
  70417. }
  70418. if(hasPositiveSide) {
  70419. path = 'M' + startPt + 'L' + pathPos.substr(1) + 'L' + endPt;
  70420. } else {
  70421. path = 'M' + endPt + 'L' + pathNeg.substr(1) + 'L' + startPt;
  70422. }
  70423. }
  70424. pathSel.attr('d', path);
  70425. // save a few things used in getPositionOnKdePath, getKdeValue
  70426. // on hover and for meanline draw block below
  70427. d.posCenterPx = posCenterPx;
  70428. d.posDensityScale = scale * bdPos;
  70429. d.path = pathSel.node();
  70430. d.pathLength = d.path.getTotalLength() / (hasBothSides ? 2 : 1);
  70431. });
  70432. var boxAttrs = trace.box;
  70433. var boxWidth = boxAttrs.width;
  70434. var boxLineWidth = (boxAttrs.line || {}).width;
  70435. var bdPosScaled;
  70436. var bPosPxOffset;
  70437. if(hasBothSides) {
  70438. bdPosScaled = bdPos * boxWidth;
  70439. bPosPxOffset = 0;
  70440. } else if(hasPositiveSide) {
  70441. bdPosScaled = [0, bdPos * boxWidth / 2];
  70442. bPosPxOffset = -boxLineWidth;
  70443. } else {
  70444. bdPosScaled = [bdPos * boxWidth / 2, 0];
  70445. bPosPxOffset = boxLineWidth;
  70446. }
  70447. // inner box
  70448. boxPlot.plotBoxAndWhiskers(plotGroup, {pos: posAxis, val: valAxis}, trace, {
  70449. bPos: bPos,
  70450. bdPos: bdPosScaled,
  70451. bPosPxOffset: bPosPxOffset
  70452. });
  70453. // meanline insider box
  70454. boxPlot.plotBoxMean(plotGroup, {pos: posAxis, val: valAxis}, trace, {
  70455. bPos: bPos,
  70456. bdPos: bdPosScaled,
  70457. bPosPxOffset: bPosPxOffset
  70458. });
  70459. var fn;
  70460. if(!trace.box.visible && trace.meanline.visible) {
  70461. fn = Lib.identity;
  70462. }
  70463. // N.B. use different class name than boxPlot.plotBoxMean,
  70464. // to avoid selectAll conflict
  70465. var meanPaths = plotGroup.selectAll('path.meanline').data(fn || []);
  70466. meanPaths.enter().append('path')
  70467. .attr('class', 'meanline')
  70468. .style('fill', 'none')
  70469. .style('vector-effect', 'non-scaling-stroke');
  70470. meanPaths.exit().remove();
  70471. meanPaths.each(function(d) {
  70472. var v = valAxis.c2p(d.mean, true);
  70473. var p = helpers.getPositionOnKdePath(d, trace, v);
  70474. d3.select(this).attr('d',
  70475. trace.orientation === 'h' ?
  70476. 'M' + v + ',' + p[0] + 'V' + p[1] :
  70477. 'M' + p[0] + ',' + v + 'H' + p[1]
  70478. );
  70479. });
  70480. boxPlot.plotPoints(plotGroup, {x: xa, y: ya}, trace, t);
  70481. });
  70482. };
  70483. },{"../../components/drawing":72,"../../lib":168,"../box/plot":291,"../scatter/line_points":381,"./helpers":405,"d3":16}],411:[function(_dereq_,module,exports){
  70484. /**
  70485. * Copyright 2012-2019, Plotly, Inc.
  70486. * All rights reserved.
  70487. *
  70488. * This source code is licensed under the MIT license found in the
  70489. * LICENSE file in the root directory of this source tree.
  70490. */
  70491. 'use strict';
  70492. var d3 = _dereq_('d3');
  70493. var Color = _dereq_('../../components/color');
  70494. var stylePoints = _dereq_('../scatter/style').stylePoints;
  70495. module.exports = function style(gd, cd) {
  70496. var s = cd ? cd[0].node3 : d3.select(gd).selectAll('g.trace.violins');
  70497. s.style('opacity', function(d) { return d[0].trace.opacity; });
  70498. s.each(function(d) {
  70499. var trace = d[0].trace;
  70500. var sel = d3.select(this);
  70501. var box = trace.box || {};
  70502. var boxLine = box.line || {};
  70503. var meanline = trace.meanline || {};
  70504. var meanLineWidth = meanline.width;
  70505. sel.selectAll('path.violin')
  70506. .style('stroke-width', trace.line.width + 'px')
  70507. .call(Color.stroke, trace.line.color)
  70508. .call(Color.fill, trace.fillcolor);
  70509. sel.selectAll('path.box')
  70510. .style('stroke-width', boxLine.width + 'px')
  70511. .call(Color.stroke, boxLine.color)
  70512. .call(Color.fill, box.fillcolor);
  70513. var meanLineStyle = {
  70514. 'stroke-width': meanLineWidth + 'px',
  70515. 'stroke-dasharray': (2 * meanLineWidth) + 'px,' + meanLineWidth + 'px'
  70516. };
  70517. sel.selectAll('path.mean')
  70518. .style(meanLineStyle)
  70519. .call(Color.stroke, meanline.color);
  70520. sel.selectAll('path.meanline')
  70521. .style(meanLineStyle)
  70522. .call(Color.stroke, meanline.color);
  70523. stylePoints(sel, trace, gd);
  70524. });
  70525. };
  70526. },{"../../components/color":51,"../scatter/style":390,"d3":16}]},{},[11])(11)
  70527. });