protovis-d3.2.js 516 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905
  1. // 21a9062b1af7e0328b11351e63de4f904867ec28
  2. /**
  3. * @class The built-in Array class.
  4. * @name Array
  5. */
  6. /**
  7. * Creates a new array with the results of calling a provided function on every
  8. * element in this array. Implemented in Javascript 1.6.
  9. *
  10. * @function
  11. * @name Array.prototype.map
  12. * @see <a
  13. * href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Map">map</a>
  14. * documentation.
  15. * @param {function} f function that produces an element of the new Array from
  16. * an element of the current one.
  17. * @param [o] object to use as <tt>this</tt> when executing <tt>f</tt>.
  18. */
  19. if (!Array.prototype.map) Array.prototype.map = function(f, o) {
  20. var n = this.length;
  21. var result = new Array(n);
  22. for (var i = 0; i < n; i++) {
  23. if (i in this) {
  24. result[i] = f.call(o, this[i], i, this);
  25. }
  26. }
  27. return result;
  28. };
  29. /**
  30. * Creates a new array with all elements that pass the test implemented by the
  31. * provided function. Implemented in Javascript 1.6.
  32. *
  33. * @function
  34. * @name Array.prototype.filter
  35. * @see <a
  36. * href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/filter">filter</a>
  37. * documentation.
  38. * @param {function} f function to test each element of the array.
  39. * @param [o] object to use as <tt>this</tt> when executing <tt>f</tt>.
  40. */
  41. if (!Array.prototype.filter) Array.prototype.filter = function(f, o) {
  42. var n = this.length;
  43. var result = new Array();
  44. for (var i = 0; i < n; i++) {
  45. if (i in this) {
  46. var v = this[i];
  47. if (f.call(o, v, i, this)) result.push(v);
  48. }
  49. }
  50. return result;
  51. };
  52. /**
  53. * Executes a provided function once per array element. Implemented in
  54. * Javascript 1.6.
  55. *
  56. * @function
  57. * @name Array.prototype.forEach
  58. * @see <a
  59. * href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/ForEach">forEach</a>
  60. * documentation.
  61. * @param {function} f function to execute for each element.
  62. * @param [o] object to use as <tt>this</tt> when executing <tt>f</tt>.
  63. */
  64. if (!Array.prototype.forEach) Array.prototype.forEach = function(f, o) {
  65. var n = this.length >>> 0;
  66. for (var i = 0; i < n; i++) {
  67. if (i in this) f.call(o, this[i], i, this);
  68. }
  69. };
  70. /**
  71. * Apply a function against an accumulator and each value of the array (from
  72. * left-to-right) as to reduce it to a single value. Implemented in Javascript
  73. * 1.8.
  74. *
  75. * @function
  76. * @name Array.prototype.reduce
  77. * @see <a
  78. * href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Reduce">reduce</a>
  79. * documentation.
  80. * @param {function} f function to execute on each value in the array.
  81. * @param [v] object to use as the first argument to the first call of
  82. * <tt>t</tt>.
  83. */
  84. if (!Array.prototype.reduce) Array.prototype.reduce = function(f, v) {
  85. var len = this.length;
  86. if (!len && (arguments.length == 1)) {
  87. throw new Error("reduce: empty array, no initial value");
  88. }
  89. var i = 0;
  90. if (arguments.length < 2) {
  91. while (true) {
  92. if (i in this) {
  93. v = this[i++];
  94. break;
  95. }
  96. if (++i >= len) {
  97. throw new Error("reduce: no values, no initial value");
  98. }
  99. }
  100. }
  101. for (; i < len; i++) {
  102. if (i in this) {
  103. v = f(v, this[i], i, this);
  104. }
  105. }
  106. return v;
  107. };
  108. /**
  109. * The top-level Protovis namespace. All public methods and fields should be
  110. * registered on this object. Note that core Protovis source is surrounded by an
  111. * anonymous function, so any other declared globals will not be visible outside
  112. * of core methods. This also allows multiple versions of Protovis to coexist,
  113. * since each version will see their own <tt>pv</tt> namespace.
  114. *
  115. * @namespace The top-level Protovis namespace, <tt>pv</tt>.
  116. */
  117. var pv = {};
  118. /**
  119. * Protovis major and minor version numbers.
  120. *
  121. * @namespace Protovis major and minor version numbers.
  122. */
  123. pv.version = {
  124. /**
  125. * The major version number.
  126. *
  127. * @type number
  128. * @constant
  129. */
  130. major: 3,
  131. /**
  132. * The minor version number.
  133. *
  134. * @type number
  135. * @constant
  136. */
  137. minor: 2
  138. };
  139. /**
  140. * Returns the passed-in argument, <tt>x</tt>; the identity function. This method
  141. * is provided for convenience since it is used as the default behavior for a
  142. * number of property functions.
  143. *
  144. * @param x a value.
  145. * @returns the value <tt>x</tt>.
  146. */
  147. pv.identity = function(x) { return x; };
  148. /**
  149. * Returns <tt>this.index</tt>. This method is provided for convenience for use
  150. * with scales. For example, to color bars by their index, say:
  151. *
  152. * <pre>.fillStyle(pv.Colors.category10().by(pv.index))</pre>
  153. *
  154. * This method is equivalent to <tt>function() this.index</tt>, but more
  155. * succinct. Note that the <tt>index</tt> property is also supported for
  156. * accessor functions with {@link pv.max}, {@link pv.min} and other array
  157. * utility methods.
  158. *
  159. * @see pv.Scale
  160. * @see pv.Mark#index
  161. */
  162. pv.index = function() { return this.index; };
  163. /**
  164. * Returns <tt>this.childIndex</tt>. This method is provided for convenience for
  165. * use with scales. For example, to color bars by their child index, say:
  166. *
  167. * <pre>.fillStyle(pv.Colors.category10().by(pv.child))</pre>
  168. *
  169. * This method is equivalent to <tt>function() this.childIndex</tt>, but more
  170. * succinct.
  171. *
  172. * @see pv.Scale
  173. * @see pv.Mark#childIndex
  174. */
  175. pv.child = function() { return this.childIndex; };
  176. /**
  177. * Returns <tt>this.parent.index</tt>. This method is provided for convenience
  178. * for use with scales. This method is provided for convenience for use with
  179. * scales. For example, to color bars by their parent index, say:
  180. *
  181. * <pre>.fillStyle(pv.Colors.category10().by(pv.parent))</pre>
  182. *
  183. * Tthis method is equivalent to <tt>function() this.parent.index</tt>, but more
  184. * succinct.
  185. *
  186. * @see pv.Scale
  187. * @see pv.Mark#index
  188. */
  189. pv.parent = function() { return this.parent.index; };
  190. /**
  191. * Stores the current event. This field is only set within event handlers.
  192. *
  193. * @type Event
  194. * @name pv.event
  195. */
  196. /**
  197. * @private Returns a prototype object suitable for extending the given class
  198. * <tt>f</tt>. Rather than constructing a new instance of <tt>f</tt> to serve as
  199. * the prototype (which unnecessarily runs the constructor on the created
  200. * prototype object, potentially polluting it), an anonymous function is
  201. * generated internally that shares the same prototype:
  202. *
  203. * <pre>function g() {}
  204. * g.prototype = f.prototype;
  205. * return new g();</pre>
  206. *
  207. * For more details, see Douglas Crockford's essay on prototypal inheritance.
  208. *
  209. * @param {function} f a constructor.
  210. * @returns a suitable prototype object.
  211. * @see Douglas Crockford's essay on <a
  212. * href="http://javascript.crockford.com/prototypal.html">prototypal
  213. * inheritance</a>.
  214. */
  215. pv.extend = function(f) {
  216. function g() {}
  217. g.prototype = f.prototype || f;
  218. return new g();
  219. };
  220. try {
  221. eval("pv.parse = function(x) x;"); // native support
  222. } catch (e) {
  223. /**
  224. * @private Parses a Protovis specification, which may use JavaScript 1.8
  225. * function expresses, replacing those function expressions with proper
  226. * functions such that the code can be run by a JavaScript 1.6 interpreter. This
  227. * hack only supports function expressions (using clumsy regular expressions, no
  228. * less), and not other JavaScript 1.8 features such as let expressions.
  229. *
  230. * @param {string} s a Protovis specification (i.e., a string of JavaScript 1.8
  231. * source code).
  232. * @returns {string} a conformant JavaScript 1.6 source code.
  233. */
  234. pv.parse = function(js) { // hacky regex support
  235. var re = new RegExp("function\\s*(\\b\\w+)?\\s*\\([^)]*\\)\\s*", "mg"), m, d, i = 0, s = "";
  236. while (m = re.exec(js)) {
  237. var j = m.index + m[0].length;
  238. if (js.charAt(j) != '{') {
  239. s += js.substring(i, j) + "{return ";
  240. i = j;
  241. for (var p = 0; p >= 0 && j < js.length; j++) {
  242. var c = js.charAt(j);
  243. switch (c) {
  244. case '"': case '\'': {
  245. while (++j < js.length && (d = js.charAt(j)) != c) {
  246. if (d == '\\') j++;
  247. }
  248. break;
  249. }
  250. case '[': case '(': p++; break;
  251. case ']': case ')': p--; break;
  252. case ';':
  253. case ',': if (p == 0) p--; break;
  254. }
  255. }
  256. s += pv.parse(js.substring(i, --j)) + ";}";
  257. i = j;
  258. }
  259. re.lastIndex = j;
  260. }
  261. s += js.substring(i);
  262. return s;
  263. };
  264. }
  265. /**
  266. * @private Computes the value of the specified CSS property <tt>p</tt> on the
  267. * specified element <tt>e</tt>.
  268. *
  269. * @param {string} p the name of the CSS property.
  270. * @param e the element on which to compute the CSS property.
  271. */
  272. pv.css = function(e, p) {
  273. return window.getComputedStyle
  274. ? window.getComputedStyle(e, null).getPropertyValue(p)
  275. : e.currentStyle[p];
  276. };
  277. /**
  278. * @private Reports the specified error to the JavaScript console. Mozilla only
  279. * allows logging to the console for privileged code; if the console is
  280. * unavailable, the alert dialog box is used instead.
  281. *
  282. * @param e the exception that triggered the error.
  283. */
  284. pv.error = function(e) {
  285. (typeof console == "undefined") ? alert(e) : console.error(e);
  286. };
  287. /**
  288. * @private Registers the specified listener for events of the specified type on
  289. * the specified target. For standards-compliant browsers, this method uses
  290. * <tt>addEventListener</tt>; for Internet Explorer, <tt>attachEvent</tt>.
  291. *
  292. * @param target a DOM element.
  293. * @param {string} type the type of event, such as "click".
  294. * @param {function} the event handler callback.
  295. */
  296. pv.listen = function(target, type, listener) {
  297. listener = pv.listener(listener);
  298. return target.addEventListener
  299. ? target.addEventListener(type, listener, false)
  300. : target.attachEvent("on" + type, listener);
  301. };
  302. /**
  303. * @private Returns a wrapper for the specified listener function such that the
  304. * {@link pv.event} is set for the duration of the listener's invocation. The
  305. * wrapper is cached on the returned function, such that duplicate registrations
  306. * of the wrapped event handler are ignored.
  307. *
  308. * @param {function} f an event handler.
  309. * @returns {function} the wrapped event handler.
  310. */
  311. pv.listener = function(f) {
  312. return f.$listener || (f.$listener = function(e) {
  313. try {
  314. pv.event = e || window.event;
  315. return f.call(this, pv.event);
  316. } finally {
  317. delete pv.event;
  318. }
  319. });
  320. };
  321. /**
  322. * @private Returns true iff <i>a</i> is an ancestor of <i>e</i>. This is useful
  323. * for ignoring mouseout and mouseover events that are contained within the
  324. * target element.
  325. */
  326. pv.ancestor = function(a, e) {
  327. while (e) {
  328. if (e == a) return true;
  329. e = e.parentNode;
  330. }
  331. return false;
  332. };
  333. /** @private Returns a locally-unique positive id. */
  334. pv.id = function() {
  335. var id = 1; return function() { return id++; };
  336. }();
  337. /** @private Returns a function wrapping the specified constant. */
  338. pv.functor = function(v) {
  339. return typeof v == "function" ? v : function() { return v; };
  340. };
  341. /*
  342. * Parses the Protovis specifications on load, allowing the use of JavaScript
  343. * 1.8 function expressions on browsers that only support JavaScript 1.6.
  344. *
  345. * @see pv.parse
  346. */
  347. pv.listen(window, "load", function() {
  348. /*
  349. * Note: in Firefox any variables declared here are visible to the eval'd
  350. * script below. Even worse, any global variables declared by the script
  351. * could overwrite local variables here (such as the index, `i`)! To protect
  352. * against this, all variables are explicitly scoped on a pv.$ object.
  353. */
  354. pv.$ = {i:0, x:document.getElementsByTagName("script")};
  355. for (; pv.$.i < pv.$.x.length; pv.$.i++) {
  356. pv.$.s = pv.$.x[pv.$.i];
  357. if (pv.$.s.type == "text/javascript+protovis") {
  358. try {
  359. window.eval(pv.parse(pv.$.s.text));
  360. } catch (e) {
  361. pv.error(e);
  362. }
  363. }
  364. }
  365. delete pv.$;
  366. });
  367. /**
  368. * Abstract; see an implementing class.
  369. *
  370. * @class Represents an abstract text formatter and parser. A <i>format</i> is a
  371. * function that converts an object of a given type, such as a <tt>Date</tt>, to
  372. * a human-readable string representation. The format may also have a
  373. * {@link #parse} method for converting a string representation back to the
  374. * given object type.
  375. *
  376. * <p>Because formats are themselves functions, they can be used directly as
  377. * mark properties. For example, if the data associated with a label are dates,
  378. * a date format can be used as label text:
  379. *
  380. * <pre> .text(pv.Format.date("%m/%d/%y"))</pre>
  381. *
  382. * And as with scales, if the format is used in multiple places, it can be
  383. * convenient to declare it as a global variable and then reference it from the
  384. * appropriate property functions. For example, if the data has a <tt>date</tt>
  385. * attribute, and <tt>format</tt> references a given date format:
  386. *
  387. * <pre> .text(function(d) format(d.date))</pre>
  388. *
  389. * Similarly, to parse a string into a date:
  390. *
  391. * <pre>var date = format.parse("4/30/2010");</pre>
  392. *
  393. * Not all format implementations support parsing. See the implementing class
  394. * for details.
  395. *
  396. * @see pv.Format.date
  397. * @see pv.Format.number
  398. * @see pv.Format.time
  399. */
  400. pv.Format = {};
  401. /**
  402. * Formats the specified object, returning the string representation.
  403. *
  404. * @function
  405. * @name pv.Format.prototype.format
  406. * @param {object} x the object to format.
  407. * @returns {string} the formatted string.
  408. */
  409. /**
  410. * Parses the specified string, returning the object representation.
  411. *
  412. * @function
  413. * @name pv.Format.prototype.parse
  414. * @param {string} x the string to parse.
  415. * @returns {object} the parsed object.
  416. */
  417. /**
  418. * @private Given a string that may be used as part of a regular expression,
  419. * this methods returns an appropriately quoted version of the specified string,
  420. * with any special characters escaped.
  421. *
  422. * @param {string} s a string to quote.
  423. * @returns {string} the quoted string.
  424. */
  425. pv.Format.re = function(s) {
  426. return s.replace(/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g, "\\$&");
  427. };
  428. /**
  429. * @private Optionally pads the specified string <i>s</i> so that it is at least
  430. * <i>n</i> characters long, using the padding character <i>c</i>.
  431. *
  432. * @param {string} c the padding character.
  433. * @param {number} n the minimum string length.
  434. * @param {string} s the string to pad.
  435. * @returns {string} the padded string.
  436. */
  437. pv.Format.pad = function(c, n, s) {
  438. var m = n - String(s).length;
  439. return (m < 1) ? s : new Array(m + 1).join(c) + s;
  440. };
  441. /**
  442. * Constructs a new date format with the specified string pattern.
  443. *
  444. * @class The format string is in the same format expected by the
  445. * <tt>strftime</tt> function in C. The following conversion specifications are
  446. * supported:<ul>
  447. *
  448. * <li>%a - abbreviated weekday name.</li>
  449. * <li>%A - full weekday name.</li>
  450. * <li>%b - abbreviated month names.</li>
  451. * <li>%B - full month names.</li>
  452. * <li>%c - locale's appropriate date and time.</li>
  453. * <li>%C - century number.</li>
  454. * <li>%d - day of month [01,31] (zero padded).</li>
  455. * <li>%D - same as %m/%d/%y.</li>
  456. * <li>%e - day of month [ 1,31] (space padded).</li>
  457. * <li>%h - same as %b.</li>
  458. * <li>%H - hour (24-hour clock) [00,23] (zero padded).</li>
  459. * <li>%I - hour (12-hour clock) [01,12] (zero padded).</li>
  460. * <li>%m - month number [01,12] (zero padded).</li>
  461. * <li>%M - minute [0,59] (zero padded).</li>
  462. * <li>%n - newline character.</li>
  463. * <li>%p - locale's equivalent of a.m. or p.m.</li>
  464. * <li>%r - same as %I:%M:%S %p.</li>
  465. * <li>%R - same as %H:%M.</li>
  466. * <li>%S - second [00,61] (zero padded).</li>
  467. * <li>%t - tab character.</li>
  468. * <li>%T - same as %H:%M:%S.</li>
  469. * <li>%x - same as %m/%d/%y.</li>
  470. * <li>%X - same as %I:%M:%S %p.</li>
  471. * <li>%y - year with century [00,99] (zero padded).</li>
  472. * <li>%Y - year including century.</li>
  473. * <li>%% - %.</li>
  474. *
  475. * </ul>The following conversion specifications are currently <i>unsupported</i>
  476. * for formatting:<ul>
  477. *
  478. * <li>%j - day number [1,366].</li>
  479. * <li>%u - weekday number [1,7].</li>
  480. * <li>%U - week number [00,53].</li>
  481. * <li>%V - week number [01,53].</li>
  482. * <li>%w - weekday number [0,6].</li>
  483. * <li>%W - week number [00,53].</li>
  484. * <li>%Z - timezone name or abbreviation.</li>
  485. *
  486. * </ul>In addition, the following conversion specifications are currently
  487. * <i>unsupported</i> for parsing:<ul>
  488. *
  489. * <li>%a - day of week, either abbreviated or full name.</li>
  490. * <li>%A - same as %a.</li>
  491. * <li>%c - locale's appropriate date and time.</li>
  492. * <li>%C - century number.</li>
  493. * <li>%D - same as %m/%d/%y.</li>
  494. * <li>%I - hour (12-hour clock) [1,12].</li>
  495. * <li>%n - any white space.</li>
  496. * <li>%p - locale's equivalent of a.m. or p.m.</li>
  497. * <li>%r - same as %I:%M:%S %p.</li>
  498. * <li>%R - same as %H:%M.</li>
  499. * <li>%t - same as %n.</li>
  500. * <li>%T - same as %H:%M:%S.</li>
  501. * <li>%x - locale's equivalent to %m/%d/%y.</li>
  502. * <li>%X - locale's equivalent to %I:%M:%S %p.</li>
  503. *
  504. * </ul>
  505. *
  506. * @see <a
  507. * href="http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html">strftime</a>
  508. * documentation.
  509. * @see <a
  510. * href="http://www.opengroup.org/onlinepubs/007908799/xsh/strptime.html">strptime</a>
  511. * documentation.
  512. * @extends pv.Format
  513. * @param {string} pattern the format pattern.
  514. */
  515. pv.Format.date = function(pattern) {
  516. var pad = pv.Format.pad;
  517. /** @private */
  518. function format(d) {
  519. return pattern.replace(/%[a-zA-Z0-9]/g, function(s) {
  520. switch (s) {
  521. case '%a': return [
  522. "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
  523. ][d.getDay()];
  524. case '%A': return [
  525. "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
  526. "Saturday"
  527. ][d.getDay()];
  528. case '%h':
  529. case '%b': return [
  530. "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
  531. "Oct", "Nov", "Dec"
  532. ][d.getMonth()];
  533. case '%B': return [
  534. "January", "February", "March", "April", "May", "June", "July",
  535. "August", "September", "October", "November", "December"
  536. ][d.getMonth()];
  537. case '%c': return d.toLocaleString();
  538. case '%C': return pad("0", 2, Math.floor(d.getFullYear() / 100) % 100);
  539. case '%d': return pad("0", 2, d.getDate());
  540. case '%x':
  541. case '%D': return pad("0", 2, d.getMonth() + 1)
  542. + "/" + pad("0", 2, d.getDate())
  543. + "/" + pad("0", 2, d.getFullYear() % 100);
  544. case '%e': return pad(" ", 2, d.getDate());
  545. case '%H': return pad("0", 2, d.getHours());
  546. case '%I': {
  547. var h = d.getHours() % 12;
  548. return h ? pad("0", 2, h) : 12;
  549. }
  550. // TODO %j: day of year as a decimal number [001,366]
  551. case '%m': return pad("0", 2, d.getMonth() + 1);
  552. case '%M': return pad("0", 2, d.getMinutes());
  553. case '%n': return "\n";
  554. case '%p': return d.getHours() < 12 ? "AM" : "PM";
  555. case '%T':
  556. case '%X':
  557. case '%r': {
  558. var h = d.getHours() % 12;
  559. return (h ? pad("0", 2, h) : 12)
  560. + ":" + pad("0", 2, d.getMinutes())
  561. + ":" + pad("0", 2, d.getSeconds())
  562. + " " + (d.getHours() < 12 ? "AM" : "PM");
  563. }
  564. case '%R': return pad("0", 2, d.getHours()) + ":" + pad("0", 2, d.getMinutes());
  565. case '%S': return pad("0", 2, d.getSeconds());
  566. case '%Q': return pad("0", 3, d.getMilliseconds());
  567. case '%t': return "\t";
  568. case '%u': {
  569. var w = d.getDay();
  570. return w ? w : 1;
  571. }
  572. // TODO %U: week number (sunday first day) [00,53]
  573. // TODO %V: week number (monday first day) [01,53] ... with weirdness
  574. case '%w': return d.getDay();
  575. // TODO %W: week number (monday first day) [00,53] ... with weirdness
  576. case '%y': return pad("0", 2, d.getFullYear() % 100);
  577. case '%Y': return d.getFullYear();
  578. // TODO %Z: timezone name or abbreviation
  579. case '%%': return "%";
  580. }
  581. return s;
  582. });
  583. }
  584. /**
  585. * Converts a date to a string using the associated formatting pattern.
  586. *
  587. * @function
  588. * @name pv.Format.date.prototype.format
  589. * @param {Date} date a date to format.
  590. * @returns {string} the formatted date as a string.
  591. */
  592. format.format = format;
  593. /**
  594. * Parses a date from a string using the associated formatting pattern.
  595. *
  596. * @function
  597. * @name pv.Format.date.prototype.parse
  598. * @param {string} s the string to parse as a date.
  599. * @returns {Date} the parsed date.
  600. */
  601. format.parse = function(s) {
  602. var year = 1970, month = 0, date = 1, hour = 0, minute = 0, second = 0;
  603. var fields = [function() {}];
  604. /* Register callbacks for each field in the format pattern. */
  605. var re = pv.Format.re(pattern).replace(/%[a-zA-Z0-9]/g, function(s) {
  606. switch (s) {
  607. // TODO %a: day of week, either abbreviated or full name
  608. // TODO %A: same as %a
  609. case '%b': {
  610. fields.push(function(x) { month = {
  611. Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7,
  612. Sep: 8, Oct: 9, Nov: 10, Dec: 11
  613. }[x]; });
  614. return "([A-Za-z]+)";
  615. }
  616. case '%h':
  617. case '%B': {
  618. fields.push(function(x) { month = {
  619. January: 0, February: 1, March: 2, April: 3, May: 4, June: 5,
  620. July: 6, August: 7, September: 8, October: 9, November: 10,
  621. December: 11
  622. }[x]; });
  623. return "([A-Za-z]+)";
  624. }
  625. // TODO %c: locale's appropriate date and time
  626. // TODO %C: century number[0,99]
  627. case '%e':
  628. case '%d': {
  629. fields.push(function(x) { date = x; });
  630. return "([0-9]+)";
  631. }
  632. // TODO %D: same as %m/%d/%y
  633. case '%I':
  634. case '%H': {
  635. fields.push(function(x) { hour = x; });
  636. return "([0-9]+)";
  637. }
  638. // TODO %j: day number [1,366]
  639. case '%m': {
  640. fields.push(function(x) { month = x - 1; });
  641. return "([0-9]+)";
  642. }
  643. case '%M': {
  644. fields.push(function(x) { minute = x; });
  645. return "([0-9]+)";
  646. }
  647. // TODO %n: any white space
  648. // TODO %p: locale's equivalent of a.m. or p.m.
  649. case '%p': { // TODO this is a hack
  650. fields.push(function(x) {
  651. if (hour == 12) {
  652. if (x == "am") hour = 0;
  653. } else if (x == "pm") {
  654. hour = Number(hour) + 12;
  655. }
  656. });
  657. return "(am|pm)";
  658. }
  659. // TODO %r: %I:%M:%S %p
  660. // TODO %R: %H:%M
  661. case '%S': {
  662. fields.push(function(x) { second = x; });
  663. return "([0-9]+)";
  664. }
  665. // TODO %t: any white space
  666. // TODO %T: %H:%M:%S
  667. // TODO %U: week number [00,53]
  668. // TODO %w: weekday [0,6]
  669. // TODO %W: week number [00, 53]
  670. // TODO %x: locale date (%m/%d/%y)
  671. // TODO %X: locale time (%I:%M:%S %p)
  672. case '%y': {
  673. fields.push(function(x) {
  674. x = Number(x);
  675. year = x + (((0 <= x) && (x < 69)) ? 2000
  676. : (((x >= 69) && (x < 100) ? 1900 : 0)));
  677. });
  678. return "([0-9]+)";
  679. }
  680. case '%Y': {
  681. fields.push(function(x) { year = x; });
  682. return "([0-9]+)";
  683. }
  684. case '%%': {
  685. fields.push(function() {});
  686. return "%";
  687. }
  688. }
  689. return s;
  690. });
  691. var match = s.match(re);
  692. if (match) match.forEach(function(m, i) { fields[i](m); });
  693. return new Date(year, month, date, hour, minute, second);
  694. };
  695. return format;
  696. };
  697. /**
  698. * Returns a time format of the given type, either "short" or "long".
  699. *
  700. * @class Represents a time format, converting between a <tt>number</tt>
  701. * representing a duration in milliseconds, and a <tt>string</tt>. Two types of
  702. * time formats are supported: "short" and "long". The <i>short</i> format type
  703. * returns a string such as "3.3 days" or "12.1 minutes", while the <i>long</i>
  704. * format returns "13:04:12" or similar.
  705. *
  706. * @extends pv.Format
  707. * @param {string} type the type; "short" or "long".
  708. */
  709. pv.Format.time = function(type) {
  710. var pad = pv.Format.pad;
  711. /*
  712. * MILLISECONDS = 1
  713. * SECONDS = 1e3
  714. * MINUTES = 6e4
  715. * HOURS = 36e5
  716. * DAYS = 864e5
  717. * WEEKS = 6048e5
  718. * MONTHS = 2592e6
  719. * YEARS = 31536e6
  720. */
  721. /** @private */
  722. function format(t) {
  723. t = Number(t); // force conversion from Date
  724. switch (type) {
  725. case "short": {
  726. if (t >= 31536e6) {
  727. return (t / 31536e6).toFixed(1) + " years";
  728. } else if (t >= 6048e5) {
  729. return (t / 6048e5).toFixed(1) + " weeks";
  730. } else if (t >= 864e5) {
  731. return (t / 864e5).toFixed(1) + " days";
  732. } else if (t >= 36e5) {
  733. return (t / 36e5).toFixed(1) + " hours";
  734. } else if (t >= 6e4) {
  735. return (t / 6e4).toFixed(1) + " minutes";
  736. }
  737. return (t / 1e3).toFixed(1) + " seconds";
  738. }
  739. case "long": {
  740. var a = [],
  741. s = ((t % 6e4) / 1e3) >> 0,
  742. m = ((t % 36e5) / 6e4) >> 0;
  743. a.push(pad("0", 2, s));
  744. if (t >= 36e5) {
  745. var h = ((t % 864e5) / 36e5) >> 0;
  746. a.push(pad("0", 2, m));
  747. if (t >= 864e5) {
  748. a.push(pad("0", 2, h));
  749. a.push(Math.floor(t / 864e5).toFixed());
  750. } else {
  751. a.push(h.toFixed());
  752. }
  753. } else {
  754. a.push(m.toFixed());
  755. }
  756. return a.reverse().join(":");
  757. }
  758. }
  759. }
  760. /**
  761. * Formats the specified time, returning the string representation.
  762. *
  763. * @function
  764. * @name pv.Format.time.prototype.format
  765. * @param {number} t the duration in milliseconds. May also be a <tt>Date</tt>.
  766. * @returns {string} the formatted string.
  767. */
  768. format.format = format;
  769. /**
  770. * Parses the specified string, returning the time in milliseconds.
  771. *
  772. * @function
  773. * @name pv.Format.time.prototype.parse
  774. * @param {string} s a formatted string.
  775. * @returns {number} the parsed duration in milliseconds.
  776. */
  777. format.parse = function(s) {
  778. switch (type) {
  779. case "short": {
  780. var re = /([0-9,.]+)\s*([a-z]+)/g, a, t = 0;
  781. while (a = re.exec(s)) {
  782. var f = parseFloat(a[0].replace(",", "")), u = 0;
  783. switch (a[2].toLowerCase()) {
  784. case "year": case "years": u = 31536e6; break;
  785. case "week": case "weeks": u = 6048e5; break;
  786. case "day": case "days": u = 864e5; break;
  787. case "hour": case "hours": u = 36e5; break;
  788. case "minute": case "minutes": u = 6e4; break;
  789. case "second": case "seconds": u = 1e3; break;
  790. }
  791. t += f * u;
  792. }
  793. return t;
  794. }
  795. case "long": {
  796. var a = s.replace(",", "").split(":").reverse(), t = 0;
  797. if (a.length) t += parseFloat(a[0]) * 1e3;
  798. if (a.length > 1) t += parseFloat(a[1]) * 6e4;
  799. if (a.length > 2) t += parseFloat(a[2]) * 36e5;
  800. if (a.length > 3) t += parseFloat(a[3]) * 864e5;
  801. return t;
  802. }
  803. }
  804. }
  805. return format;
  806. };
  807. /**
  808. * Returns a default number format.
  809. *
  810. * @class Represents a number format, converting between a <tt>number</tt> and a
  811. * <tt>string</tt>. This class allows numbers to be formatted with variable
  812. * precision (both for the integral and fractional part of the number), optional
  813. * thousands grouping, and optional padding. The thousands (",") and decimal
  814. * (".") separator can be customized.
  815. *
  816. * @returns {pv.Format.number} a number format.
  817. */
  818. pv.Format.number = function() {
  819. var mini = 0, // default minimum integer digits
  820. maxi = Infinity, // default maximum integer digits
  821. mins = 0, // mini, including group separators
  822. minf = 0, // default minimum fraction digits
  823. maxf = 0, // default maximum fraction digits
  824. maxk = 1, // 10^maxf
  825. padi = "0", // default integer pad
  826. padf = "0", // default fraction pad
  827. padg = true, // whether group separator affects integer padding
  828. decimal = ".", // default decimal separator
  829. group = ","; // default group separator
  830. /** @private */
  831. function format(x) {
  832. /* Round the fractional part, and split on decimal separator. */
  833. if (Infinity > maxf) x = Math.round(x * maxk) / maxk;
  834. var s = String(Math.abs(x)).split(".");
  835. /* Pad, truncate and group the integral part. */
  836. var i = s[0], n = (x < 0) ? "-" : "";
  837. if (i.length > maxi) i = i.substring(i.length - maxi);
  838. if (padg && (i.length < mini)) i = n + new Array(mini - i.length + 1).join(padi) + i;
  839. if (i.length > 3) i = i.replace(/\B(?=(?:\d{3})+(?!\d))/g, group);
  840. if (!padg && (i.length < mins)) i = new Array(mins - i.length + 1).join(padi) + n + i;
  841. s[0] = i;
  842. /* Pad the fractional part. */
  843. var f = s[1] || "";
  844. if (f.length < minf) s[1] = f + new Array(minf - f.length + 1).join(padf);
  845. return s.join(decimal);
  846. }
  847. /**
  848. * @function
  849. * @name pv.Format.number.prototype.format
  850. * @param {number} x
  851. * @returns {string}
  852. */
  853. format.format = format;
  854. /**
  855. * Parses the specified string as a number. Before parsing, leading and
  856. * trailing padding is removed. Group separators are also removed, and the
  857. * decimal separator is replaced with the standard point ("."). The integer
  858. * part is truncated per the maximum integer digits, and the fraction part is
  859. * rounded per the maximum fraction digits.
  860. *
  861. * @function
  862. * @name pv.Format.number.prototype.parse
  863. * @param {string} x the string to parse.
  864. * @returns {number} the parsed number.
  865. */
  866. format.parse = function(x) {
  867. var re = pv.Format.re;
  868. /* Remove leading and trailing padding. Split on the decimal separator. */
  869. var s = String(x)
  870. .replace(new RegExp("^(" + re(padi) + ")*"), "")
  871. .replace(new RegExp("(" + re(padf) + ")*$"), "")
  872. .split(decimal);
  873. /* Remove grouping and truncate the integral part. */
  874. var i = s[0].replace(new RegExp(re(group), "g"), "");
  875. if (i.length > maxi) i = i.substring(i.length - maxi);
  876. /* Round the fractional part. */
  877. var f = s[1] ? Number("0." + s[1]) : 0;
  878. if (Infinity > maxf) f = Math.round(f * maxk) / maxk;
  879. return Math.round(i) + f;
  880. };
  881. /**
  882. * Sets or gets the minimum and maximum number of integer digits. This
  883. * controls the number of decimal digits to display before the decimal
  884. * separator for the integral part of the number. If the number of digits is
  885. * smaller than the minimum, the digits are padded; if the number of digits is
  886. * larger, the digits are truncated, showing only the lower-order digits. The
  887. * default range is [0, Infinity].
  888. *
  889. * <p>If only one argument is specified to this method, this value is used as
  890. * both the minimum and maximum number. If no arguments are specified, a
  891. * two-element array is returned containing the minimum and the maximum.
  892. *
  893. * @function
  894. * @name pv.Format.number.prototype.integerDigits
  895. * @param {number} [min] the minimum integer digits.
  896. * @param {number} [max] the maximum integer digits.
  897. * @returns {pv.Format.number} <tt>this</tt>, or the current integer digits.
  898. */
  899. format.integerDigits = function(min, max) {
  900. if (arguments.length) {
  901. mini = Number(min);
  902. maxi = (arguments.length > 1) ? Number(max) : mini;
  903. mins = mini + Math.floor(mini / 3) * group.length;
  904. return this;
  905. }
  906. return [mini, maxi];
  907. };
  908. /**
  909. * Sets or gets the minimum and maximum number of fraction digits. The
  910. * controls the number of decimal digits to display after the decimal
  911. * separator for the fractional part of the number. If the number of digits is
  912. * smaller than the minimum, the digits are padded; if the number of digits is
  913. * larger, the fractional part is rounded, showing only the higher-order
  914. * digits. The default range is [0, 0].
  915. *
  916. * <p>If only one argument is specified to this method, this value is used as
  917. * both the minimum and maximum number. If no arguments are specified, a
  918. * two-element array is returned containing the minimum and the maximum.
  919. *
  920. * @function
  921. * @name pv.Format.number.prototype.fractionDigits
  922. * @param {number} [min] the minimum fraction digits.
  923. * @param {number} [max] the maximum fraction digits.
  924. * @returns {pv.Format.number} <tt>this</tt>, or the current fraction digits.
  925. */
  926. format.fractionDigits = function(min, max) {
  927. if (arguments.length) {
  928. minf = Number(min);
  929. maxf = (arguments.length > 1) ? Number(max) : minf;
  930. maxk = Math.pow(10, maxf);
  931. return this;
  932. }
  933. return [minf, maxf];
  934. };
  935. /**
  936. * Sets or gets the character used to pad the integer part. The integer pad is
  937. * used when the number of integer digits is smaller than the minimum. The
  938. * default pad character is "0" (zero).
  939. *
  940. * @param {string} [x] the new pad character.
  941. * @returns {pv.Format.number} <tt>this</tt> or the current pad character.
  942. */
  943. format.integerPad = function(x) {
  944. if (arguments.length) {
  945. padi = String(x);
  946. padg = /\d/.test(padi);
  947. return this;
  948. }
  949. return padi;
  950. };
  951. /**
  952. * Sets or gets the character used to pad the fration part. The fraction pad
  953. * is used when the number of fraction digits is smaller than the minimum. The
  954. * default pad character is "0" (zero).
  955. *
  956. * @param {string} [x] the new pad character.
  957. * @returns {pv.Format.number} <tt>this</tt> or the current pad character.
  958. */
  959. format.fractionPad = function(x) {
  960. if (arguments.length) {
  961. padf = String(x);
  962. return this;
  963. }
  964. return padf;
  965. };
  966. /**
  967. * Sets or gets the character used as the decimal point, separating the
  968. * integer and fraction parts of the number. The default decimal point is ".".
  969. *
  970. * @param {string} [x] the new decimal separator.
  971. * @returns {pv.Format.number} <tt>this</tt> or the current decimal separator.
  972. */
  973. format.decimal = function(x) {
  974. if (arguments.length) {
  975. decimal = String(x);
  976. return this;
  977. }
  978. return decimal;
  979. };
  980. /**
  981. * Sets or gets the character used as the group separator, grouping integer
  982. * digits by thousands. The default decimal point is ",". Grouping can be
  983. * disabled by using "" for the separator.
  984. *
  985. * @param {string} [x] the new group separator.
  986. * @returns {pv.Format.number} <tt>this</tt> or the current group separator.
  987. */
  988. format.group = function(x) {
  989. if (arguments.length) {
  990. group = x ? String(x) : "";
  991. mins = mini + Math.floor(mini / 3) * group.length;
  992. return this;
  993. }
  994. return group;
  995. };
  996. return format;
  997. };
  998. /**
  999. * @private A private variant of Array.prototype.map that supports the index
  1000. * property.
  1001. */
  1002. pv.map = function(array, f) {
  1003. var o = {};
  1004. return f
  1005. ? array.map(function(d, i) { o.index = i; return f.call(o, d); })
  1006. : array.slice();
  1007. };
  1008. /**
  1009. * Concatenates the specified array with itself <i>n</i> times. For example,
  1010. * <tt>pv.repeat([1, 2])</tt> returns [1, 2, 1, 2].
  1011. *
  1012. * @param {array} a an array.
  1013. * @param {number} [n] the number of times to repeat; defaults to two.
  1014. * @returns {array} an array that repeats the specified array.
  1015. */
  1016. pv.repeat = function(array, n) {
  1017. if (arguments.length == 1) n = 2;
  1018. return pv.blend(pv.range(n).map(function() { return array; }));
  1019. };
  1020. /**
  1021. * Given two arrays <tt>a</tt> and <tt>b</tt>, <style
  1022. * type="text/css">sub{line-height:0}</style> returns an array of all possible
  1023. * pairs of elements [a<sub>i</sub>, b<sub>j</sub>]. The outer loop is on array
  1024. * <i>a</i>, while the inner loop is on <i>b</i>, such that the order of
  1025. * returned elements is [a<sub>0</sub>, b<sub>0</sub>], [a<sub>0</sub>,
  1026. * b<sub>1</sub>], ... [a<sub>0</sub>, b<sub>m</sub>], [a<sub>1</sub>,
  1027. * b<sub>0</sub>], [a<sub>1</sub>, b<sub>1</sub>], ... [a<sub>1</sub>,
  1028. * b<sub>m</sub>], ... [a<sub>n</sub>, b<sub>m</sub>]. If either array is empty,
  1029. * an empty array is returned.
  1030. *
  1031. * @param {array} a an array.
  1032. * @param {array} b an array.
  1033. * @returns {array} an array of pairs of elements in <tt>a</tt> and <tt>b</tt>.
  1034. */
  1035. pv.cross = function(a, b) {
  1036. var array = [];
  1037. for (var i = 0, n = a.length, m = b.length; i < n; i++) {
  1038. for (var j = 0, x = a[i]; j < m; j++) {
  1039. array.push([x, b[j]]);
  1040. }
  1041. }
  1042. return array;
  1043. };
  1044. /**
  1045. * Given the specified array of arrays, concatenates the arrays into a single
  1046. * array. If the individual arrays are explicitly known, an alternative to blend
  1047. * is to use JavaScript's <tt>concat</tt> method directly. These two equivalent
  1048. * expressions:<ul>
  1049. *
  1050. * <li><tt>pv.blend([[1, 2, 3], ["a", "b", "c"]])</tt>
  1051. * <li><tt>[1, 2, 3].concat(["a", "b", "c"])</tt>
  1052. *
  1053. * </ul>return [1, 2, 3, "a", "b", "c"].
  1054. *
  1055. * @param {array[]} arrays an array of arrays.
  1056. * @returns {array} an array containing all the elements of each array in
  1057. * <tt>arrays</tt>.
  1058. */
  1059. pv.blend = function(arrays) {
  1060. return Array.prototype.concat.apply([], arrays);
  1061. };
  1062. /**
  1063. * Given the specified array of arrays, <style
  1064. * type="text/css">sub{line-height:0}</style> transposes each element
  1065. * array<sub>ij</sub> with array<sub>ji</sub>. If the array has dimensions
  1066. * <i>n</i>&times;<i>m</i>, it will have dimensions <i>m</i>&times;<i>n</i>
  1067. * after this method returns. This method transposes the elements of the array
  1068. * in place, mutating the array, and returning a reference to the array.
  1069. *
  1070. * @param {array[]} arrays an array of arrays.
  1071. * @returns {array[]} the passed-in array, after transposing the elements.
  1072. */
  1073. pv.transpose = function(arrays) {
  1074. var n = arrays.length, m = pv.max(arrays, function(d) { return d.length; });
  1075. if (m > n) {
  1076. arrays.length = m;
  1077. for (var i = n; i < m; i++) {
  1078. arrays[i] = new Array(n);
  1079. }
  1080. for (var i = 0; i < n; i++) {
  1081. for (var j = i + 1; j < m; j++) {
  1082. var t = arrays[i][j];
  1083. arrays[i][j] = arrays[j][i];
  1084. arrays[j][i] = t;
  1085. }
  1086. }
  1087. } else {
  1088. for (var i = 0; i < m; i++) {
  1089. arrays[i].length = n;
  1090. }
  1091. for (var i = 0; i < n; i++) {
  1092. for (var j = 0; j < i; j++) {
  1093. var t = arrays[i][j];
  1094. arrays[i][j] = arrays[j][i];
  1095. arrays[j][i] = t;
  1096. }
  1097. }
  1098. }
  1099. arrays.length = m;
  1100. for (var i = 0; i < m; i++) {
  1101. arrays[i].length = n;
  1102. }
  1103. return arrays;
  1104. };
  1105. /**
  1106. * Returns a normalized copy of the specified array, such that the sum of the
  1107. * returned elements sum to one. If the specified array is not an array of
  1108. * numbers, an optional accessor function <tt>f</tt> can be specified to map the
  1109. * elements to numbers. For example, if <tt>array</tt> is an array of objects,
  1110. * and each object has a numeric property "foo", the expression
  1111. *
  1112. * <pre>pv.normalize(array, function(d) d.foo)</pre>
  1113. *
  1114. * returns a normalized array on the "foo" property. If an accessor function is
  1115. * not specified, the identity function is used. Accessor functions can refer to
  1116. * <tt>this.index</tt>.
  1117. *
  1118. * @param {array} array an array of objects, or numbers.
  1119. * @param {function} [f] an optional accessor function.
  1120. * @returns {number[]} an array of numbers that sums to one.
  1121. */
  1122. pv.normalize = function(array, f) {
  1123. var norm = pv.map(array, f), sum = pv.sum(norm);
  1124. for (var i = 0; i < norm.length; i++) norm[i] /= sum;
  1125. return norm;
  1126. };
  1127. /**
  1128. * Returns a permutation of the specified array, using the specified array of
  1129. * indexes. The returned array contains the corresponding element in
  1130. * <tt>array</tt> for each index in <tt>indexes</tt>, in order. For example,
  1131. *
  1132. * <pre>pv.permute(["a", "b", "c"], [1, 2, 0])</pre>
  1133. *
  1134. * returns <tt>["b", "c", "a"]</tt>. It is acceptable for the array of indexes
  1135. * to be a different length from the array of elements, and for indexes to be
  1136. * duplicated or omitted. The optional accessor function <tt>f</tt> can be used
  1137. * to perform a simultaneous mapping of the array elements. Accessor functions
  1138. * can refer to <tt>this.index</tt>.
  1139. *
  1140. * @param {array} array an array.
  1141. * @param {number[]} indexes an array of indexes into <tt>array</tt>.
  1142. * @param {function} [f] an optional accessor function.
  1143. * @returns {array} an array of elements from <tt>array</tt>; a permutation.
  1144. */
  1145. pv.permute = function(array, indexes, f) {
  1146. if (!f) f = pv.identity;
  1147. var p = new Array(indexes.length), o = {};
  1148. indexes.forEach(function(j, i) { o.index = j; p[i] = f.call(o, array[j]); });
  1149. return p;
  1150. };
  1151. /**
  1152. * Returns a map from key to index for the specified <tt>keys</tt> array. For
  1153. * example,
  1154. *
  1155. * <pre>pv.numerate(["a", "b", "c"])</pre>
  1156. *
  1157. * returns <tt>{a: 0, b: 1, c: 2}</tt>. Note that since JavaScript maps only
  1158. * support string keys, <tt>keys</tt> must contain strings, or other values that
  1159. * naturally map to distinct string values. Alternatively, an optional accessor
  1160. * function <tt>f</tt> can be specified to compute the string key for the given
  1161. * element. Accessor functions can refer to <tt>this.index</tt>.
  1162. *
  1163. * @param {array} keys an array, usually of string keys.
  1164. * @param {function} [f] an optional key function.
  1165. * @returns a map from key to index.
  1166. */
  1167. pv.numerate = function(keys, f) {
  1168. if (!f) f = pv.identity;
  1169. var map = {}, o = {};
  1170. keys.forEach(function(x, i) { o.index = i; map[f.call(o, x)] = i; });
  1171. return map;
  1172. };
  1173. /**
  1174. * Returns the unique elements in the specified array, in the order they appear.
  1175. * Note that since JavaScript maps only support string keys, <tt>array</tt> must
  1176. * contain strings, or other values that naturally map to distinct string
  1177. * values. Alternatively, an optional accessor function <tt>f</tt> can be
  1178. * specified to compute the string key for the given element. Accessor functions
  1179. * can refer to <tt>this.index</tt>.
  1180. *
  1181. * @param {array} array an array, usually of string keys.
  1182. * @param {function} [f] an optional key function.
  1183. * @returns {array} the unique values.
  1184. */
  1185. pv.uniq = function(array, f) {
  1186. if (!f) f = pv.identity;
  1187. var map = {}, keys = [], o = {}, y;
  1188. array.forEach(function(x, i) {
  1189. o.index = i;
  1190. y = f.call(o, x);
  1191. if (!(y in map)) map[y] = keys.push(y);
  1192. });
  1193. return keys;
  1194. };
  1195. /**
  1196. * The comparator function for natural order. This can be used in conjunction with
  1197. * the built-in array <tt>sort</tt> method to sort elements by their natural
  1198. * order, ascending. Note that if no comparator function is specified to the
  1199. * built-in <tt>sort</tt> method, the default order is lexicographic, <i>not</i>
  1200. * natural!
  1201. *
  1202. * @see <a
  1203. * href="http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/sort">Array.sort</a>.
  1204. * @param a an element to compare.
  1205. * @param b an element to compare.
  1206. * @returns {number} negative if a &lt; b; positive if a &gt; b; otherwise 0.
  1207. */
  1208. pv.naturalOrder = function(a, b) {
  1209. return (a < b) ? -1 : ((a > b) ? 1 : 0);
  1210. };
  1211. /**
  1212. * The comparator function for reverse natural order. This can be used in
  1213. * conjunction with the built-in array <tt>sort</tt> method to sort elements by
  1214. * their natural order, descending. Note that if no comparator function is
  1215. * specified to the built-in <tt>sort</tt> method, the default order is
  1216. * lexicographic, <i>not</i> natural!
  1217. *
  1218. * @see #naturalOrder
  1219. * @param a an element to compare.
  1220. * @param b an element to compare.
  1221. * @returns {number} negative if a &lt; b; positive if a &gt; b; otherwise 0.
  1222. */
  1223. pv.reverseOrder = function(b, a) {
  1224. return (a < b) ? -1 : ((a > b) ? 1 : 0);
  1225. };
  1226. /**
  1227. * Searches the specified array of numbers for the specified value using the
  1228. * binary search algorithm. The array must be sorted (as by the <tt>sort</tt>
  1229. * method) prior to making this call. If it is not sorted, the results are
  1230. * undefined. If the array contains multiple elements with the specified value,
  1231. * there is no guarantee which one will be found.
  1232. *
  1233. * <p>The <i>insertion point</i> is defined as the point at which the value
  1234. * would be inserted into the array: the index of the first element greater than
  1235. * the value, or <tt>array.length</tt>, if all elements in the array are less
  1236. * than the specified value. Note that this guarantees that the return value
  1237. * will be nonnegative if and only if the value is found.
  1238. *
  1239. * @param {number[]} array the array to be searched.
  1240. * @param {number} value the value to be searched for.
  1241. * @returns the index of the search value, if it is contained in the array;
  1242. * otherwise, (-(<i>insertion point</i>) - 1).
  1243. * @param {function} [f] an optional key function.
  1244. */
  1245. pv.search = function(array, value, f) {
  1246. if (!f) f = pv.identity;
  1247. var low = 0, high = array.length - 1;
  1248. while (low <= high) {
  1249. var mid = (low + high) >> 1, midValue = f(array[mid]);
  1250. if (midValue < value) low = mid + 1;
  1251. else if (midValue > value) high = mid - 1;
  1252. else return mid;
  1253. }
  1254. return -low - 1;
  1255. };
  1256. pv.search.index = function(array, value, f) {
  1257. var i = pv.search(array, value, f);
  1258. return (i < 0) ? (-i - 1) : i;
  1259. };
  1260. /**
  1261. * Returns an array of numbers, starting at <tt>start</tt>, incrementing by
  1262. * <tt>step</tt>, until <tt>stop</tt> is reached. The stop value is
  1263. * exclusive. If only a single argument is specified, this value is interpeted
  1264. * as the <i>stop</i> value, with the <i>start</i> value as zero. If only two
  1265. * arguments are specified, the step value is implied to be one.
  1266. *
  1267. * <p>The method is modeled after the built-in <tt>range</tt> method from
  1268. * Python. See the Python documentation for more details.
  1269. *
  1270. * @see <a href="http://docs.python.org/library/functions.html#range">Python range</a>
  1271. * @param {number} [start] the start value.
  1272. * @param {number} stop the stop value.
  1273. * @param {number} [step] the step value.
  1274. * @returns {number[]} an array of numbers.
  1275. */
  1276. pv.range = function(start, stop, step) {
  1277. if (arguments.length == 1) {
  1278. stop = start;
  1279. start = 0;
  1280. }
  1281. if (step == undefined) step = 1;
  1282. if ((stop - start) / step == Infinity) throw new Error("range must be finite");
  1283. var array = [], i = 0, j;
  1284. if (step < 0) {
  1285. while ((j = start + step * i++) > stop) {
  1286. array.push(j);
  1287. }
  1288. } else {
  1289. while ((j = start + step * i++) < stop) {
  1290. array.push(j);
  1291. }
  1292. }
  1293. return array;
  1294. };
  1295. /**
  1296. * Returns a random number in the range [<tt>start</tt>, <tt>stop</tt>) that is
  1297. * a multiple of <tt>step</tt>. More specifically, the returned number is of the
  1298. * form <tt>start</tt> + <i>n</i> * <tt>step</tt>, where <i>n</i> is a
  1299. * nonnegative integer. If <tt>step</tt> is not specified, it defaults to 1,
  1300. * returning a random integer if <tt>start</tt> is also an integer.
  1301. *
  1302. * @param {number} [start] the start value value.
  1303. * @param {number} stop the stop value.
  1304. * @param {number} [step] the step value.
  1305. * @returns {number} a random number between <i>start</i> and <i>stop</i>.
  1306. */
  1307. pv.random = function(start, stop, step) {
  1308. if (arguments.length == 1) {
  1309. stop = start;
  1310. start = 0;
  1311. }
  1312. if (step == undefined) step = 1;
  1313. return step
  1314. ? (Math.floor(Math.random() * (stop - start) / step) * step + start)
  1315. : (Math.random() * (stop - start) + start);
  1316. };
  1317. /**
  1318. * Returns the sum of the specified array. If the specified array is not an
  1319. * array of numbers, an optional accessor function <tt>f</tt> can be specified
  1320. * to map the elements to numbers. See {@link #normalize} for an example.
  1321. * Accessor functions can refer to <tt>this.index</tt>.
  1322. *
  1323. * @param {array} array an array of objects, or numbers.
  1324. * @param {function} [f] an optional accessor function.
  1325. * @returns {number} the sum of the specified array.
  1326. */
  1327. pv.sum = function(array, f) {
  1328. var o = {};
  1329. return array.reduce(f
  1330. ? function(p, d, i) { o.index = i; return p + f.call(o, d); }
  1331. : function(p, d) { return p + d; }, 0);
  1332. };
  1333. /**
  1334. * Returns the maximum value of the specified array. If the specified array is
  1335. * not an array of numbers, an optional accessor function <tt>f</tt> can be
  1336. * specified to map the elements to numbers. See {@link #normalize} for an
  1337. * example. Accessor functions can refer to <tt>this.index</tt>.
  1338. *
  1339. * @param {array} array an array of objects, or numbers.
  1340. * @param {function} [f] an optional accessor function.
  1341. * @returns {number} the maximum value of the specified array.
  1342. */
  1343. pv.max = function(array, f) {
  1344. if (f == pv.index) return array.length - 1;
  1345. return Math.max.apply(null, f ? pv.map(array, f) : array);
  1346. };
  1347. /**
  1348. * Returns the index of the maximum value of the specified array. If the
  1349. * specified array is not an array of numbers, an optional accessor function
  1350. * <tt>f</tt> can be specified to map the elements to numbers. See
  1351. * {@link #normalize} for an example. Accessor functions can refer to
  1352. * <tt>this.index</tt>.
  1353. *
  1354. * @param {array} array an array of objects, or numbers.
  1355. * @param {function} [f] an optional accessor function.
  1356. * @returns {number} the index of the maximum value of the specified array.
  1357. */
  1358. pv.max.index = function(array, f) {
  1359. if (!array.length) return -1;
  1360. if (f == pv.index) return array.length - 1;
  1361. if (!f) f = pv.identity;
  1362. var maxi = 0, maxx = -Infinity, o = {};
  1363. for (var i = 0; i < array.length; i++) {
  1364. o.index = i;
  1365. var x = f.call(o, array[i]);
  1366. if (x > maxx) {
  1367. maxx = x;
  1368. maxi = i;
  1369. }
  1370. }
  1371. return maxi;
  1372. }
  1373. /**
  1374. * Returns the minimum value of the specified array of numbers. If the specified
  1375. * array is not an array of numbers, an optional accessor function <tt>f</tt>
  1376. * can be specified to map the elements to numbers. See {@link #normalize} for
  1377. * an example. Accessor functions can refer to <tt>this.index</tt>.
  1378. *
  1379. * @param {array} array an array of objects, or numbers.
  1380. * @param {function} [f] an optional accessor function.
  1381. * @returns {number} the minimum value of the specified array.
  1382. */
  1383. pv.min = function(array, f) {
  1384. if (f == pv.index) return 0;
  1385. return Math.min.apply(null, f ? pv.map(array, f) : array);
  1386. };
  1387. /**
  1388. * Returns the index of the minimum value of the specified array. If the
  1389. * specified array is not an array of numbers, an optional accessor function
  1390. * <tt>f</tt> can be specified to map the elements to numbers. See
  1391. * {@link #normalize} for an example. Accessor functions can refer to
  1392. * <tt>this.index</tt>.
  1393. *
  1394. * @param {array} array an array of objects, or numbers.
  1395. * @param {function} [f] an optional accessor function.
  1396. * @returns {number} the index of the minimum value of the specified array.
  1397. */
  1398. pv.min.index = function(array, f) {
  1399. if (!array.length) return -1;
  1400. if (f == pv.index) return 0;
  1401. if (!f) f = pv.identity;
  1402. var mini = 0, minx = Infinity, o = {};
  1403. for (var i = 0; i < array.length; i++) {
  1404. o.index = i;
  1405. var x = f.call(o, array[i]);
  1406. if (x < minx) {
  1407. minx = x;
  1408. mini = i;
  1409. }
  1410. }
  1411. return mini;
  1412. }
  1413. /**
  1414. * Returns the arithmetic mean, or average, of the specified array. If the
  1415. * specified array is not an array of numbers, an optional accessor function
  1416. * <tt>f</tt> can be specified to map the elements to numbers. See
  1417. * {@link #normalize} for an example. Accessor functions can refer to
  1418. * <tt>this.index</tt>.
  1419. *
  1420. * @param {array} array an array of objects, or numbers.
  1421. * @param {function} [f] an optional accessor function.
  1422. * @returns {number} the mean of the specified array.
  1423. */
  1424. pv.mean = function(array, f) {
  1425. return pv.sum(array, f) / array.length;
  1426. };
  1427. /**
  1428. * Returns the median of the specified array. If the specified array is not an
  1429. * array of numbers, an optional accessor function <tt>f</tt> can be specified
  1430. * to map the elements to numbers. See {@link #normalize} for an example.
  1431. * Accessor functions can refer to <tt>this.index</tt>.
  1432. *
  1433. * @param {array} array an array of objects, or numbers.
  1434. * @param {function} [f] an optional accessor function.
  1435. * @returns {number} the median of the specified array.
  1436. */
  1437. pv.median = function(array, f) {
  1438. if (f == pv.index) return (array.length - 1) / 2;
  1439. array = pv.map(array, f).sort(pv.naturalOrder);
  1440. if (array.length % 2) return array[Math.floor(array.length / 2)];
  1441. var i = array.length / 2;
  1442. return (array[i - 1] + array[i]) / 2;
  1443. };
  1444. /**
  1445. * Returns the unweighted variance of the specified array. If the specified
  1446. * array is not an array of numbers, an optional accessor function <tt>f</tt>
  1447. * can be specified to map the elements to numbers. See {@link #normalize} for
  1448. * an example. Accessor functions can refer to <tt>this.index</tt>.
  1449. *
  1450. * @param {array} array an array of objects, or numbers.
  1451. * @param {function} [f] an optional accessor function.
  1452. * @returns {number} the variance of the specified array.
  1453. */
  1454. pv.variance = function(array, f) {
  1455. if (array.length < 1) return NaN;
  1456. if (array.length == 1) return 0;
  1457. var mean = pv.mean(array, f), sum = 0, o = {};
  1458. if (!f) f = pv.identity;
  1459. for (var i = 0; i < array.length; i++) {
  1460. o.index = i;
  1461. var d = f.call(o, array[i]) - mean;
  1462. sum += d * d;
  1463. }
  1464. return sum;
  1465. };
  1466. /**
  1467. * Returns an unbiased estimation of the standard deviation of a population,
  1468. * given the specified random sample. If the specified array is not an array of
  1469. * numbers, an optional accessor function <tt>f</tt> can be specified to map the
  1470. * elements to numbers. See {@link #normalize} for an example. Accessor
  1471. * functions can refer to <tt>this.index</tt>.
  1472. *
  1473. * @param {array} array an array of objects, or numbers.
  1474. * @param {function} [f] an optional accessor function.
  1475. * @returns {number} the standard deviation of the specified array.
  1476. */
  1477. pv.deviation = function(array, f) {
  1478. return Math.sqrt(pv.variance(array, f) / (array.length - 1));
  1479. };
  1480. /**
  1481. * Returns the logarithm with a given base value.
  1482. *
  1483. * @param {number} x the number for which to compute the logarithm.
  1484. * @param {number} b the base of the logarithm.
  1485. * @returns {number} the logarithm value.
  1486. */
  1487. pv.log = function(x, b) {
  1488. return Math.log(x) / Math.log(b);
  1489. };
  1490. /**
  1491. * Computes a zero-symmetric logarithm. Computes the logarithm of the absolute
  1492. * value of the input, and determines the sign of the output according to the
  1493. * sign of the input value.
  1494. *
  1495. * @param {number} x the number for which to compute the logarithm.
  1496. * @param {number} b the base of the logarithm.
  1497. * @returns {number} the symmetric log value.
  1498. */
  1499. pv.logSymmetric = function(x, b) {
  1500. return (x == 0) ? 0 : ((x < 0) ? -pv.log(-x, b) : pv.log(x, b));
  1501. };
  1502. /**
  1503. * Computes a zero-symmetric logarithm, with adjustment to values between zero
  1504. * and the logarithm base. This adjustment introduces distortion for values less
  1505. * than the base number, but enables simultaneous plotting of log-transformed
  1506. * data involving both positive and negative numbers.
  1507. *
  1508. * @param {number} x the number for which to compute the logarithm.
  1509. * @param {number} b the base of the logarithm.
  1510. * @returns {number} the adjusted, symmetric log value.
  1511. */
  1512. pv.logAdjusted = function(x, b) {
  1513. if (!isFinite(x)) return x;
  1514. var negative = x < 0;
  1515. if (x < b) x += (b - x) / b;
  1516. return negative ? -pv.log(x, b) : pv.log(x, b);
  1517. };
  1518. /**
  1519. * Rounds an input value down according to its logarithm. The method takes the
  1520. * floor of the logarithm of the value and then uses the resulting value as an
  1521. * exponent for the base value.
  1522. *
  1523. * @param {number} x the number for which to compute the logarithm floor.
  1524. * @param {number} b the base of the logarithm.
  1525. * @returns {number} the rounded-by-logarithm value.
  1526. */
  1527. pv.logFloor = function(x, b) {
  1528. return (x > 0)
  1529. ? Math.pow(b, Math.floor(pv.log(x, b)))
  1530. : -Math.pow(b, -Math.floor(-pv.log(-x, b)));
  1531. };
  1532. /**
  1533. * Rounds an input value up according to its logarithm. The method takes the
  1534. * ceiling of the logarithm of the value and then uses the resulting value as an
  1535. * exponent for the base value.
  1536. *
  1537. * @param {number} x the number for which to compute the logarithm ceiling.
  1538. * @param {number} b the base of the logarithm.
  1539. * @returns {number} the rounded-by-logarithm value.
  1540. */
  1541. pv.logCeil = function(x, b) {
  1542. return (x > 0)
  1543. ? Math.pow(b, Math.ceil(pv.log(x, b)))
  1544. : -Math.pow(b, -Math.ceil(-pv.log(-x, b)));
  1545. };
  1546. (function() {
  1547. var radians = Math.PI / 180,
  1548. degrees = 180 / Math.PI;
  1549. /** Returns the number of radians corresponding to the specified degrees. */
  1550. pv.radians = function(degrees) { return radians * degrees; };
  1551. /** Returns the number of degrees corresponding to the specified radians. */
  1552. pv.degrees = function(radians) { return degrees * radians; };
  1553. })();
  1554. /**
  1555. * Returns all of the property names (keys) of the specified object (a map). The
  1556. * order of the returned array is not defined.
  1557. *
  1558. * @param map an object.
  1559. * @returns {string[]} an array of strings corresponding to the keys.
  1560. * @see #entries
  1561. */
  1562. pv.keys = function(map) {
  1563. var array = [];
  1564. for (var key in map) {
  1565. array.push(key);
  1566. }
  1567. return array;
  1568. };
  1569. /**
  1570. * Returns all of the entries (key-value pairs) of the specified object (a
  1571. * map). The order of the returned array is not defined. Each key-value pair is
  1572. * represented as an object with <tt>key</tt> and <tt>value</tt> attributes,
  1573. * e.g., <tt>{key: "foo", value: 42}</tt>.
  1574. *
  1575. * @param map an object.
  1576. * @returns {array} an array of key-value pairs corresponding to the keys.
  1577. */
  1578. pv.entries = function(map) {
  1579. var array = [];
  1580. for (var key in map) {
  1581. array.push({ key: key, value: map[key] });
  1582. }
  1583. return array;
  1584. };
  1585. /**
  1586. * Returns all of the values (attribute values) of the specified object (a
  1587. * map). The order of the returned array is not defined.
  1588. *
  1589. * @param map an object.
  1590. * @returns {array} an array of objects corresponding to the values.
  1591. * @see #entries
  1592. */
  1593. pv.values = function(map) {
  1594. var array = [];
  1595. for (var key in map) {
  1596. array.push(map[key]);
  1597. }
  1598. return array;
  1599. };
  1600. /**
  1601. * Returns a map constructed from the specified <tt>keys</tt>, using the
  1602. * function <tt>f</tt> to compute the value for each key. The single argument to
  1603. * the value function is the key. The callback is invoked only for indexes of
  1604. * the array which have assigned values; it is not invoked for indexes which
  1605. * have been deleted or which have never been assigned values.
  1606. *
  1607. * <p>For example, this expression creates a map from strings to string length:
  1608. *
  1609. * <pre>pv.dict(["one", "three", "seventeen"], function(s) s.length)</pre>
  1610. *
  1611. * The returned value is <tt>{one: 3, three: 5, seventeen: 9}</tt>. Accessor
  1612. * functions can refer to <tt>this.index</tt>.
  1613. *
  1614. * @param {array} keys an array.
  1615. * @param {function} f a value function.
  1616. * @returns a map from keys to values.
  1617. */
  1618. pv.dict = function(keys, f) {
  1619. var m = {}, o = {};
  1620. for (var i = 0; i < keys.length; i++) {
  1621. if (i in keys) {
  1622. var k = keys[i];
  1623. o.index = i;
  1624. m[k] = f.call(o, k);
  1625. }
  1626. }
  1627. return m;
  1628. };
  1629. /**
  1630. * Returns a {@link pv.Dom} operator for the given map. This is a convenience
  1631. * factory method, equivalent to <tt>new pv.Dom(map)</tt>. To apply the operator
  1632. * and retrieve the root node, call {@link pv.Dom#root}; to retrieve all nodes
  1633. * flattened, use {@link pv.Dom#nodes}.
  1634. *
  1635. * @see pv.Dom
  1636. * @param map a map from which to construct a DOM.
  1637. * @returns {pv.Dom} a DOM operator for the specified map.
  1638. */
  1639. pv.dom = function(map) {
  1640. return new pv.Dom(map);
  1641. };
  1642. /**
  1643. * Constructs a DOM operator for the specified map. This constructor should not
  1644. * be invoked directly; use {@link pv.dom} instead.
  1645. *
  1646. * @class Represets a DOM operator for the specified map. This allows easy
  1647. * transformation of a hierarchical JavaScript object (such as a JSON map) to a
  1648. * W3C Document Object Model hierarchy. For more information on which attributes
  1649. * and methods from the specification are supported, see {@link pv.Dom.Node}.
  1650. *
  1651. * <p>Leaves in the map are determined using an associated <i>leaf</i> function;
  1652. * see {@link #leaf}. By default, leaves are any value whose type is not
  1653. * "object", such as numbers or strings.
  1654. *
  1655. * @param map a map from which to construct a DOM.
  1656. */
  1657. pv.Dom = function(map) {
  1658. this.$map = map;
  1659. };
  1660. /** @private The default leaf function. */
  1661. pv.Dom.prototype.$leaf = function(n) {
  1662. return typeof n != "object";
  1663. };
  1664. /**
  1665. * Sets or gets the leaf function for this DOM operator. The leaf function
  1666. * identifies which values in the map are leaves, and which are internal nodes.
  1667. * By default, objects are considered internal nodes, and primitives (such as
  1668. * numbers and strings) are considered leaves.
  1669. *
  1670. * @param {function} f the new leaf function.
  1671. * @returns the current leaf function, or <tt>this</tt>.
  1672. */
  1673. pv.Dom.prototype.leaf = function(f) {
  1674. if (arguments.length) {
  1675. this.$leaf = f;
  1676. return this;
  1677. }
  1678. return this.$leaf;
  1679. };
  1680. /**
  1681. * Applies the DOM operator, returning the root node.
  1682. *
  1683. * @returns {pv.Dom.Node} the root node.
  1684. * @param {string} [nodeName] optional node name for the root.
  1685. */
  1686. pv.Dom.prototype.root = function(nodeName) {
  1687. var leaf = this.$leaf, root = recurse(this.$map);
  1688. /** @private */
  1689. function recurse(map) {
  1690. var n = new pv.Dom.Node();
  1691. for (var k in map) {
  1692. var v = map[k];
  1693. n.appendChild(leaf(v) ? new pv.Dom.Node(v) : recurse(v)).nodeName = k;
  1694. }
  1695. return n;
  1696. }
  1697. root.nodeName = nodeName;
  1698. return root;
  1699. };
  1700. /**
  1701. * Applies the DOM operator, returning the array of all nodes in preorder
  1702. * traversal.
  1703. *
  1704. * @returns {array} the array of nodes in preorder traversal.
  1705. */
  1706. pv.Dom.prototype.nodes = function() {
  1707. return this.root().nodes();
  1708. };
  1709. /**
  1710. * Constructs a DOM node for the specified value. Instances of this class are
  1711. * not typically created directly; instead they are generated from a JavaScript
  1712. * map using the {@link pv.Dom} operator.
  1713. *
  1714. * @class Represents a <tt>Node</tt> in the W3C Document Object Model.
  1715. */
  1716. pv.Dom.Node = function(value) {
  1717. this.nodeValue = value;
  1718. this.childNodes = [];
  1719. };
  1720. /**
  1721. * The node name. When generated from a map, the node name corresponds to the
  1722. * key at the given level in the map. Note that the root node has no associated
  1723. * key, and thus has an undefined node name (and no <tt>parentNode</tt>).
  1724. *
  1725. * @type string
  1726. * @field pv.Dom.Node.prototype.nodeName
  1727. */
  1728. /**
  1729. * The node value. When generated from a map, node value corresponds to the leaf
  1730. * value for leaf nodes, and is undefined for internal nodes.
  1731. *
  1732. * @field pv.Dom.Node.prototype.nodeValue
  1733. */
  1734. /**
  1735. * The array of child nodes. This array is empty for leaf nodes. An easy way to
  1736. * check if child nodes exist is to query <tt>firstChild</tt>.
  1737. *
  1738. * @type array
  1739. * @field pv.Dom.Node.prototype.childNodes
  1740. */
  1741. /**
  1742. * The parent node, which is null for root nodes.
  1743. *
  1744. * @type pv.Dom.Node
  1745. */
  1746. pv.Dom.Node.prototype.parentNode = null;
  1747. /**
  1748. * The first child, which is null for leaf nodes.
  1749. *
  1750. * @type pv.Dom.Node
  1751. */
  1752. pv.Dom.Node.prototype.firstChild = null;
  1753. /**
  1754. * The last child, which is null for leaf nodes.
  1755. *
  1756. * @type pv.Dom.Node
  1757. */
  1758. pv.Dom.Node.prototype.lastChild = null;
  1759. /**
  1760. * The previous sibling node, which is null for the first child.
  1761. *
  1762. * @type pv.Dom.Node
  1763. */
  1764. pv.Dom.Node.prototype.previousSibling = null;
  1765. /**
  1766. * The next sibling node, which is null for the last child.
  1767. *
  1768. * @type pv.Dom.Node
  1769. */
  1770. pv.Dom.Node.prototype.nextSibling = null;
  1771. /**
  1772. * Removes the specified child node from this node.
  1773. *
  1774. * @throws Error if the specified child is not a child of this node.
  1775. * @returns {pv.Dom.Node} the removed child.
  1776. */
  1777. pv.Dom.Node.prototype.removeChild = function(n) {
  1778. var i = this.childNodes.indexOf(n);
  1779. if (i == -1) throw new Error("child not found");
  1780. this.childNodes.splice(i, 1);
  1781. if (n.previousSibling) n.previousSibling.nextSibling = n.nextSibling;
  1782. else this.firstChild = n.nextSibling;
  1783. if (n.nextSibling) n.nextSibling.previousSibling = n.previousSibling;
  1784. else this.lastChild = n.previousSibling;
  1785. delete n.nextSibling;
  1786. delete n.previousSibling;
  1787. delete n.parentNode;
  1788. return n;
  1789. };
  1790. /**
  1791. * Appends the specified child node to this node. If the specified child is
  1792. * already part of the DOM, the child is first removed before being added to
  1793. * this node.
  1794. *
  1795. * @returns {pv.Dom.Node} the appended child.
  1796. */
  1797. pv.Dom.Node.prototype.appendChild = function(n) {
  1798. if (n.parentNode) n.parentNode.removeChild(n);
  1799. n.parentNode = this;
  1800. n.previousSibling = this.lastChild;
  1801. if (this.lastChild) this.lastChild.nextSibling = n;
  1802. else this.firstChild = n;
  1803. this.lastChild = n;
  1804. this.childNodes.push(n);
  1805. return n;
  1806. };
  1807. /**
  1808. * Inserts the specified child <i>n</i> before the given reference child
  1809. * <i>r</i> of this node. If <i>r</i> is null, this method is equivalent to
  1810. * {@link #appendChild}. If <i>n</i> is already part of the DOM, it is first
  1811. * removed before being inserted.
  1812. *
  1813. * @throws Error if <i>r</i> is non-null and not a child of this node.
  1814. * @returns {pv.Dom.Node} the inserted child.
  1815. */
  1816. pv.Dom.Node.prototype.insertBefore = function(n, r) {
  1817. if (!r) return this.appendChild(n);
  1818. var i = this.childNodes.indexOf(r);
  1819. if (i == -1) throw new Error("child not found");
  1820. if (n.parentNode) n.parentNode.removeChild(n);
  1821. n.parentNode = this;
  1822. n.nextSibling = r;
  1823. n.previousSibling = r.previousSibling;
  1824. if (r.previousSibling) {
  1825. r.previousSibling.nextSibling = n;
  1826. } else {
  1827. if (r == this.lastChild) this.lastChild = n;
  1828. this.firstChild = n;
  1829. }
  1830. this.childNodes.splice(i, 0, n);
  1831. return n;
  1832. };
  1833. /**
  1834. * Replaces the specified child <i>r</i> of this node with the node <i>n</i>. If
  1835. * <i>n</i> is already part of the DOM, it is first removed before being added.
  1836. *
  1837. * @throws Error if <i>r</i> is not a child of this node.
  1838. */
  1839. pv.Dom.Node.prototype.replaceChild = function(n, r) {
  1840. var i = this.childNodes.indexOf(r);
  1841. if (i == -1) throw new Error("child not found");
  1842. if (n.parentNode) n.parentNode.removeChild(n);
  1843. n.parentNode = this;
  1844. n.nextSibling = r.nextSibling;
  1845. n.previousSibling = r.previousSibling;
  1846. if (r.previousSibling) r.previousSibling.nextSibling = n;
  1847. else this.firstChild = n;
  1848. if (r.nextSibling) r.nextSibling.previousSibling = n;
  1849. else this.lastChild = n;
  1850. this.childNodes[i] = n;
  1851. return r;
  1852. };
  1853. /**
  1854. * Visits each node in the tree in preorder traversal, applying the specified
  1855. * function <i>f</i>. The arguments to the function are:<ol>
  1856. *
  1857. * <li>The current node.
  1858. * <li>The current depth, starting at 0 for the root node.</ol>
  1859. *
  1860. * @param {function} f a function to apply to each node.
  1861. */
  1862. pv.Dom.Node.prototype.visitBefore = function(f) {
  1863. function visit(n, i) {
  1864. f(n, i);
  1865. for (var c = n.firstChild; c; c = c.nextSibling) {
  1866. visit(c, i + 1);
  1867. }
  1868. }
  1869. visit(this, 0);
  1870. };
  1871. /**
  1872. * Visits each node in the tree in postorder traversal, applying the specified
  1873. * function <i>f</i>. The arguments to the function are:<ol>
  1874. *
  1875. * <li>The current node.
  1876. * <li>The current depth, starting at 0 for the root node.</ol>
  1877. *
  1878. * @param {function} f a function to apply to each node.
  1879. */
  1880. pv.Dom.Node.prototype.visitAfter = function(f) {
  1881. function visit(n, i) {
  1882. for (var c = n.firstChild; c; c = c.nextSibling) {
  1883. visit(c, i + 1);
  1884. }
  1885. f(n, i);
  1886. }
  1887. visit(this, 0);
  1888. };
  1889. /**
  1890. * Sorts child nodes of this node, and all descendent nodes recursively, using
  1891. * the specified comparator function <tt>f</tt>. The comparator function is
  1892. * passed two nodes to compare.
  1893. *
  1894. * <p>Note: during the sort operation, the comparator function should not rely
  1895. * on the tree being well-formed; the values of <tt>previousSibling</tt> and
  1896. * <tt>nextSibling</tt> for the nodes being compared are not defined during the
  1897. * sort operation.
  1898. *
  1899. * @param {function} f a comparator function.
  1900. * @returns this.
  1901. */
  1902. pv.Dom.Node.prototype.sort = function(f) {
  1903. if (this.firstChild) {
  1904. this.childNodes.sort(f);
  1905. var p = this.firstChild = this.childNodes[0], c;
  1906. delete p.previousSibling;
  1907. for (var i = 1; i < this.childNodes.length; i++) {
  1908. p.sort(f);
  1909. c = this.childNodes[i];
  1910. c.previousSibling = p;
  1911. p = p.nextSibling = c;
  1912. }
  1913. this.lastChild = p;
  1914. delete p.nextSibling;
  1915. p.sort(f);
  1916. }
  1917. return this;
  1918. };
  1919. /**
  1920. * Reverses all sibling nodes.
  1921. *
  1922. * @returns this.
  1923. */
  1924. pv.Dom.Node.prototype.reverse = function() {
  1925. var childNodes = [];
  1926. this.visitAfter(function(n) {
  1927. while (n.lastChild) childNodes.push(n.removeChild(n.lastChild));
  1928. for (var c; c = childNodes.pop();) n.insertBefore(c, n.firstChild);
  1929. });
  1930. return this;
  1931. };
  1932. /** Returns all descendants of this node in preorder traversal. */
  1933. pv.Dom.Node.prototype.nodes = function() {
  1934. var array = [];
  1935. /** @private */
  1936. function flatten(node) {
  1937. array.push(node);
  1938. node.childNodes.forEach(flatten);
  1939. }
  1940. flatten(this, array);
  1941. return array;
  1942. };
  1943. /**
  1944. * Toggles the child nodes of this node. If this node is not yet toggled, this
  1945. * method removes all child nodes and appends them to a new <tt>toggled</tt>
  1946. * array attribute on this node. Otherwise, if this node is toggled, this method
  1947. * re-adds all toggled child nodes and deletes the <tt>toggled</tt> attribute.
  1948. *
  1949. * <p>This method has no effect if the node has no child nodes.
  1950. *
  1951. * @param {boolean} [recursive] whether the toggle should apply to descendants.
  1952. */
  1953. pv.Dom.Node.prototype.toggle = function(recursive) {
  1954. if (recursive) return this.toggled
  1955. ? this.visitBefore(function(n) { if (n.toggled) n.toggle(); })
  1956. : this.visitAfter(function(n) { if (!n.toggled) n.toggle(); });
  1957. var n = this;
  1958. if (n.toggled) {
  1959. for (var c; c = n.toggled.pop();) n.appendChild(c);
  1960. delete n.toggled;
  1961. } else if (n.lastChild) {
  1962. n.toggled = [];
  1963. while (n.lastChild) n.toggled.push(n.removeChild(n.lastChild));
  1964. }
  1965. };
  1966. /**
  1967. * Given a flat array of values, returns a simple DOM with each value wrapped by
  1968. * a node that is a child of the root node.
  1969. *
  1970. * @param {array} values.
  1971. * @returns {array} nodes.
  1972. */
  1973. pv.nodes = function(values) {
  1974. var root = new pv.Dom.Node();
  1975. for (var i = 0; i < values.length; i++) {
  1976. root.appendChild(new pv.Dom.Node(values[i]));
  1977. }
  1978. return root.nodes();
  1979. };
  1980. /**
  1981. * Returns a {@link pv.Tree} operator for the specified array. This is a
  1982. * convenience factory method, equivalent to <tt>new pv.Tree(array)</tt>.
  1983. *
  1984. * @see pv.Tree
  1985. * @param {array} array an array from which to construct a tree.
  1986. * @returns {pv.Tree} a tree operator for the specified array.
  1987. */
  1988. pv.tree = function(array) {
  1989. return new pv.Tree(array);
  1990. };
  1991. /**
  1992. * Constructs a tree operator for the specified array. This constructor should
  1993. * not be invoked directly; use {@link pv.tree} instead.
  1994. *
  1995. * @class Represents a tree operator for the specified array. The tree operator
  1996. * allows a hierarchical map to be constructed from an array; it is similar to
  1997. * the {@link pv.Nest} operator, except the hierarchy is derived dynamically
  1998. * from the array elements.
  1999. *
  2000. * <p>For example, given an array of size information for ActionScript classes:
  2001. *
  2002. * <pre>{ name: "flare.flex.FlareVis", size: 4116 },
  2003. * { name: "flare.physics.DragForce", size: 1082 },
  2004. * { name: "flare.physics.GravityForce", size: 1336 }, ...</pre>
  2005. *
  2006. * To facilitate visualization, it may be useful to nest the elements by their
  2007. * package hierarchy:
  2008. *
  2009. * <pre>var tree = pv.tree(classes)
  2010. * .keys(function(d) d.name.split("."))
  2011. * .map();</pre>
  2012. *
  2013. * The resulting tree is:
  2014. *
  2015. * <pre>{ flare: {
  2016. * flex: {
  2017. * FlareVis: {
  2018. * name: "flare.flex.FlareVis",
  2019. * size: 4116 } },
  2020. * physics: {
  2021. * DragForce: {
  2022. * name: "flare.physics.DragForce",
  2023. * size: 1082 },
  2024. * GravityForce: {
  2025. * name: "flare.physics.GravityForce",
  2026. * size: 1336 } },
  2027. * ... } }</pre>
  2028. *
  2029. * By specifying a value function,
  2030. *
  2031. * <pre>var tree = pv.tree(classes)
  2032. * .keys(function(d) d.name.split("."))
  2033. * .value(function(d) d.size)
  2034. * .map();</pre>
  2035. *
  2036. * we can further eliminate redundant data:
  2037. *
  2038. * <pre>{ flare: {
  2039. * flex: {
  2040. * FlareVis: 4116 },
  2041. * physics: {
  2042. * DragForce: 1082,
  2043. * GravityForce: 1336 },
  2044. * ... } }</pre>
  2045. *
  2046. * For visualizations with large data sets, performance improvements may be seen
  2047. * by storing the data in a tree format, and then flattening it into an array at
  2048. * runtime with {@link pv.Flatten}.
  2049. *
  2050. * @param {array} array an array from which to construct a tree.
  2051. */
  2052. pv.Tree = function(array) {
  2053. this.array = array;
  2054. };
  2055. /**
  2056. * Assigns a <i>keys</i> function to this operator; required. The keys function
  2057. * returns an array of <tt>string</tt>s for each element in the associated
  2058. * array; these keys determine how the elements are nested in the tree. The
  2059. * returned keys should be unique for each element in the array; otherwise, the
  2060. * behavior of this operator is undefined.
  2061. *
  2062. * @param {function} k the keys function.
  2063. * @returns {pv.Tree} this.
  2064. */
  2065. pv.Tree.prototype.keys = function(k) {
  2066. this.k = k;
  2067. return this;
  2068. };
  2069. /**
  2070. * Assigns a <i>value</i> function to this operator; optional. The value
  2071. * function specifies an optional transformation of the element in the array
  2072. * before it is inserted into the map. If no value function is specified, it is
  2073. * equivalent to using the identity function.
  2074. *
  2075. * @param {function} k the value function.
  2076. * @returns {pv.Tree} this.
  2077. */
  2078. pv.Tree.prototype.value = function(v) {
  2079. this.v = v;
  2080. return this;
  2081. };
  2082. /**
  2083. * Returns a hierarchical map of values. The hierarchy is determined by the keys
  2084. * function; the values in the map are determined by the value function.
  2085. *
  2086. * @returns a hierarchical map of values.
  2087. */
  2088. pv.Tree.prototype.map = function() {
  2089. var map = {}, o = {};
  2090. for (var i = 0; i < this.array.length; i++) {
  2091. o.index = i;
  2092. var value = this.array[i], keys = this.k.call(o, value), node = map;
  2093. for (var j = 0; j < keys.length - 1; j++) {
  2094. node = node[keys[j]] || (node[keys[j]] = {});
  2095. }
  2096. node[keys[j]] = this.v ? this.v.call(o, value) : value;
  2097. }
  2098. return map;
  2099. };
  2100. /**
  2101. * Returns a {@link pv.Nest} operator for the specified array. This is a
  2102. * convenience factory method, equivalent to <tt>new pv.Nest(array)</tt>.
  2103. *
  2104. * @see pv.Nest
  2105. * @param {array} array an array of elements to nest.
  2106. * @returns {pv.Nest} a nest operator for the specified array.
  2107. */
  2108. pv.nest = function(array) {
  2109. return new pv.Nest(array);
  2110. };
  2111. /**
  2112. * Constructs a nest operator for the specified array. This constructor should
  2113. * not be invoked directly; use {@link pv.nest} instead.
  2114. *
  2115. * @class Represents a {@link Nest} operator for the specified array. Nesting
  2116. * allows elements in an array to be grouped into a hierarchical tree
  2117. * structure. The levels in the tree are specified by <i>key</i> functions. The
  2118. * leaf nodes of the tree can be sorted by value, while the internal nodes can
  2119. * be sorted by key. Finally, the tree can be returned either has a
  2120. * multidimensional array via {@link #entries}, or as a hierarchical map via
  2121. * {@link #map}. The {@link #rollup} routine similarly returns a map, collapsing
  2122. * the elements in each leaf node using a summary function.
  2123. *
  2124. * <p>For example, consider the following tabular data structure of Barley
  2125. * yields, from various sites in Minnesota during 1931-2:
  2126. *
  2127. * <pre>{ yield: 27.00, variety: "Manchuria", year: 1931, site: "University Farm" },
  2128. * { yield: 48.87, variety: "Manchuria", year: 1931, site: "Waseca" },
  2129. * { yield: 27.43, variety: "Manchuria", year: 1931, site: "Morris" }, ...</pre>
  2130. *
  2131. * To facilitate visualization, it may be useful to nest the elements first by
  2132. * year, and then by variety, as follows:
  2133. *
  2134. * <pre>var nest = pv.nest(yields)
  2135. * .key(function(d) d.year)
  2136. * .key(function(d) d.variety)
  2137. * .entries();</pre>
  2138. *
  2139. * This returns a nested array. Each element of the outer array is a key-values
  2140. * pair, listing the values for each distinct key:
  2141. *
  2142. * <pre>{ key: 1931, values: [
  2143. * { key: "Manchuria", values: [
  2144. * { yield: 27.00, variety: "Manchuria", year: 1931, site: "University Farm" },
  2145. * { yield: 48.87, variety: "Manchuria", year: 1931, site: "Waseca" },
  2146. * { yield: 27.43, variety: "Manchuria", year: 1931, site: "Morris" },
  2147. * ...
  2148. * ] },
  2149. * { key: "Glabron", values: [
  2150. * { yield: 43.07, variety: "Glabron", year: 1931, site: "University Farm" },
  2151. * { yield: 55.20, variety: "Glabron", year: 1931, site: "Waseca" },
  2152. * ...
  2153. * ] },
  2154. * ] },
  2155. * { key: 1932, values: ... }</pre>
  2156. *
  2157. * Further details, including sorting and rollup, is provided below on the
  2158. * corresponding methods.
  2159. *
  2160. * @param {array} array an array of elements to nest.
  2161. */
  2162. pv.Nest = function(array) {
  2163. this.array = array;
  2164. this.keys = [];
  2165. };
  2166. /**
  2167. * Nests using the specified key function. Multiple keys may be added to the
  2168. * nest; the array elements will be nested in the order keys are specified.
  2169. *
  2170. * @param {function} key a key function; must return a string or suitable map
  2171. * key.
  2172. * @returns {pv.Nest} this.
  2173. */
  2174. pv.Nest.prototype.key = function(key) {
  2175. this.keys.push(key);
  2176. return this;
  2177. };
  2178. /**
  2179. * Sorts the previously-added keys. The natural sort order is used by default
  2180. * (see {@link pv.naturalOrder}); if an alternative order is desired,
  2181. * <tt>order</tt> should be a comparator function. If this method is not called
  2182. * (i.e., keys are <i>unsorted</i>), keys will appear in the order they appear
  2183. * in the underlying elements array. For example,
  2184. *
  2185. * <pre>pv.nest(yields)
  2186. * .key(function(d) d.year)
  2187. * .key(function(d) d.variety)
  2188. * .sortKeys()
  2189. * .entries()</pre>
  2190. *
  2191. * groups yield data by year, then variety, and sorts the variety groups
  2192. * lexicographically (since the variety attribute is a string).
  2193. *
  2194. * <p>Key sort order is only used in conjunction with {@link #entries}, which
  2195. * returns an array of key-values pairs. If the nest is used to construct a
  2196. * {@link #map} instead, keys are unsorted.
  2197. *
  2198. * @param {function} [order] an optional comparator function.
  2199. * @returns {pv.Nest} this.
  2200. */
  2201. pv.Nest.prototype.sortKeys = function(order) {
  2202. this.keys[this.keys.length - 1].order = order || pv.naturalOrder;
  2203. return this;
  2204. };
  2205. /**
  2206. * Sorts the leaf values. The natural sort order is used by default (see
  2207. * {@link pv.naturalOrder}); if an alternative order is desired, <tt>order</tt>
  2208. * should be a comparator function. If this method is not called (i.e., values
  2209. * are <i>unsorted</i>), values will appear in the order they appear in the
  2210. * underlying elements array. For example,
  2211. *
  2212. * <pre>pv.nest(yields)
  2213. * .key(function(d) d.year)
  2214. * .key(function(d) d.variety)
  2215. * .sortValues(function(a, b) a.yield - b.yield)
  2216. * .entries()</pre>
  2217. *
  2218. * groups yield data by year, then variety, and sorts the values for each
  2219. * variety group by yield.
  2220. *
  2221. * <p>Value sort order, unlike keys, applies to both {@link #entries} and
  2222. * {@link #map}. It has no effect on {@link #rollup}.
  2223. *
  2224. * @param {function} [order] an optional comparator function.
  2225. * @returns {pv.Nest} this.
  2226. */
  2227. pv.Nest.prototype.sortValues = function(order) {
  2228. this.order = order || pv.naturalOrder;
  2229. return this;
  2230. };
  2231. /**
  2232. * Returns a hierarchical map of values. Each key adds one level to the
  2233. * hierarchy. With only a single key, the returned map will have a key for each
  2234. * distinct value of the key function; the correspond value with be an array of
  2235. * elements with that key value. If a second key is added, this will be a nested
  2236. * map. For example:
  2237. *
  2238. * <pre>pv.nest(yields)
  2239. * .key(function(d) d.variety)
  2240. * .key(function(d) d.site)
  2241. * .map()</pre>
  2242. *
  2243. * returns a map <tt>m</tt> such that <tt>m[variety][site]</tt> is an array, a subset of
  2244. * <tt>yields</tt>, with each element having the given variety and site.
  2245. *
  2246. * @returns a hierarchical map of values.
  2247. */
  2248. pv.Nest.prototype.map = function() {
  2249. var map = {}, values = [];
  2250. /* Build the map. */
  2251. for (var i, j = 0; j < this.array.length; j++) {
  2252. var x = this.array[j];
  2253. var m = map;
  2254. for (i = 0; i < this.keys.length - 1; i++) {
  2255. var k = this.keys[i](x);
  2256. if (!m[k]) m[k] = {};
  2257. m = m[k];
  2258. }
  2259. k = this.keys[i](x);
  2260. if (!m[k]) {
  2261. var a = [];
  2262. values.push(a);
  2263. m[k] = a;
  2264. }
  2265. m[k].push(x);
  2266. }
  2267. /* Sort each leaf array. */
  2268. if (this.order) {
  2269. for (var i = 0; i < values.length; i++) {
  2270. values[i].sort(this.order);
  2271. }
  2272. }
  2273. return map;
  2274. };
  2275. /**
  2276. * Returns a hierarchical nested array. This method is similar to
  2277. * {@link pv.entries}, but works recursively on the entire hierarchy. Rather
  2278. * than returning a map like {@link #map}, this method returns a nested
  2279. * array. Each element of the array has a <tt>key</tt> and <tt>values</tt>
  2280. * field. For leaf nodes, the <tt>values</tt> array will be a subset of the
  2281. * underlying elements array; for non-leaf nodes, the <tt>values</tt> array will
  2282. * contain more key-values pairs.
  2283. *
  2284. * <p>For an example usage, see the {@link Nest} constructor.
  2285. *
  2286. * @returns a hierarchical nested array.
  2287. */
  2288. pv.Nest.prototype.entries = function() {
  2289. /** Recursively extracts the entries for the given map. */
  2290. function entries(map) {
  2291. var array = [];
  2292. for (var k in map) {
  2293. var v = map[k];
  2294. array.push({ key: k, values: (v instanceof Array) ? v : entries(v) });
  2295. };
  2296. return array;
  2297. }
  2298. /** Recursively sorts the values for the given key-values array. */
  2299. function sort(array, i) {
  2300. var o = this.keys[i].order;
  2301. if (o) array.sort(function(a, b) { return o(a.key, b.key); });
  2302. if (++i < this.keys.length) {
  2303. for (var j = 0; j < array.length; j++) {
  2304. sort.call(this, array[j].values, i);
  2305. }
  2306. }
  2307. return array;
  2308. }
  2309. return sort.call(this, entries(this.map()), 0);
  2310. };
  2311. /**
  2312. * Returns a rollup map. The behavior of this method is the same as
  2313. * {@link #map}, except that the leaf values are replaced with the return value
  2314. * of the specified rollup function <tt>f</tt>. For example,
  2315. *
  2316. * <pre>pv.nest(yields)
  2317. * .key(function(d) d.site)
  2318. * .rollup(function(v) pv.median(v, function(d) d.yield))</pre>
  2319. *
  2320. * first groups yield data by site, and then returns a map from site to median
  2321. * yield for the given site.
  2322. *
  2323. * @see #map
  2324. * @param {function} f a rollup function.
  2325. * @returns a hierarchical map, with the leaf values computed by <tt>f</tt>.
  2326. */
  2327. pv.Nest.prototype.rollup = function(f) {
  2328. /** Recursively descends to the leaf nodes (arrays) and does rollup. */
  2329. function rollup(map) {
  2330. for (var key in map) {
  2331. var value = map[key];
  2332. if (value instanceof Array) {
  2333. map[key] = f(value);
  2334. } else {
  2335. rollup(value);
  2336. }
  2337. }
  2338. return map;
  2339. }
  2340. return rollup(this.map());
  2341. };
  2342. /**
  2343. * Returns a {@link pv.Flatten} operator for the specified map. This is a
  2344. * convenience factory method, equivalent to <tt>new pv.Flatten(map)</tt>.
  2345. *
  2346. * @see pv.Flatten
  2347. * @param map a map to flatten.
  2348. * @returns {pv.Flatten} a flatten operator for the specified map.
  2349. */
  2350. pv.flatten = function(map) {
  2351. return new pv.Flatten(map);
  2352. };
  2353. /**
  2354. * Constructs a flatten operator for the specified map. This constructor should
  2355. * not be invoked directly; use {@link pv.flatten} instead.
  2356. *
  2357. * @class Represents a flatten operator for the specified array. Flattening
  2358. * allows hierarchical maps to be flattened into an array. The levels in the
  2359. * input tree are specified by <i>key</i> functions.
  2360. *
  2361. * <p>For example, consider the following hierarchical data structure of Barley
  2362. * yields, from various sites in Minnesota during 1931-2:
  2363. *
  2364. * <pre>{ 1931: {
  2365. * Manchuria: {
  2366. * "University Farm": 27.00,
  2367. * "Waseca": 48.87,
  2368. * "Morris": 27.43,
  2369. * ... },
  2370. * Glabron: {
  2371. * "University Farm": 43.07,
  2372. * "Waseca": 55.20,
  2373. * ... } },
  2374. * 1932: {
  2375. * ... } }</pre>
  2376. *
  2377. * To facilitate visualization, it may be useful to flatten the tree into a
  2378. * tabular array:
  2379. *
  2380. * <pre>var array = pv.flatten(yields)
  2381. * .key("year")
  2382. * .key("variety")
  2383. * .key("site")
  2384. * .key("yield")
  2385. * .array();</pre>
  2386. *
  2387. * This returns an array of object elements. Each element in the array has
  2388. * attributes corresponding to this flatten operator's keys:
  2389. *
  2390. * <pre>{ site: "University Farm", variety: "Manchuria", year: 1931, yield: 27 },
  2391. * { site: "Waseca", variety: "Manchuria", year: 1931, yield: 48.87 },
  2392. * { site: "Morris", variety: "Manchuria", year: 1931, yield: 27.43 },
  2393. * { site: "University Farm", variety: "Glabron", year: 1931, yield: 43.07 },
  2394. * { site: "Waseca", variety: "Glabron", year: 1931, yield: 55.2 }, ...</pre>
  2395. *
  2396. * <p>The flatten operator is roughly the inverse of the {@link pv.Nest} and
  2397. * {@link pv.Tree} operators.
  2398. *
  2399. * @param map a map to flatten.
  2400. */
  2401. pv.Flatten = function(map) {
  2402. this.map = map;
  2403. this.keys = [];
  2404. };
  2405. /**
  2406. * Flattens using the specified key function. Multiple keys may be added to the
  2407. * flatten; the tiers of the underlying tree must correspond to the specified
  2408. * keys, in order. The order of the returned array is undefined; however, you
  2409. * can easily sort it.
  2410. *
  2411. * @param {string} key the key name.
  2412. * @param {function} [f] an optional value map function.
  2413. * @returns {pv.Nest} this.
  2414. */
  2415. pv.Flatten.prototype.key = function(key, f) {
  2416. this.keys.push({name: key, value: f});
  2417. delete this.$leaf;
  2418. return this;
  2419. };
  2420. /**
  2421. * Flattens using the specified leaf function. This is an alternative to
  2422. * specifying an explicit set of keys; the tiers of the underlying tree will be
  2423. * determined dynamically by recursing on the values, and the resulting keys
  2424. * will be stored in the entries <tt>keys</tt> attribute. The leaf function must
  2425. * return true for leaves, and false for internal nodes.
  2426. *
  2427. * @param {function} f a leaf function.
  2428. * @returns {pv.Nest} this.
  2429. */
  2430. pv.Flatten.prototype.leaf = function(f) {
  2431. this.keys.length = 0;
  2432. this.$leaf = f;
  2433. return this;
  2434. };
  2435. /**
  2436. * Returns the flattened array. Each entry in the array is an object; each
  2437. * object has attributes corresponding to this flatten operator's keys.
  2438. *
  2439. * @returns an array of elements from the flattened map.
  2440. */
  2441. pv.Flatten.prototype.array = function() {
  2442. var entries = [], stack = [], keys = this.keys, leaf = this.$leaf;
  2443. /* Recursively visit using the leaf function. */
  2444. if (leaf) {
  2445. function recurse(value, i) {
  2446. if (leaf(value)) {
  2447. entries.push({keys: stack.slice(), value: value});
  2448. } else {
  2449. for (var key in value) {
  2450. stack.push(key);
  2451. recurse(value[key], i + 1);
  2452. stack.pop();
  2453. }
  2454. }
  2455. }
  2456. recurse(this.map, 0);
  2457. return entries;
  2458. }
  2459. /* Recursively visits the specified value. */
  2460. function visit(value, i) {
  2461. if (i < keys.length - 1) {
  2462. for (var key in value) {
  2463. stack.push(key);
  2464. visit(value[key], i + 1);
  2465. stack.pop();
  2466. }
  2467. } else {
  2468. entries.push(stack.concat(value));
  2469. }
  2470. }
  2471. visit(this.map, 0);
  2472. return entries.map(function(stack) {
  2473. var m = {};
  2474. for (var i = 0; i < keys.length; i++) {
  2475. var k = keys[i], v = stack[i];
  2476. m[k.name] = k.value ? k.value.call(null, v) : v;
  2477. }
  2478. return m;
  2479. });
  2480. };
  2481. /**
  2482. * Returns a {@link pv.Vector} for the specified <i>x</i> and <i>y</i>
  2483. * coordinate. This is a convenience factory method, equivalent to <tt>new
  2484. * pv.Vector(x, y)</tt>.
  2485. *
  2486. * @see pv.Vector
  2487. * @param {number} x the <i>x</i> coordinate.
  2488. * @param {number} y the <i>y</i> coordinate.
  2489. * @returns {pv.Vector} a vector for the specified coordinates.
  2490. */
  2491. pv.vector = function(x, y) {
  2492. return new pv.Vector(x, y);
  2493. };
  2494. /**
  2495. * Constructs a {@link pv.Vector} for the specified <i>x</i> and <i>y</i>
  2496. * coordinate. This constructor should not be invoked directly; use
  2497. * {@link pv.vector} instead.
  2498. *
  2499. * @class Represents a two-dimensional vector; a 2-tuple <i>&#x27e8;x,
  2500. * y&#x27e9;</i>. The intent of this class is to simplify vector math. Note that
  2501. * in performance-sensitive cases it may be more efficient to represent 2D
  2502. * vectors as simple objects with <tt>x</tt> and <tt>y</tt> attributes, rather
  2503. * than using instances of this class.
  2504. *
  2505. * @param {number} x the <i>x</i> coordinate.
  2506. * @param {number} y the <i>y</i> coordinate.
  2507. */
  2508. pv.Vector = function(x, y) {
  2509. this.x = x;
  2510. this.y = y;
  2511. };
  2512. /**
  2513. * Returns a vector perpendicular to this vector: <i>&#x27e8;-y, x&#x27e9;</i>.
  2514. *
  2515. * @returns {pv.Vector} a perpendicular vector.
  2516. */
  2517. pv.Vector.prototype.perp = function() {
  2518. return new pv.Vector(-this.y, this.x);
  2519. };
  2520. /**
  2521. * Returns a normalized copy of this vector: a vector with the same direction,
  2522. * but unit length. If this vector has zero length this method returns a copy of
  2523. * this vector.
  2524. *
  2525. * @returns {pv.Vector} a unit vector.
  2526. */
  2527. pv.Vector.prototype.norm = function() {
  2528. var l = this.length();
  2529. return this.times(l ? (1 / l) : 1);
  2530. };
  2531. /**
  2532. * Returns the magnitude of this vector, defined as <i>sqrt(x * x + y * y)</i>.
  2533. *
  2534. * @returns {number} a length.
  2535. */
  2536. pv.Vector.prototype.length = function() {
  2537. return Math.sqrt(this.x * this.x + this.y * this.y);
  2538. };
  2539. /**
  2540. * Returns a scaled copy of this vector: <i>&#x27e8;x * k, y * k&#x27e9;</i>.
  2541. * To perform the equivalent divide operation, use <i>1 / k</i>.
  2542. *
  2543. * @param {number} k the scale factor.
  2544. * @returns {pv.Vector} a scaled vector.
  2545. */
  2546. pv.Vector.prototype.times = function(k) {
  2547. return new pv.Vector(this.x * k, this.y * k);
  2548. };
  2549. /**
  2550. * Returns this vector plus the vector <i>v</i>: <i>&#x27e8;x + v.x, y +
  2551. * v.y&#x27e9;</i>. If only one argument is specified, it is interpreted as the
  2552. * vector <i>v</i>.
  2553. *
  2554. * @param {number} x the <i>x</i> coordinate to add.
  2555. * @param {number} y the <i>y</i> coordinate to add.
  2556. * @returns {pv.Vector} a new vector.
  2557. */
  2558. pv.Vector.prototype.plus = function(x, y) {
  2559. return (arguments.length == 1)
  2560. ? new pv.Vector(this.x + x.x, this.y + x.y)
  2561. : new pv.Vector(this.x + x, this.y + y);
  2562. };
  2563. /**
  2564. * Returns this vector minus the vector <i>v</i>: <i>&#x27e8;x - v.x, y -
  2565. * v.y&#x27e9;</i>. If only one argument is specified, it is interpreted as the
  2566. * vector <i>v</i>.
  2567. *
  2568. * @param {number} x the <i>x</i> coordinate to subtract.
  2569. * @param {number} y the <i>y</i> coordinate to subtract.
  2570. * @returns {pv.Vector} a new vector.
  2571. */
  2572. pv.Vector.prototype.minus = function(x, y) {
  2573. return (arguments.length == 1)
  2574. ? new pv.Vector(this.x - x.x, this.y - x.y)
  2575. : new pv.Vector(this.x - x, this.y - y);
  2576. };
  2577. /**
  2578. * Returns the dot product of this vector and the vector <i>v</i>: <i>x * v.x +
  2579. * y * v.y</i>. If only one argument is specified, it is interpreted as the
  2580. * vector <i>v</i>.
  2581. *
  2582. * @param {number} x the <i>x</i> coordinate to dot.
  2583. * @param {number} y the <i>y</i> coordinate to dot.
  2584. * @returns {number} a dot product.
  2585. */
  2586. pv.Vector.prototype.dot = function(x, y) {
  2587. return (arguments.length == 1)
  2588. ? this.x * x.x + this.y * x.y
  2589. : this.x * x + this.y * y;
  2590. };
  2591. /**
  2592. * Returns a new identity transform.
  2593. *
  2594. * @class Represents a transformation matrix. The transformation matrix is
  2595. * limited to expressing translate and uniform scale transforms only; shearing,
  2596. * rotation, general affine, and other transforms are not supported.
  2597. *
  2598. * <p>The methods on this class treat the transform as immutable, returning a
  2599. * copy of the transformation matrix with the specified transform applied. Note,
  2600. * alternatively, that the matrix fields can be get and set directly.
  2601. */
  2602. pv.Transform = function() {};
  2603. pv.Transform.prototype = {k: 1, x: 0, y: 0};
  2604. /**
  2605. * The scale magnitude; defaults to 1.
  2606. *
  2607. * @type number
  2608. * @name pv.Transform.prototype.k
  2609. */
  2610. /**
  2611. * The x-offset; defaults to 0.
  2612. *
  2613. * @type number
  2614. * @name pv.Transform.prototype.x
  2615. */
  2616. /**
  2617. * The y-offset; defaults to 0.
  2618. *
  2619. * @type number
  2620. * @name pv.Transform.prototype.y
  2621. */
  2622. /**
  2623. * @private The identity transform.
  2624. *
  2625. * @type pv.Transform
  2626. */
  2627. pv.Transform.identity = new pv.Transform();
  2628. // k 0 x 1 0 a k 0 ka+x
  2629. // 0 k y * 0 1 b = 0 k kb+y
  2630. // 0 0 1 0 0 1 0 0 1
  2631. /**
  2632. * Returns a translated copy of this transformation matrix.
  2633. *
  2634. * @param {number} x the x-offset.
  2635. * @param {number} y the y-offset.
  2636. * @returns {pv.Transform} the translated transformation matrix.
  2637. */
  2638. pv.Transform.prototype.translate = function(x, y) {
  2639. var v = new pv.Transform();
  2640. v.k = this.k;
  2641. v.x = this.k * x + this.x;
  2642. v.y = this.k * y + this.y;
  2643. return v;
  2644. };
  2645. // k 0 x d 0 0 kd 0 x
  2646. // 0 k y * 0 d 0 = 0 kd y
  2647. // 0 0 1 0 0 1 0 0 1
  2648. /**
  2649. * Returns a scaled copy of this transformation matrix.
  2650. *
  2651. * @param {number} k
  2652. * @returns {pv.Transform} the scaled transformation matrix.
  2653. */
  2654. pv.Transform.prototype.scale = function(k) {
  2655. var v = new pv.Transform();
  2656. v.k = this.k * k;
  2657. v.x = this.x;
  2658. v.y = this.y;
  2659. return v;
  2660. };
  2661. /**
  2662. * Returns the inverse of this transformation matrix.
  2663. *
  2664. * @returns {pv.Transform} the inverted transformation matrix.
  2665. */
  2666. pv.Transform.prototype.invert = function() {
  2667. var v = new pv.Transform(), k = 1 / this.k;
  2668. v.k = k;
  2669. v.x = -this.x * k;
  2670. v.y = -this.y * k;
  2671. return v;
  2672. };
  2673. // k 0 x d 0 a kd 0 ka+x
  2674. // 0 k y * 0 d b = 0 kd kb+y
  2675. // 0 0 1 0 0 1 0 0 1
  2676. /**
  2677. * Returns this matrix post-multiplied by the specified matrix <i>m</i>.
  2678. *
  2679. * @param {pv.Transform} m
  2680. * @returns {pv.Transform} the post-multiplied transformation matrix.
  2681. */
  2682. pv.Transform.prototype.times = function(m) {
  2683. var v = new pv.Transform();
  2684. v.k = this.k * m.k;
  2685. v.x = this.k * m.x + this.x;
  2686. v.y = this.k * m.y + this.y;
  2687. return v;
  2688. };
  2689. /**
  2690. * Abstract; see the various scale implementations.
  2691. *
  2692. * @class Represents a scale; a function that performs a transformation from
  2693. * data domain to visual range. For quantitative and quantile scales, the domain
  2694. * is expressed as numbers; for ordinal scales, the domain is expressed as
  2695. * strings (or equivalently objects with unique string representations). The
  2696. * "visual range" may correspond to pixel space, colors, font sizes, and the
  2697. * like.
  2698. *
  2699. * <p>Note that scales are functions, and thus can be used as properties
  2700. * directly, assuming that the data associated with a mark is a number. While
  2701. * this is convenient for single-use scales, frequently it is desirable to
  2702. * define scales globally:
  2703. *
  2704. * <pre>var y = pv.Scale.linear(0, 100).range(0, 640);</pre>
  2705. *
  2706. * The <tt>y</tt> scale can now be equivalently referenced within a property:
  2707. *
  2708. * <pre> .height(function(d) y(d))</pre>
  2709. *
  2710. * Alternatively, if the data are not simple numbers, the appropriate value can
  2711. * be passed to the <tt>y</tt> scale (e.g., <tt>d.foo</tt>). The {@link #by}
  2712. * method similarly allows the data to be mapped to a numeric value before
  2713. * performing the linear transformation.
  2714. *
  2715. * @see pv.Scale.quantitative
  2716. * @see pv.Scale.quantile
  2717. * @see pv.Scale.ordinal
  2718. * @extends function
  2719. */
  2720. pv.Scale = function() {};
  2721. /**
  2722. * @private Returns a function that interpolators from the start value to the
  2723. * end value, given a parameter <i>t</i> in [0, 1].
  2724. *
  2725. * @param start the start value.
  2726. * @param end the end value.
  2727. */
  2728. pv.Scale.interpolator = function(start, end) {
  2729. if (typeof start == "number") {
  2730. return function(t) {
  2731. return t * (end - start) + start;
  2732. };
  2733. }
  2734. /* For now, assume color. */
  2735. start = pv.color(start).rgb();
  2736. end = pv.color(end).rgb();
  2737. return function(t) {
  2738. var a = start.a * (1 - t) + end.a * t;
  2739. if (a < 1e-5) a = 0; // avoid scientific notation
  2740. return (start.a == 0) ? pv.rgb(end.r, end.g, end.b, a)
  2741. : ((end.a == 0) ? pv.rgb(start.r, start.g, start.b, a)
  2742. : pv.rgb(
  2743. Math.round(start.r * (1 - t) + end.r * t),
  2744. Math.round(start.g * (1 - t) + end.g * t),
  2745. Math.round(start.b * (1 - t) + end.b * t), a));
  2746. };
  2747. };
  2748. /**
  2749. * Returns a view of this scale by the specified accessor function <tt>f</tt>.
  2750. * Given a scale <tt>y</tt>, <tt>y.by(function(d) d.foo)</tt> is equivalent to
  2751. * <tt>function(d) y(d.foo)</tt>.
  2752. *
  2753. * <p>This method is provided for convenience, such that scales can be
  2754. * succinctly defined inline. For example, given an array of data elements that
  2755. * have a <tt>score</tt> attribute with the domain [0, 1], the height property
  2756. * could be specified as:
  2757. *
  2758. * <pre> .height(pv.Scale.linear().range(0, 480).by(function(d) d.score))</pre>
  2759. *
  2760. * This is equivalent to:
  2761. *
  2762. * <pre> .height(function(d) d.score * 480)</pre>
  2763. *
  2764. * This method should be used judiciously; it is typically more clear to invoke
  2765. * the scale directly, passing in the value to be scaled.
  2766. *
  2767. * @function
  2768. * @name pv.Scale.prototype.by
  2769. * @param {function} f an accessor function.
  2770. * @returns {pv.Scale} a view of this scale by the specified accessor function.
  2771. */
  2772. /**
  2773. * Returns a default quantitative, linear, scale for the specified domain. The
  2774. * arguments to this constructor are optional, and equivalent to calling
  2775. * {@link #domain}. The default domain and range are [0,1].
  2776. *
  2777. * <p>This constructor is typically not used directly; see one of the
  2778. * quantitative scale implementations instead.
  2779. *
  2780. * @class Represents an abstract quantitative scale; a function that performs a
  2781. * numeric transformation. This class is typically not used directly; see one of
  2782. * the quantitative scale implementations (linear, log, root, etc.)
  2783. * instead. <style type="text/css">sub{line-height:0}</style> A quantitative
  2784. * scale represents a 1-dimensional transformation from a numeric domain of
  2785. * input data [<i>d<sub>0</sub></i>, <i>d<sub>1</sub></i>] to a numeric range of
  2786. * pixels [<i>r<sub>0</sub></i>, <i>r<sub>1</sub></i>]. In addition to
  2787. * readability, scales offer several useful features:
  2788. *
  2789. * <p>1. The range can be expressed in colors, rather than pixels. For example:
  2790. *
  2791. * <pre> .fillStyle(pv.Scale.linear(0, 100).range("red", "green"))</pre>
  2792. *
  2793. * will fill the marks "red" on an input value of 0, "green" on an input value
  2794. * of 100, and some color in-between for intermediate values.
  2795. *
  2796. * <p>2. The domain and range can be subdivided for a non-uniform
  2797. * transformation. For example, you may want a diverging color scale that is
  2798. * increasingly red for negative values, and increasingly green for positive
  2799. * values:
  2800. *
  2801. * <pre> .fillStyle(pv.Scale.linear(-1, 0, 1).range("red", "white", "green"))</pre>
  2802. *
  2803. * The domain can be specified as a series of <i>n</i> monotonically-increasing
  2804. * values; the range must also be specified as <i>n</i> values, resulting in
  2805. * <i>n - 1</i> contiguous linear scales.
  2806. *
  2807. * <p>3. Quantitative scales can be inverted for interaction. The
  2808. * {@link #invert} method takes a value in the output range, and returns the
  2809. * corresponding value in the input domain. This is frequently used to convert
  2810. * the mouse location (see {@link pv.Mark#mouse}) to a value in the input
  2811. * domain. Note that inversion is only supported for numeric ranges, and not
  2812. * colors.
  2813. *
  2814. * <p>4. A scale can be queried for reasonable "tick" values. The {@link #ticks}
  2815. * method provides a convenient way to get a series of evenly-spaced rounded
  2816. * values in the input domain. Frequently these are used in conjunction with
  2817. * {@link pv.Rule} to display tick marks or grid lines.
  2818. *
  2819. * <p>5. A scale can be "niced" to extend the domain to suitable rounded
  2820. * numbers. If the minimum and maximum of the domain are messy because they are
  2821. * derived from data, you can use {@link #nice} to round these values down and
  2822. * up to even numbers.
  2823. *
  2824. * @param {number...} domain... optional domain values.
  2825. * @see pv.Scale.linear
  2826. * @see pv.Scale.log
  2827. * @see pv.Scale.root
  2828. * @extends pv.Scale
  2829. */
  2830. pv.Scale.quantitative = function() {
  2831. var d = [0, 1], // default domain
  2832. l = [0, 1], // default transformed domain
  2833. r = [0, 1], // default range
  2834. i = [pv.identity], // default interpolators
  2835. type = Number, // default type
  2836. n = false, // whether the domain is negative
  2837. f = pv.identity, // default forward transform
  2838. g = pv.identity, // default inverse transform
  2839. tickFormat = String; // default tick formatting function
  2840. /** @private */
  2841. function newDate(x) {
  2842. return new Date(x);
  2843. }
  2844. /** @private */
  2845. function scale(x) {
  2846. var j = pv.search(d, x);
  2847. if (j < 0) j = -j - 2;
  2848. j = Math.max(0, Math.min(i.length - 1, j));
  2849. return i[j]((f(x) - l[j]) / (l[j + 1] - l[j]));
  2850. }
  2851. /** @private */
  2852. scale.transform = function(forward, inverse) {
  2853. /** @ignore */ f = function(x) { return n ? -forward(-x) : forward(x); };
  2854. /** @ignore */ g = function(y) { return n ? -inverse(-y) : inverse(y); };
  2855. l = d.map(f);
  2856. return this;
  2857. };
  2858. /**
  2859. * Sets or gets the input domain. This method can be invoked several ways:
  2860. *
  2861. * <p>1. <tt>domain(min, ..., max)</tt>
  2862. *
  2863. * <p>Specifying the domain as a series of numbers is the most explicit and
  2864. * recommended approach. Most commonly, two numbers are specified: the minimum
  2865. * and maximum value. However, for a diverging scale, or other subdivided
  2866. * non-uniform scales, multiple values can be specified. Values can be derived
  2867. * from data using {@link pv.min} and {@link pv.max}. For example:
  2868. *
  2869. * <pre> .domain(0, pv.max(array))</pre>
  2870. *
  2871. * An alternative method for deriving minimum and maximum values from data
  2872. * follows.
  2873. *
  2874. * <p>2. <tt>domain(array, minf, maxf)</tt>
  2875. *
  2876. * <p>When both the minimum and maximum value are derived from data, the
  2877. * arguments to the <tt>domain</tt> method can be specified as the array of
  2878. * data, followed by zero, one or two accessor functions. For example, if the
  2879. * array of data is just an array of numbers:
  2880. *
  2881. * <pre> .domain(array)</pre>
  2882. *
  2883. * On the other hand, if the array elements are objects representing stock
  2884. * values per day, and the domain should consider the stock's daily low and
  2885. * daily high:
  2886. *
  2887. * <pre> .domain(array, function(d) d.low, function(d) d.high)</pre>
  2888. *
  2889. * The first method of setting the domain is preferred because it is more
  2890. * explicit; setting the domain using this second method should be used only
  2891. * if brevity is required.
  2892. *
  2893. * <p>3. <tt>domain()</tt>
  2894. *
  2895. * <p>Invoking the <tt>domain</tt> method with no arguments returns the
  2896. * current domain as an array of numbers.
  2897. *
  2898. * @function
  2899. * @name pv.Scale.quantitative.prototype.domain
  2900. * @param {number...} domain... domain values.
  2901. * @returns {pv.Scale.quantitative} <tt>this</tt>, or the current domain.
  2902. */
  2903. scale.domain = function(array, min, max) {
  2904. if (arguments.length) {
  2905. var o; // the object we use to infer the domain type
  2906. if (array instanceof Array) {
  2907. if (arguments.length < 2) min = pv.identity;
  2908. if (arguments.length < 3) max = min;
  2909. o = array.length && min(array[0]);
  2910. d = array.length ? [pv.min(array, min), pv.max(array, max)] : [];
  2911. } else {
  2912. o = array;
  2913. d = Array.prototype.slice.call(arguments).map(Number);
  2914. }
  2915. if (!d.length) d = [-Infinity, Infinity];
  2916. else if (d.length == 1) d = [d[0], d[0]];
  2917. n = (d[0] || d[d.length - 1]) < 0;
  2918. l = d.map(f);
  2919. type = (o instanceof Date) ? newDate : Number;
  2920. return this;
  2921. }
  2922. return d.map(type);
  2923. };
  2924. /**
  2925. * Sets or gets the output range. This method can be invoked several ways:
  2926. *
  2927. * <p>1. <tt>range(min, ..., max)</tt>
  2928. *
  2929. * <p>The range may be specified as a series of numbers or colors. Most
  2930. * commonly, two numbers are specified: the minimum and maximum pixel values.
  2931. * For a color scale, values may be specified as {@link pv.Color}s or
  2932. * equivalent strings. For a diverging scale, or other subdivided non-uniform
  2933. * scales, multiple values can be specified. For example:
  2934. *
  2935. * <pre> .range("red", "white", "green")</pre>
  2936. *
  2937. * <p>Currently, only numbers and colors are supported as range values. The
  2938. * number of range values must exactly match the number of domain values, or
  2939. * the behavior of the scale is undefined.
  2940. *
  2941. * <p>2. <tt>range()</tt>
  2942. *
  2943. * <p>Invoking the <tt>range</tt> method with no arguments returns the current
  2944. * range as an array of numbers or colors.
  2945. *
  2946. * @function
  2947. * @name pv.Scale.quantitative.prototype.range
  2948. * @param {...} range... range values.
  2949. * @returns {pv.Scale.quantitative} <tt>this</tt>, or the current range.
  2950. */
  2951. scale.range = function() {
  2952. if (arguments.length) {
  2953. r = Array.prototype.slice.call(arguments);
  2954. if (!r.length) r = [-Infinity, Infinity];
  2955. else if (r.length == 1) r = [r[0], r[0]];
  2956. i = [];
  2957. for (var j = 0; j < r.length - 1; j++) {
  2958. i.push(pv.Scale.interpolator(r[j], r[j + 1]));
  2959. }
  2960. return this;
  2961. }
  2962. return r;
  2963. };
  2964. /**
  2965. * Inverts the specified value in the output range, returning the
  2966. * corresponding value in the input domain. This is frequently used to convert
  2967. * the mouse location (see {@link pv.Mark#mouse}) to a value in the input
  2968. * domain. Inversion is only supported for numeric ranges, and not colors.
  2969. *
  2970. * <p>Note that this method does not do any rounding or bounds checking. If
  2971. * the input domain is discrete (e.g., an array index), the returned value
  2972. * should be rounded. If the specified <tt>y</tt> value is outside the range,
  2973. * the returned value may be equivalently outside the input domain.
  2974. *
  2975. * @function
  2976. * @name pv.Scale.quantitative.prototype.invert
  2977. * @param {number} y a value in the output range (a pixel location).
  2978. * @returns {number} a value in the input domain.
  2979. */
  2980. scale.invert = function(y) {
  2981. var j = pv.search(r, y);
  2982. if (j < 0) j = -j - 2;
  2983. j = Math.max(0, Math.min(i.length - 1, j));
  2984. return type(g(l[j] + (y - r[j]) / (r[j + 1] - r[j]) * (l[j + 1] - l[j])));
  2985. };
  2986. /**
  2987. * Returns an array of evenly-spaced, suitably-rounded values in the input
  2988. * domain. This method attempts to return between 5 and 10 tick values. These
  2989. * values are frequently used in conjunction with {@link pv.Rule} to display
  2990. * tick marks or grid lines.
  2991. *
  2992. * @function
  2993. * @name pv.Scale.quantitative.prototype.ticks
  2994. * @param {number} [m] optional number of desired ticks.
  2995. * @returns {number[]} an array input domain values to use as ticks.
  2996. */
  2997. scale.ticks = function(m) {
  2998. var start = d[0],
  2999. end = d[d.length - 1],
  3000. reverse = end < start,
  3001. min = reverse ? end : start,
  3002. max = reverse ? start : end,
  3003. span = max - min;
  3004. /* Special case: empty, invalid or infinite span. */
  3005. if (!span || !isFinite(span)) {
  3006. if (type == newDate) tickFormat = pv.Format.date("%x");
  3007. return [type(min)];
  3008. }
  3009. /* Special case: dates. */
  3010. if (type == newDate) {
  3011. /* Floor the date d given the precision p. */
  3012. function floor(d, p) {
  3013. switch (p) {
  3014. case 31536e6: d.setMonth(0);
  3015. case 2592e6: d.setDate(1);
  3016. case 6048e5: if (p == 6048e5) d.setDate(d.getDate() - d.getDay());
  3017. case 864e5: d.setHours(0);
  3018. case 36e5: d.setMinutes(0);
  3019. case 6e4: d.setSeconds(0);
  3020. case 1e3: d.setMilliseconds(0);
  3021. }
  3022. }
  3023. var precision, format, increment, step = 1;
  3024. if (span >= 3 * 31536e6) {
  3025. precision = 31536e6;
  3026. format = "%Y";
  3027. /** @ignore */ increment = function(d) { d.setFullYear(d.getFullYear() + step); };
  3028. } else if (span >= 3 * 2592e6) {
  3029. precision = 2592e6;
  3030. format = "%m/%Y";
  3031. /** @ignore */ increment = function(d) { d.setMonth(d.getMonth() + step); };
  3032. } else if (span >= 3 * 6048e5) {
  3033. precision = 6048e5;
  3034. format = "%m/%d";
  3035. /** @ignore */ increment = function(d) { d.setDate(d.getDate() + 7 * step); };
  3036. } else if (span >= 3 * 864e5) {
  3037. precision = 864e5;
  3038. format = "%m/%d";
  3039. /** @ignore */ increment = function(d) { d.setDate(d.getDate() + step); };
  3040. } else if (span >= 3 * 36e5) {
  3041. precision = 36e5;
  3042. format = "%I:%M %p";
  3043. /** @ignore */ increment = function(d) { d.setHours(d.getHours() + step); };
  3044. } else if (span >= 3 * 6e4) {
  3045. precision = 6e4;
  3046. format = "%I:%M %p";
  3047. /** @ignore */ increment = function(d) { d.setMinutes(d.getMinutes() + step); };
  3048. } else if (span >= 3 * 1e3) {
  3049. precision = 1e3;
  3050. format = "%I:%M:%S";
  3051. /** @ignore */ increment = function(d) { d.setSeconds(d.getSeconds() + step); };
  3052. } else {
  3053. precision = 1;
  3054. format = "%S.%Qs";
  3055. /** @ignore */ increment = function(d) { d.setTime(d.getTime() + step); };
  3056. }
  3057. tickFormat = pv.Format.date(format);
  3058. var date = new Date(min), dates = [];
  3059. floor(date, precision);
  3060. /* If we'd generate too many ticks, skip some!. */
  3061. var n = span / precision;
  3062. if (n > 10) {
  3063. switch (precision) {
  3064. case 36e5: {
  3065. step = (n > 20) ? 6 : 3;
  3066. date.setHours(Math.floor(date.getHours() / step) * step);
  3067. break;
  3068. }
  3069. case 2592e6: {
  3070. step = 3; // seasons
  3071. date.setMonth(Math.floor(date.getMonth() / step) * step);
  3072. break;
  3073. }
  3074. case 6e4: {
  3075. step = (n > 30) ? 15 : ((n > 15) ? 10 : 5);
  3076. date.setMinutes(Math.floor(date.getMinutes() / step) * step);
  3077. break;
  3078. }
  3079. case 1e3: {
  3080. step = (n > 90) ? 15 : ((n > 60) ? 10 : 5);
  3081. date.setSeconds(Math.floor(date.getSeconds() / step) * step);
  3082. break;
  3083. }
  3084. case 1: {
  3085. step = (n > 1000) ? 250 : ((n > 200) ? 100 : ((n > 100) ? 50 : ((n > 50) ? 25 : 5)));
  3086. date.setMilliseconds(Math.floor(date.getMilliseconds() / step) * step);
  3087. break;
  3088. }
  3089. default: {
  3090. step = pv.logCeil(n / 15, 10);
  3091. if (n / step < 2) step /= 5;
  3092. else if (n / step < 5) step /= 2;
  3093. date.setFullYear(Math.floor(date.getFullYear() / step) * step);
  3094. break;
  3095. }
  3096. }
  3097. }
  3098. while (true) {
  3099. increment(date);
  3100. if (date > max) break;
  3101. dates.push(new Date(date));
  3102. }
  3103. return reverse ? dates.reverse() : dates;
  3104. }
  3105. /* Normal case: numbers. */
  3106. if (!arguments.length) m = 10;
  3107. var step = pv.logFloor(span / m, 10),
  3108. err = m / (span / step);
  3109. if (err <= .15) step *= 10;
  3110. else if (err <= .35) step *= 5;
  3111. else if (err <= .75) step *= 2;
  3112. var start = Math.ceil(min / step) * step,
  3113. end = Math.floor(max / step) * step;
  3114. tickFormat = pv.Format.number()
  3115. .fractionDigits(Math.max(0, -Math.floor(pv.log(step, 10) + .01)));
  3116. var ticks = pv.range(start, end + step, step);
  3117. return reverse ? ticks.reverse() : ticks;
  3118. };
  3119. /**
  3120. * Formats the specified tick value using the appropriate precision, based on
  3121. * the step interval between tick marks. If {@link #ticks} has not been called,
  3122. * the argument is converted to a string, but no formatting is applied.
  3123. *
  3124. * @function
  3125. * @name pv.Scale.quantitative.prototype.tickFormat
  3126. * @param {number} t a tick value.
  3127. * @returns {string} a formatted tick value.
  3128. */
  3129. scale.tickFormat = function (t) { return tickFormat(t); };
  3130. /**
  3131. * "Nices" this scale, extending the bounds of the input domain to
  3132. * evenly-rounded values. Nicing is useful if the domain is computed
  3133. * dynamically from data, and may be irregular. For example, given a domain of
  3134. * [0.20147987687960267, 0.996679553296417], a call to <tt>nice()</tt> might
  3135. * extend the domain to [0.2, 1].
  3136. *
  3137. * <p>This method must be invoked each time after setting the domain.
  3138. *
  3139. * @function
  3140. * @name pv.Scale.quantitative.prototype.nice
  3141. * @returns {pv.Scale.quantitative} <tt>this</tt>.
  3142. */
  3143. scale.nice = function() {
  3144. if (d.length != 2) return this; // TODO support non-uniform domains
  3145. var start = d[0],
  3146. end = d[d.length - 1],
  3147. reverse = end < start,
  3148. min = reverse ? end : start,
  3149. max = reverse ? start : end,
  3150. span = max - min;
  3151. /* Special case: empty, invalid or infinite span. */
  3152. if (!span || !isFinite(span)) return this;
  3153. var step = Math.pow(10, Math.round(Math.log(span) / Math.log(10)) - 1);
  3154. d = [Math.floor(min / step) * step, Math.ceil(max / step) * step];
  3155. if (reverse) d.reverse();
  3156. l = d.map(f);
  3157. return this;
  3158. };
  3159. /**
  3160. * Returns a view of this scale by the specified accessor function <tt>f</tt>.
  3161. * Given a scale <tt>y</tt>, <tt>y.by(function(d) d.foo)</tt> is equivalent to
  3162. * <tt>function(d) y(d.foo)</tt>.
  3163. *
  3164. * <p>This method is provided for convenience, such that scales can be
  3165. * succinctly defined inline. For example, given an array of data elements
  3166. * that have a <tt>score</tt> attribute with the domain [0, 1], the height
  3167. * property could be specified as:
  3168. *
  3169. * <pre> .height(pv.Scale.linear().range(0, 480).by(function(d) d.score))</pre>
  3170. *
  3171. * This is equivalent to:
  3172. *
  3173. * <pre> .height(function(d) d.score * 480)</pre>
  3174. *
  3175. * This method should be used judiciously; it is typically more clear to
  3176. * invoke the scale directly, passing in the value to be scaled.
  3177. *
  3178. * @function
  3179. * @name pv.Scale.quantitative.prototype.by
  3180. * @param {function} f an accessor function.
  3181. * @returns {pv.Scale.quantitative} a view of this scale by the specified
  3182. * accessor function.
  3183. */
  3184. scale.by = function(f) {
  3185. function by() { return scale(f.apply(this, arguments)); }
  3186. for (var method in scale) by[method] = scale[method];
  3187. return by;
  3188. };
  3189. scale.domain.apply(scale, arguments);
  3190. return scale;
  3191. };
  3192. /**
  3193. * Returns a linear scale for the specified domain. The arguments to this
  3194. * constructor are optional, and equivalent to calling {@link #domain}.
  3195. * The default domain and range are [0,1].
  3196. *
  3197. * @class Represents a linear scale; a function that performs a linear
  3198. * transformation. <style type="text/css">sub{line-height:0}</style> Most
  3199. * commonly, a linear scale represents a 1-dimensional linear transformation
  3200. * from a numeric domain of input data [<i>d<sub>0</sub></i>,
  3201. * <i>d<sub>1</sub></i>] to a numeric range of pixels [<i>r<sub>0</sub></i>,
  3202. * <i>r<sub>1</sub></i>]. The equation for such a scale is:
  3203. *
  3204. * <blockquote><i>f(x) = (x - d<sub>0</sub>) / (d<sub>1</sub> - d<sub>0</sub>) *
  3205. * (r<sub>1</sub> - r<sub>0</sub>) + r<sub>0</sub></i></blockquote>
  3206. *
  3207. * For example, a linear scale from the domain [0, 100] to range [0, 640]:
  3208. *
  3209. * <blockquote><i>f(x) = (x - 0) / (100 - 0) * (640 - 0) + 0</i><br>
  3210. * <i>f(x) = x / 100 * 640</i><br>
  3211. * <i>f(x) = x * 6.4</i><br>
  3212. * </blockquote>
  3213. *
  3214. * Thus, saying
  3215. *
  3216. * <pre> .height(function(d) d * 6.4)</pre>
  3217. *
  3218. * is identical to
  3219. *
  3220. * <pre> .height(pv.Scale.linear(0, 100).range(0, 640))</pre>
  3221. *
  3222. * Note that the scale is itself a function, and thus can be used as a property
  3223. * directly, assuming that the data associated with a mark is a number. While
  3224. * this is convenient for single-use scales, frequently it is desirable to
  3225. * define scales globally:
  3226. *
  3227. * <pre>var y = pv.Scale.linear(0, 100).range(0, 640);</pre>
  3228. *
  3229. * The <tt>y</tt> scale can now be equivalently referenced within a property:
  3230. *
  3231. * <pre> .height(function(d) y(d))</pre>
  3232. *
  3233. * Alternatively, if the data are not simple numbers, the appropriate value can
  3234. * be passed to the <tt>y</tt> scale (e.g., <tt>d.foo</tt>). The {@link #by}
  3235. * method similarly allows the data to be mapped to a numeric value before
  3236. * performing the linear transformation.
  3237. *
  3238. * @param {number...} domain... optional domain values.
  3239. * @extends pv.Scale.quantitative
  3240. */
  3241. pv.Scale.linear = function() {
  3242. var scale = pv.Scale.quantitative();
  3243. scale.domain.apply(scale, arguments);
  3244. return scale;
  3245. };
  3246. /**
  3247. * Returns a log scale for the specified domain. The arguments to this
  3248. * constructor are optional, and equivalent to calling {@link #domain}.
  3249. * The default domain is [1,10] and the default range is [0,1].
  3250. *
  3251. * @class Represents a log scale. <style
  3252. * type="text/css">sub{line-height:0}</style> Most commonly, a log scale
  3253. * represents a 1-dimensional log transformation from a numeric domain of input
  3254. * data [<i>d<sub>0</sub></i>, <i>d<sub>1</sub></i>] to a numeric range of
  3255. * pixels [<i>r<sub>0</sub></i>, <i>r<sub>1</sub></i>]. The equation for such a
  3256. * scale is:
  3257. *
  3258. * <blockquote><i>f(x) = (log(x) - log(d<sub>0</sub>)) / (log(d<sub>1</sub>) -
  3259. * log(d<sub>0</sub>)) * (r<sub>1</sub> - r<sub>0</sub>) +
  3260. * r<sub>0</sub></i></blockquote>
  3261. *
  3262. * where <i>log(x)</i> represents the zero-symmetric logarthim of <i>x</i> using
  3263. * the scale's associated base (default: 10, see {@link pv.logSymmetric}). For
  3264. * example, a log scale from the domain [1, 100] to range [0, 640]:
  3265. *
  3266. * <blockquote><i>f(x) = (log(x) - log(1)) / (log(100) - log(1)) * (640 - 0) + 0</i><br>
  3267. * <i>f(x) = log(x) / 2 * 640</i><br>
  3268. * <i>f(x) = log(x) * 320</i><br>
  3269. * </blockquote>
  3270. *
  3271. * Thus, saying
  3272. *
  3273. * <pre> .height(function(d) Math.log(d) * 138.974)</pre>
  3274. *
  3275. * is equivalent to
  3276. *
  3277. * <pre> .height(pv.Scale.log(1, 100).range(0, 640))</pre>
  3278. *
  3279. * Note that the scale is itself a function, and thus can be used as a property
  3280. * directly, assuming that the data associated with a mark is a number. While
  3281. * this is convenient for single-use scales, frequently it is desirable to
  3282. * define scales globally:
  3283. *
  3284. * <pre>var y = pv.Scale.log(1, 100).range(0, 640);</pre>
  3285. *
  3286. * The <tt>y</tt> scale can now be equivalently referenced within a property:
  3287. *
  3288. * <pre> .height(function(d) y(d))</pre>
  3289. *
  3290. * Alternatively, if the data are not simple numbers, the appropriate value can
  3291. * be passed to the <tt>y</tt> scale (e.g., <tt>d.foo</tt>). The {@link #by}
  3292. * method similarly allows the data to be mapped to a numeric value before
  3293. * performing the log transformation.
  3294. *
  3295. * @param {number...} domain... optional domain values.
  3296. * @extends pv.Scale.quantitative
  3297. */
  3298. pv.Scale.log = function() {
  3299. var scale = pv.Scale.quantitative(1, 10),
  3300. b, // logarithm base
  3301. p, // cached Math.log(b)
  3302. /** @ignore */ log = function(x) { return Math.log(x) / p; },
  3303. /** @ignore */ pow = function(y) { return Math.pow(b, y); };
  3304. /**
  3305. * Returns an array of evenly-spaced, suitably-rounded values in the input
  3306. * domain. These values are frequently used in conjunction with
  3307. * {@link pv.Rule} to display tick marks or grid lines.
  3308. *
  3309. * @function
  3310. * @name pv.Scale.log.prototype.ticks
  3311. * @returns {number[]} an array input domain values to use as ticks.
  3312. */
  3313. scale.ticks = function() {
  3314. // TODO support non-uniform domains
  3315. var d = scale.domain(),
  3316. n = d[0] < 0,
  3317. i = Math.floor(n ? -log(-d[0]) : log(d[0])),
  3318. j = Math.ceil(n ? -log(-d[1]) : log(d[1])),
  3319. ticks = [];
  3320. if (n) {
  3321. ticks.push(-pow(-i));
  3322. for (; i++ < j;) for (var k = b - 1; k > 0; k--) ticks.push(-pow(-i) * k);
  3323. } else {
  3324. for (; i < j; i++) for (var k = 1; k < b; k++) ticks.push(pow(i) * k);
  3325. ticks.push(pow(i));
  3326. }
  3327. for (i = 0; ticks[i] < d[0]; i++); // strip small values
  3328. for (j = ticks.length; ticks[j - 1] > d[1]; j--); // strip big values
  3329. return ticks.slice(i, j);
  3330. };
  3331. /**
  3332. * Formats the specified tick value using the appropriate precision, assuming
  3333. * base 10.
  3334. *
  3335. * @function
  3336. * @name pv.Scale.log.prototype.tickFormat
  3337. * @param {number} t a tick value.
  3338. * @returns {string} a formatted tick value.
  3339. */
  3340. scale.tickFormat = function(t) {
  3341. return t.toPrecision(1);
  3342. };
  3343. /**
  3344. * "Nices" this scale, extending the bounds of the input domain to
  3345. * evenly-rounded values. This method uses {@link pv.logFloor} and
  3346. * {@link pv.logCeil}. Nicing is useful if the domain is computed dynamically
  3347. * from data, and may be irregular. For example, given a domain of
  3348. * [0.20147987687960267, 0.996679553296417], a call to <tt>nice()</tt> might
  3349. * extend the domain to [0.1, 1].
  3350. *
  3351. * <p>This method must be invoked each time after setting the domain (and
  3352. * base).
  3353. *
  3354. * @function
  3355. * @name pv.Scale.log.prototype.nice
  3356. * @returns {pv.Scale.log} <tt>this</tt>.
  3357. */
  3358. scale.nice = function() {
  3359. // TODO support non-uniform domains
  3360. var d = scale.domain();
  3361. return scale.domain(pv.logFloor(d[0], b), pv.logCeil(d[1], b));
  3362. };
  3363. /**
  3364. * Sets or gets the logarithm base. Defaults to 10.
  3365. *
  3366. * @function
  3367. * @name pv.Scale.log.prototype.base
  3368. * @param {number} [v] the new base.
  3369. * @returns {pv.Scale.log} <tt>this</tt>, or the current base.
  3370. */
  3371. scale.base = function(v) {
  3372. if (arguments.length) {
  3373. b = Number(v);
  3374. p = Math.log(b);
  3375. scale.transform(log, pow); // update transformed domain
  3376. return this;
  3377. }
  3378. return b;
  3379. };
  3380. scale.domain.apply(scale, arguments);
  3381. return scale.base(10);
  3382. };
  3383. /**
  3384. * Returns a root scale for the specified domain. The arguments to this
  3385. * constructor are optional, and equivalent to calling {@link #domain}.
  3386. * The default domain and range are [0,1].
  3387. *
  3388. * @class Represents a root scale; a function that performs a power
  3389. * transformation. <style type="text/css">sub{line-height:0}</style> Most
  3390. * commonly, a root scale represents a 1-dimensional root transformation from a
  3391. * numeric domain of input data [<i>d<sub>0</sub></i>, <i>d<sub>1</sub></i>] to
  3392. * a numeric range of pixels [<i>r<sub>0</sub></i>, <i>r<sub>1</sub></i>].
  3393. *
  3394. * <p>Note that the scale is itself a function, and thus can be used as a
  3395. * property directly, assuming that the data associated with a mark is a
  3396. * number. While this is convenient for single-use scales, frequently it is
  3397. * desirable to define scales globally:
  3398. *
  3399. * <pre>var y = pv.Scale.root(0, 100).range(0, 640);</pre>
  3400. *
  3401. * The <tt>y</tt> scale can now be equivalently referenced within a property:
  3402. *
  3403. * <pre> .height(function(d) y(d))</pre>
  3404. *
  3405. * Alternatively, if the data are not simple numbers, the appropriate value can
  3406. * be passed to the <tt>y</tt> scale (e.g., <tt>d.foo</tt>). The {@link #by}
  3407. * method similarly allows the data to be mapped to a numeric value before
  3408. * performing the root transformation.
  3409. *
  3410. * @param {number...} domain... optional domain values.
  3411. * @extends pv.Scale.quantitative
  3412. */
  3413. pv.Scale.root = function() {
  3414. var scale = pv.Scale.quantitative();
  3415. /**
  3416. * Sets or gets the exponent; defaults to 2.
  3417. *
  3418. * @function
  3419. * @name pv.Scale.root.prototype.power
  3420. * @param {number} [v] the new exponent.
  3421. * @returns {pv.Scale.root} <tt>this</tt>, or the current base.
  3422. */
  3423. scale.power = function(v) {
  3424. if (arguments.length) {
  3425. var b = Number(v), p = 1 / b;
  3426. scale.transform(
  3427. function(x) { return Math.pow(x, p); },
  3428. function(y) { return Math.pow(y, b); });
  3429. return this;
  3430. }
  3431. return b;
  3432. };
  3433. scale.domain.apply(scale, arguments);
  3434. return scale.power(2);
  3435. };
  3436. /**
  3437. * Returns an ordinal scale for the specified domain. The arguments to this
  3438. * constructor are optional, and equivalent to calling {@link #domain}.
  3439. *
  3440. * @class Represents an ordinal scale. <style
  3441. * type="text/css">sub{line-height:0}</style> An ordinal scale represents a
  3442. * pairwise mapping from <i>n</i> discrete values in the input domain to
  3443. * <i>n</i> discrete values in the output range. For example, an ordinal scale
  3444. * might map a domain of species ["setosa", "versicolor", "virginica"] to colors
  3445. * ["red", "green", "blue"]. Thus, saying
  3446. *
  3447. * <pre> .fillStyle(function(d) {
  3448. * switch (d.species) {
  3449. * case "setosa": return "red";
  3450. * case "versicolor": return "green";
  3451. * case "virginica": return "blue";
  3452. * }
  3453. * })</pre>
  3454. *
  3455. * is equivalent to
  3456. *
  3457. * <pre> .fillStyle(pv.Scale.ordinal("setosa", "versicolor", "virginica")
  3458. * .range("red", "green", "blue")
  3459. * .by(function(d) d.species))</pre>
  3460. *
  3461. * If the mapping from species to color does not need to be specified
  3462. * explicitly, the domain can be omitted. In this case it will be inferred
  3463. * lazily from the data:
  3464. *
  3465. * <pre> .fillStyle(pv.colors("red", "green", "blue")
  3466. * .by(function(d) d.species))</pre>
  3467. *
  3468. * When the domain is inferred, the first time the scale is invoked, the first
  3469. * element from the range will be returned. Subsequent calls with unique values
  3470. * will return subsequent elements from the range. If the inferred domain grows
  3471. * larger than the range, range values will be reused. However, it is strongly
  3472. * recommended that the domain and the range contain the same number of
  3473. * elements.
  3474. *
  3475. * <p>A range can be discretized from a continuous interval (e.g., for pixel
  3476. * positioning) by using {@link #split}, {@link #splitFlush} or
  3477. * {@link #splitBanded} after the domain has been set. For example, if
  3478. * <tt>states</tt> is an array of the fifty U.S. state names, the state name can
  3479. * be encoded in the left position:
  3480. *
  3481. * <pre> .left(pv.Scale.ordinal(states)
  3482. * .split(0, 640)
  3483. * .by(function(d) d.state))</pre>
  3484. *
  3485. * <p>N.B.: ordinal scales are not invertible (at least not yet), since the
  3486. * domain and range and discontinuous. A workaround is to use a linear scale.
  3487. *
  3488. * @param {...} domain... optional domain values.
  3489. * @extends pv.Scale
  3490. * @see pv.colors
  3491. */
  3492. pv.Scale.ordinal = function() {
  3493. var d = [], i = {}, r = [], band = 0;
  3494. /** @private */
  3495. function scale(x) {
  3496. if (!(x in i)) i[x] = d.push(x) - 1;
  3497. return r[i[x] % r.length];
  3498. }
  3499. /**
  3500. * Sets or gets the input domain. This method can be invoked several ways:
  3501. *
  3502. * <p>1. <tt>domain(values...)</tt>
  3503. *
  3504. * <p>Specifying the domain as a series of values is the most explicit and
  3505. * recommended approach. However, if the domain values are derived from data,
  3506. * you may find the second method more appropriate.
  3507. *
  3508. * <p>2. <tt>domain(array, f)</tt>
  3509. *
  3510. * <p>Rather than enumerating the domain values as explicit arguments to this
  3511. * method, you can specify a single argument of an array. In addition, you can
  3512. * specify an optional accessor function to extract the domain values from the
  3513. * array.
  3514. *
  3515. * <p>3. <tt>domain()</tt>
  3516. *
  3517. * <p>Invoking the <tt>domain</tt> method with no arguments returns the
  3518. * current domain as an array.
  3519. *
  3520. * @function
  3521. * @name pv.Scale.ordinal.prototype.domain
  3522. * @param {...} domain... domain values.
  3523. * @returns {pv.Scale.ordinal} <tt>this</tt>, or the current domain.
  3524. */
  3525. scale.domain = function(array, f) {
  3526. if (arguments.length) {
  3527. array = (array instanceof Array)
  3528. ? ((arguments.length > 1) ? pv.map(array, f) : array)
  3529. : Array.prototype.slice.call(arguments);
  3530. /* Filter the specified ordinals to their unique values. */
  3531. d = [];
  3532. var seen = {};
  3533. for (var j = 0; j < array.length; j++) {
  3534. var o = array[j];
  3535. if (!(o in seen)) {
  3536. seen[o] = true;
  3537. d.push(o);
  3538. }
  3539. }
  3540. i = pv.numerate(d);
  3541. return this;
  3542. }
  3543. return d;
  3544. };
  3545. /**
  3546. * Sets or gets the output range. This method can be invoked several ways:
  3547. *
  3548. * <p>1. <tt>range(values...)</tt>
  3549. *
  3550. * <p>Specifying the range as a series of values is the most explicit and
  3551. * recommended approach. However, if the range values are derived from data,
  3552. * you may find the second method more appropriate.
  3553. *
  3554. * <p>2. <tt>range(array, f)</tt>
  3555. *
  3556. * <p>Rather than enumerating the range values as explicit arguments to this
  3557. * method, you can specify a single argument of an array. In addition, you can
  3558. * specify an optional accessor function to extract the range values from the
  3559. * array.
  3560. *
  3561. * <p>3. <tt>range()</tt>
  3562. *
  3563. * <p>Invoking the <tt>range</tt> method with no arguments returns the
  3564. * current range as an array.
  3565. *
  3566. * @function
  3567. * @name pv.Scale.ordinal.prototype.range
  3568. * @param {...} range... range values.
  3569. * @returns {pv.Scale.ordinal} <tt>this</tt>, or the current range.
  3570. */
  3571. scale.range = function(array, f) {
  3572. if (arguments.length) {
  3573. r = (array instanceof Array)
  3574. ? ((arguments.length > 1) ? pv.map(array, f) : array)
  3575. : Array.prototype.slice.call(arguments);
  3576. if (typeof r[0] == "string") r = r.map(pv.color);
  3577. return this;
  3578. }
  3579. return r;
  3580. };
  3581. /**
  3582. * Sets the range from the given continuous interval. The interval
  3583. * [<i>min</i>, <i>max</i>] is subdivided into <i>n</i> equispaced points,
  3584. * where <i>n</i> is the number of (unique) values in the domain. The first
  3585. * and last point are offset from the edge of the range by half the distance
  3586. * between points.
  3587. *
  3588. * <p>This method must be called <i>after</i> the domain is set.
  3589. *
  3590. * @function
  3591. * @name pv.Scale.ordinal.prototype.split
  3592. * @param {number} min minimum value of the output range.
  3593. * @param {number} max maximum value of the output range.
  3594. * @returns {pv.Scale.ordinal} <tt>this</tt>.
  3595. * @see #splitFlush
  3596. * @see #splitBanded
  3597. */
  3598. scale.split = function(min, max) {
  3599. var step = (max - min) / this.domain().length;
  3600. r = pv.range(min + step / 2, max, step);
  3601. return this;
  3602. };
  3603. /**
  3604. * Sets the range from the given continuous interval. The interval
  3605. * [<i>min</i>, <i>max</i>] is subdivided into <i>n</i> equispaced points,
  3606. * where <i>n</i> is the number of (unique) values in the domain. The first
  3607. * and last point are exactly on the edge of the range.
  3608. *
  3609. * <p>This method must be called <i>after</i> the domain is set.
  3610. *
  3611. * @function
  3612. * @name pv.Scale.ordinal.prototype.splitFlush
  3613. * @param {number} min minimum value of the output range.
  3614. * @param {number} max maximum value of the output range.
  3615. * @returns {pv.Scale.ordinal} <tt>this</tt>.
  3616. * @see #split
  3617. */
  3618. scale.splitFlush = function(min, max) {
  3619. var n = this.domain().length, step = (max - min) / (n - 1);
  3620. r = (n == 1) ? [(min + max) / 2]
  3621. : pv.range(min, max + step / 2, step);
  3622. return this;
  3623. };
  3624. /**
  3625. * Sets the range from the given continuous interval. The interval
  3626. * [<i>min</i>, <i>max</i>] is subdivided into <i>n</i> equispaced bands,
  3627. * where <i>n</i> is the number of (unique) values in the domain. The first
  3628. * and last band are offset from the edge of the range by the distance between
  3629. * bands.
  3630. *
  3631. * <p>The band width argument, <tt>band</tt>, is typically in the range [0, 1]
  3632. * and defaults to 1. This fraction corresponds to the amount of space in the
  3633. * range to allocate to the bands, as opposed to padding. A value of 0.5 means
  3634. * that the band width will be equal to the padding width. The computed
  3635. * absolute band width can be retrieved from the range as
  3636. * <tt>scale.range().band</tt>.
  3637. *
  3638. * <p>If the band width argument is negative, this method will allocate bands
  3639. * of a <i>fixed</i> width <tt>-band</tt>, rather than a relative fraction of
  3640. * the available space.
  3641. *
  3642. * <p>Tip: to inset the bands by a fixed amount <tt>p</tt>, specify a minimum
  3643. * value of <tt>min + p</tt> (or simply <tt>p</tt>, if <tt>min</tt> is
  3644. * 0). Then set the mark width to <tt>scale.range().band - p</tt>.
  3645. *
  3646. * <p>This method must be called <i>after</i> the domain is set.
  3647. *
  3648. * @function
  3649. * @name pv.Scale.ordinal.prototype.splitBanded
  3650. * @param {number} min minimum value of the output range.
  3651. * @param {number} max maximum value of the output range.
  3652. * @param {number} [band] the fractional band width in [0, 1]; defaults to 1.
  3653. * @returns {pv.Scale.ordinal} <tt>this</tt>.
  3654. * @see #split
  3655. */
  3656. scale.splitBanded = function(min, max, band) {
  3657. if (arguments.length < 3) band = 1;
  3658. if (band < 0) {
  3659. var n = this.domain().length,
  3660. total = -band * n,
  3661. remaining = max - min - total,
  3662. padding = remaining / (n + 1);
  3663. r = pv.range(min + padding, max, padding - band);
  3664. r.band = -band;
  3665. } else {
  3666. var step = (max - min) / (this.domain().length + (1 - band));
  3667. r = pv.range(min + step * (1 - band), max, step);
  3668. r.band = step * band;
  3669. }
  3670. return this;
  3671. };
  3672. /**
  3673. * Returns a view of this scale by the specified accessor function <tt>f</tt>.
  3674. * Given a scale <tt>y</tt>, <tt>y.by(function(d) d.foo)</tt> is equivalent to
  3675. * <tt>function(d) y(d.foo)</tt>. This method should be used judiciously; it
  3676. * is typically more clear to invoke the scale directly, passing in the value
  3677. * to be scaled.
  3678. *
  3679. * @function
  3680. * @name pv.Scale.ordinal.prototype.by
  3681. * @param {function} f an accessor function.
  3682. * @returns {pv.Scale.ordinal} a view of this scale by the specified accessor
  3683. * function.
  3684. */
  3685. scale.by = function(f) {
  3686. function by() { return scale(f.apply(this, arguments)); }
  3687. for (var method in scale) by[method] = scale[method];
  3688. return by;
  3689. };
  3690. scale.domain.apply(scale, arguments);
  3691. return scale;
  3692. };
  3693. /**
  3694. * Constructs a default quantile scale. The arguments to this constructor are
  3695. * optional, and equivalent to calling {@link #domain}. The default domain is
  3696. * the empty set, and the default range is [0,1].
  3697. *
  3698. * @class Represents a quantile scale; a function that maps from a value within
  3699. * a sortable domain to a quantized numeric range. Typically, the domain is a
  3700. * set of numbers, but any sortable value (such as strings) can be used as the
  3701. * domain of a quantile scale. The range defaults to [0,1], with 0 corresponding
  3702. * to the smallest value in the domain, 1 the largest, .5 the median, etc.
  3703. *
  3704. * <p>By default, the number of quantiles in the range corresponds to the number
  3705. * of values in the domain. The {@link #quantiles} method can be used to specify
  3706. * an explicit number of quantiles; for example, <tt>quantiles(4)</tt> produces
  3707. * a standard quartile scale. A quartile scale's range is a set of four discrete
  3708. * values, such as [0, 1/3, 2/3, 1]. Calling the {@link #range} method will
  3709. * scale these discrete values accordingly, similar to {@link
  3710. * pv.Scale.ordinal#splitFlush}.
  3711. *
  3712. * <p>For example, given the strings ["c", "a", "b"], a default quantile scale:
  3713. *
  3714. * <pre>pv.Scale.quantile("c", "a", "b")</pre>
  3715. *
  3716. * will return 0 for "a", .5 for "b", and 1 for "c".
  3717. *
  3718. * @extends pv.Scale
  3719. */
  3720. pv.Scale.quantile = function() {
  3721. var n = -1, // number of quantiles
  3722. j = -1, // max quantile index
  3723. q = [], // quantile boundaries
  3724. d = [], // domain
  3725. y = pv.Scale.linear(); // range
  3726. /** @private */
  3727. function scale(x) {
  3728. return y(Math.max(0, Math.min(j, pv.search.index(q, x) - 1)) / j);
  3729. }
  3730. /**
  3731. * Sets or gets the quantile boundaries. By default, each element in the
  3732. * domain is in its own quantile. If the argument to this method is a number,
  3733. * it specifies the number of equal-sized quantiles by which to divide the
  3734. * domain.
  3735. *
  3736. * <p>If no arguments are specified, this method returns the quantile
  3737. * boundaries; the first element is always the minimum value of the domain,
  3738. * and the last element is the maximum value of the domain. Thus, the length
  3739. * of the returned array is always one greater than the number of quantiles.
  3740. *
  3741. * @function
  3742. * @name pv.Scale.quantile.prototype.quantiles
  3743. * @param {number} x the number of quantiles.
  3744. */
  3745. scale.quantiles = function(x) {
  3746. if (arguments.length) {
  3747. n = Number(x);
  3748. if (n < 0) {
  3749. q = [d[0]].concat(d);
  3750. j = d.length - 1;
  3751. } else {
  3752. q = [];
  3753. q[0] = d[0];
  3754. for (var i = 1; i <= n; i++) {
  3755. q[i] = d[~~(i * (d.length - 1) / n)];
  3756. }
  3757. j = n - 1;
  3758. }
  3759. return this;
  3760. }
  3761. return q;
  3762. };
  3763. /**
  3764. * Sets or gets the input domain. This method can be invoked several ways:
  3765. *
  3766. * <p>1. <tt>domain(values...)</tt>
  3767. *
  3768. * <p>Specifying the domain as a series of values is the most explicit and
  3769. * recommended approach. However, if the domain values are derived from data,
  3770. * you may find the second method more appropriate.
  3771. *
  3772. * <p>2. <tt>domain(array, f)</tt>
  3773. *
  3774. * <p>Rather than enumerating the domain values as explicit arguments to this
  3775. * method, you can specify a single argument of an array. In addition, you can
  3776. * specify an optional accessor function to extract the domain values from the
  3777. * array.
  3778. *
  3779. * <p>3. <tt>domain()</tt>
  3780. *
  3781. * <p>Invoking the <tt>domain</tt> method with no arguments returns the
  3782. * current domain as an array.
  3783. *
  3784. * @function
  3785. * @name pv.Scale.quantile.prototype.domain
  3786. * @param {...} domain... domain values.
  3787. * @returns {pv.Scale.quantile} <tt>this</tt>, or the current domain.
  3788. */
  3789. scale.domain = function(array, f) {
  3790. if (arguments.length) {
  3791. d = (array instanceof Array)
  3792. ? pv.map(array, f)
  3793. : Array.prototype.slice.call(arguments);
  3794. d.sort(pv.naturalOrder);
  3795. scale.quantiles(n); // recompute quantiles
  3796. return this;
  3797. }
  3798. return d;
  3799. };
  3800. /**
  3801. * Sets or gets the output range. This method can be invoked several ways:
  3802. *
  3803. * <p>1. <tt>range(min, ..., max)</tt>
  3804. *
  3805. * <p>The range may be specified as a series of numbers or colors. Most
  3806. * commonly, two numbers are specified: the minimum and maximum pixel values.
  3807. * For a color scale, values may be specified as {@link pv.Color}s or
  3808. * equivalent strings. For a diverging scale, or other subdivided non-uniform
  3809. * scales, multiple values can be specified. For example:
  3810. *
  3811. * <pre> .range("red", "white", "green")</pre>
  3812. *
  3813. * <p>Currently, only numbers and colors are supported as range values. The
  3814. * number of range values must exactly match the number of domain values, or
  3815. * the behavior of the scale is undefined.
  3816. *
  3817. * <p>2. <tt>range()</tt>
  3818. *
  3819. * <p>Invoking the <tt>range</tt> method with no arguments returns the current
  3820. * range as an array of numbers or colors.
  3821. *
  3822. * @function
  3823. * @name pv.Scale.quantile.prototype.range
  3824. * @param {...} range... range values.
  3825. * @returns {pv.Scale.quantile} <tt>this</tt>, or the current range.
  3826. */
  3827. scale.range = function() {
  3828. if (arguments.length) {
  3829. y.range.apply(y, arguments);
  3830. return this;
  3831. }
  3832. return y.range();
  3833. };
  3834. /**
  3835. * Returns a view of this scale by the specified accessor function <tt>f</tt>.
  3836. * Given a scale <tt>y</tt>, <tt>y.by(function(d) d.foo)</tt> is equivalent to
  3837. * <tt>function(d) y(d.foo)</tt>.
  3838. *
  3839. * <p>This method is provided for convenience, such that scales can be
  3840. * succinctly defined inline. For example, given an array of data elements
  3841. * that have a <tt>score</tt> attribute with the domain [0, 1], the height
  3842. * property could be specified as:
  3843. *
  3844. * <pre>.height(pv.Scale.linear().range(0, 480).by(function(d) d.score))</pre>
  3845. *
  3846. * This is equivalent to:
  3847. *
  3848. * <pre>.height(function(d) d.score * 480)</pre>
  3849. *
  3850. * This method should be used judiciously; it is typically more clear to
  3851. * invoke the scale directly, passing in the value to be scaled.
  3852. *
  3853. * @function
  3854. * @name pv.Scale.quantile.prototype.by
  3855. * @param {function} f an accessor function.
  3856. * @returns {pv.Scale.quantile} a view of this scale by the specified
  3857. * accessor function.
  3858. */
  3859. scale.by = function(f) {
  3860. function by() { return scale(f.apply(this, arguments)); }
  3861. for (var method in scale) by[method] = scale[method];
  3862. return by;
  3863. };
  3864. scale.domain.apply(scale, arguments);
  3865. return scale;
  3866. };
  3867. /**
  3868. * Returns a histogram operator for the specified data, with an optional
  3869. * accessor function. If the data specified is not an array of numbers, an
  3870. * accessor function must be specified to map the data to numeric values.
  3871. *
  3872. * @class Represents a histogram operator.
  3873. *
  3874. * @param {array} data an array of numbers or objects.
  3875. * @param {function} [f] an optional accessor function.
  3876. */
  3877. pv.histogram = function(data, f) {
  3878. var frequency = true;
  3879. return {
  3880. /**
  3881. * Returns the computed histogram bins. An optional array of numbers,
  3882. * <tt>ticks</tt>, may be specified as the break points. If the ticks are
  3883. * not specified, default ticks will be computed using a linear scale on the
  3884. * data domain.
  3885. *
  3886. * <p>The returned array contains {@link pv.histogram.Bin}s. The <tt>x</tt>
  3887. * attribute corresponds to the bin's start value (inclusive), while the
  3888. * <tt>dx</tt> attribute stores the bin size (end - start). The <tt>y</tt>
  3889. * attribute stores either the frequency count or probability, depending on
  3890. * how the histogram operator has been configured.
  3891. *
  3892. * <p>The {@link pv.histogram.Bin} objects are themselves arrays, containing
  3893. * the data elements present in each bin, i.e., the elements in the
  3894. * <tt>data</tt> array (prior to invoking the accessor function, if any).
  3895. * For example, if the data represented countries, and the accessor function
  3896. * returned the GDP of each country, the returned bins would be arrays of
  3897. * countries (not GDPs).
  3898. *
  3899. * @function
  3900. * @name pv.histogram.prototype.bins
  3901. * @param {array} [ticks]
  3902. * @returns {array}
  3903. */ /** @private */
  3904. bins: function(ticks) {
  3905. var x = pv.map(data, f), bins = [];
  3906. /* Initialize default ticks. */
  3907. if (!arguments.length) ticks = pv.Scale.linear(x).ticks();
  3908. /* Initialize the bins. */
  3909. for (var i = 0; i < ticks.length - 1; i++) {
  3910. var bin = bins[i] = [];
  3911. bin.x = ticks[i];
  3912. bin.dx = ticks[i + 1] - ticks[i];
  3913. bin.y = 0;
  3914. }
  3915. /* Count the number of samples per bin. */
  3916. for (var i = 0; i < x.length; i++) {
  3917. var j = pv.search.index(ticks, x[i]) - 1,
  3918. bin = bins[Math.max(0, Math.min(bins.length - 1, j))];
  3919. bin.y++;
  3920. bin.push(data[i]);
  3921. }
  3922. /* Convert frequencies to probabilities. */
  3923. if (!frequency) for (var i = 0; i < bins.length; i++) {
  3924. bins[i].y /= x.length;
  3925. }
  3926. return bins;
  3927. },
  3928. /**
  3929. * Sets or gets whether this histogram operator returns frequencies or
  3930. * probabilities.
  3931. *
  3932. * @function
  3933. * @name pv.histogram.prototype.frequency
  3934. * @param {boolean} [x]
  3935. * @returns {pv.histogram} this.
  3936. */ /** @private */
  3937. frequency: function(x) {
  3938. if (arguments.length) {
  3939. frequency = Boolean(x);
  3940. return this;
  3941. }
  3942. return frequency;
  3943. }
  3944. };
  3945. };
  3946. /**
  3947. * @class Represents a bin returned by the {@link pv.histogram} operator. Bins
  3948. * are themselves arrays containing the data elements present in the given bin
  3949. * (prior to the accessor function being invoked to convert the data object to a
  3950. * numeric value). These bin arrays have additional attributes with meta
  3951. * information about the bin.
  3952. *
  3953. * @name pv.histogram.Bin
  3954. * @extends array
  3955. * @see pv.histogram
  3956. */
  3957. /**
  3958. * The start value of the bin's range.
  3959. *
  3960. * @type number
  3961. * @name pv.histogram.Bin.prototype.x
  3962. */
  3963. /**
  3964. * The magnitude value of the bin's range; end - start.
  3965. *
  3966. * @type number
  3967. * @name pv.histogram.Bin.prototype.dx
  3968. */
  3969. /**
  3970. * The frequency or probability of the bin, depending on how the histogram
  3971. * operator was configured.
  3972. *
  3973. * @type number
  3974. * @name pv.histogram.Bin.prototype.y
  3975. */
  3976. /**
  3977. * Returns the {@link pv.Color} for the specified color format string. Colors
  3978. * may have an associated opacity, or alpha channel. Color formats are specified
  3979. * by CSS Color Modular Level 3, using either in RGB or HSL color space. For
  3980. * example:<ul>
  3981. *
  3982. * <li>#f00 // #rgb
  3983. * <li>#ff0000 // #rrggbb
  3984. * <li>rgb(255, 0, 0)
  3985. * <li>rgb(100%, 0%, 0%)
  3986. * <li>hsl(0, 100%, 50%)
  3987. * <li>rgba(0, 0, 255, 0.5)
  3988. * <li>hsla(120, 100%, 50%, 1)
  3989. *
  3990. * </ul>The SVG 1.0 color keywords names are also supported, such as "aliceblue"
  3991. * and "yellowgreen". The "transparent" keyword is supported for fully-
  3992. * transparent black.
  3993. *
  3994. * <p>If the <tt>format</tt> argument is already an instance of <tt>Color</tt>,
  3995. * the argument is returned with no further processing.
  3996. *
  3997. * @param {string} format the color specification string, such as "#f00".
  3998. * @returns {pv.Color} the corresponding <tt>Color</tt>.
  3999. * @see <a href="http://www.w3.org/TR/SVG/types.html#ColorKeywords">SVG color
  4000. * keywords</a>
  4001. * @see <a href="http://www.w3.org/TR/css3-color/">CSS3 color module</a>
  4002. */
  4003. pv.color = function(format) {
  4004. if (format.rgb) return format.rgb();
  4005. /* Handle hsl, rgb. */
  4006. var m1 = /([a-z]+)\((.*)\)/i.exec(format);
  4007. if (m1) {
  4008. var m2 = m1[2].split(","), a = 1;
  4009. switch (m1[1]) {
  4010. case "hsla":
  4011. case "rgba": {
  4012. a = parseFloat(m2[3]);
  4013. if (!a) return pv.Color.transparent;
  4014. break;
  4015. }
  4016. }
  4017. switch (m1[1]) {
  4018. case "hsla":
  4019. case "hsl": {
  4020. var h = parseFloat(m2[0]), // degrees
  4021. s = parseFloat(m2[1]) / 100, // percentage
  4022. l = parseFloat(m2[2]) / 100; // percentage
  4023. return (new pv.Color.Hsl(h, s, l, a)).rgb();
  4024. }
  4025. case "rgba":
  4026. case "rgb": {
  4027. function parse(c) { // either integer or percentage
  4028. var f = parseFloat(c);
  4029. return (c[c.length - 1] == '%') ? Math.round(f * 2.55) : f;
  4030. }
  4031. var r = parse(m2[0]), g = parse(m2[1]), b = parse(m2[2]);
  4032. return pv.rgb(r, g, b, a);
  4033. }
  4034. }
  4035. }
  4036. /* Named colors. */
  4037. var named = pv.Color.names[format];
  4038. if (named) return named;
  4039. /* Hexadecimal colors: #rgb and #rrggbb. */
  4040. if (format.charAt(0) == "#") {
  4041. var r, g, b;
  4042. if (format.length == 4) {
  4043. r = format.charAt(1); r += r;
  4044. g = format.charAt(2); g += g;
  4045. b = format.charAt(3); b += b;
  4046. } else if (format.length == 7) {
  4047. r = format.substring(1, 3);
  4048. g = format.substring(3, 5);
  4049. b = format.substring(5, 7);
  4050. }
  4051. return pv.rgb(parseInt(r, 16), parseInt(g, 16), parseInt(b, 16), 1);
  4052. }
  4053. /* Otherwise, pass-through unsupported colors. */
  4054. return new pv.Color(format, 1);
  4055. };
  4056. /**
  4057. * Constructs a color with the specified color format string and opacity. This
  4058. * constructor should not be invoked directly; use {@link pv.color} instead.
  4059. *
  4060. * @class Represents an abstract (possibly translucent) color. The color is
  4061. * divided into two parts: the <tt>color</tt> attribute, an opaque color format
  4062. * string, and the <tt>opacity</tt> attribute, a float in [0, 1]. The color
  4063. * space is dependent on the implementing class; all colors support the
  4064. * {@link #rgb} method to convert to RGB color space for interpolation.
  4065. *
  4066. * <p>See also the <a href="../../api/Color.html">Color guide</a>.
  4067. *
  4068. * @param {string} color an opaque color format string, such as "#f00".
  4069. * @param {number} opacity the opacity, in [0,1].
  4070. * @see pv.color
  4071. */
  4072. pv.Color = function(color, opacity) {
  4073. /**
  4074. * An opaque color format string, such as "#f00".
  4075. *
  4076. * @type string
  4077. * @see <a href="http://www.w3.org/TR/SVG/types.html#ColorKeywords">SVG color
  4078. * keywords</a>
  4079. * @see <a href="http://www.w3.org/TR/css3-color/">CSS3 color module</a>
  4080. */
  4081. this.color = color;
  4082. /**
  4083. * The opacity, a float in [0, 1].
  4084. *
  4085. * @type number
  4086. */
  4087. this.opacity = opacity;
  4088. };
  4089. /**
  4090. * Returns a new color that is a brighter version of this color. The behavior of
  4091. * this method may vary slightly depending on the underlying color space.
  4092. * Although brighter and darker are inverse operations, the results of a series
  4093. * of invocations of these two methods might be inconsistent because of rounding
  4094. * errors.
  4095. *
  4096. * @param [k] {number} an optional scale factor; defaults to 1.
  4097. * @see #darker
  4098. * @returns {pv.Color} a brighter color.
  4099. */
  4100. pv.Color.prototype.brighter = function(k) {
  4101. return this.rgb().brighter(k);
  4102. };
  4103. /**
  4104. * Returns a new color that is a brighter version of this color. The behavior of
  4105. * this method may vary slightly depending on the underlying color space.
  4106. * Although brighter and darker are inverse operations, the results of a series
  4107. * of invocations of these two methods might be inconsistent because of rounding
  4108. * errors.
  4109. *
  4110. * @param [k] {number} an optional scale factor; defaults to 1.
  4111. * @see #brighter
  4112. * @returns {pv.Color} a darker color.
  4113. */
  4114. pv.Color.prototype.darker = function(k) {
  4115. return this.rgb().darker(k);
  4116. };
  4117. /**
  4118. * Constructs a new RGB color with the specified channel values.
  4119. *
  4120. * @param {number} r the red channel, an integer in [0,255].
  4121. * @param {number} g the green channel, an integer in [0,255].
  4122. * @param {number} b the blue channel, an integer in [0,255].
  4123. * @param {number} [a] the alpha channel, a float in [0,1].
  4124. * @returns pv.Color.Rgb
  4125. */
  4126. pv.rgb = function(r, g, b, a) {
  4127. return new pv.Color.Rgb(r, g, b, (arguments.length == 4) ? a : 1);
  4128. };
  4129. /**
  4130. * Constructs a new RGB color with the specified channel values.
  4131. *
  4132. * @class Represents a color in RGB space.
  4133. *
  4134. * @param {number} r the red channel, an integer in [0,255].
  4135. * @param {number} g the green channel, an integer in [0,255].
  4136. * @param {number} b the blue channel, an integer in [0,255].
  4137. * @param {number} a the alpha channel, a float in [0,1].
  4138. * @extends pv.Color
  4139. */
  4140. pv.Color.Rgb = function(r, g, b, a) {
  4141. pv.Color.call(this, a ? ("rgb(" + r + "," + g + "," + b + ")") : "none", a);
  4142. /**
  4143. * The red channel, an integer in [0, 255].
  4144. *
  4145. * @type number
  4146. */
  4147. this.r = r;
  4148. /**
  4149. * The green channel, an integer in [0, 255].
  4150. *
  4151. * @type number
  4152. */
  4153. this.g = g;
  4154. /**
  4155. * The blue channel, an integer in [0, 255].
  4156. *
  4157. * @type number
  4158. */
  4159. this.b = b;
  4160. /**
  4161. * The alpha channel, a float in [0, 1].
  4162. *
  4163. * @type number
  4164. */
  4165. this.a = a;
  4166. };
  4167. pv.Color.Rgb.prototype = pv.extend(pv.Color);
  4168. /**
  4169. * Constructs a new RGB color with the same green, blue and alpha channels as
  4170. * this color, with the specified red channel.
  4171. *
  4172. * @param {number} r the red channel, an integer in [0,255].
  4173. */
  4174. pv.Color.Rgb.prototype.red = function(r) {
  4175. return pv.rgb(r, this.g, this.b, this.a);
  4176. };
  4177. /**
  4178. * Constructs a new RGB color with the same red, blue and alpha channels as this
  4179. * color, with the specified green channel.
  4180. *
  4181. * @param {number} g the green channel, an integer in [0,255].
  4182. */
  4183. pv.Color.Rgb.prototype.green = function(g) {
  4184. return pv.rgb(this.r, g, this.b, this.a);
  4185. };
  4186. /**
  4187. * Constructs a new RGB color with the same red, green and alpha channels as
  4188. * this color, with the specified blue channel.
  4189. *
  4190. * @param {number} b the blue channel, an integer in [0,255].
  4191. */
  4192. pv.Color.Rgb.prototype.blue = function(b) {
  4193. return pv.rgb(this.r, this.g, b, this.a);
  4194. };
  4195. /**
  4196. * Constructs a new RGB color with the same red, green and blue channels as this
  4197. * color, with the specified alpha channel.
  4198. *
  4199. * @param {number} a the alpha channel, a float in [0,1].
  4200. */
  4201. pv.Color.Rgb.prototype.alpha = function(a) {
  4202. return pv.rgb(this.r, this.g, this.b, a);
  4203. };
  4204. /**
  4205. * Returns the RGB color equivalent to this color. This method is abstract and
  4206. * must be implemented by subclasses.
  4207. *
  4208. * @returns {pv.Color.Rgb} an RGB color.
  4209. * @function
  4210. * @name pv.Color.prototype.rgb
  4211. */
  4212. /**
  4213. * Returns this.
  4214. *
  4215. * @returns {pv.Color.Rgb} this.
  4216. */
  4217. pv.Color.Rgb.prototype.rgb = function() { return this; };
  4218. /**
  4219. * Returns a new color that is a brighter version of this color. This method
  4220. * applies an arbitrary scale factor to each of the three RGB components of this
  4221. * color to create a brighter version of this color. Although brighter and
  4222. * darker are inverse operations, the results of a series of invocations of
  4223. * these two methods might be inconsistent because of rounding errors.
  4224. *
  4225. * @param [k] {number} an optional scale factor; defaults to 1.
  4226. * @see #darker
  4227. * @returns {pv.Color.Rgb} a brighter color.
  4228. */
  4229. pv.Color.Rgb.prototype.brighter = function(k) {
  4230. k = Math.pow(0.7, arguments.length ? k : 1);
  4231. var r = this.r, g = this.g, b = this.b, i = 30;
  4232. if (!r && !g && !b) return pv.rgb(i, i, i, this.a);
  4233. if (r && (r < i)) r = i;
  4234. if (g && (g < i)) g = i;
  4235. if (b && (b < i)) b = i;
  4236. return pv.rgb(
  4237. Math.min(255, Math.floor(r / k)),
  4238. Math.min(255, Math.floor(g / k)),
  4239. Math.min(255, Math.floor(b / k)),
  4240. this.a);
  4241. };
  4242. /**
  4243. * Returns a new color that is a darker version of this color. This method
  4244. * applies an arbitrary scale factor to each of the three RGB components of this
  4245. * color to create a darker version of this color. Although brighter and darker
  4246. * are inverse operations, the results of a series of invocations of these two
  4247. * methods might be inconsistent because of rounding errors.
  4248. *
  4249. * @param [k] {number} an optional scale factor; defaults to 1.
  4250. * @see #brighter
  4251. * @returns {pv.Color.Rgb} a darker color.
  4252. */
  4253. pv.Color.Rgb.prototype.darker = function(k) {
  4254. k = Math.pow(0.7, arguments.length ? k : 1);
  4255. return pv.rgb(
  4256. Math.max(0, Math.floor(k * this.r)),
  4257. Math.max(0, Math.floor(k * this.g)),
  4258. Math.max(0, Math.floor(k * this.b)),
  4259. this.a);
  4260. };
  4261. /**
  4262. * Constructs a new HSL color with the specified values.
  4263. *
  4264. * @param {number} h the hue, an integer in [0, 360].
  4265. * @param {number} s the saturation, a float in [0, 1].
  4266. * @param {number} l the lightness, a float in [0, 1].
  4267. * @param {number} [a] the opacity, a float in [0, 1].
  4268. * @returns pv.Color.Hsl
  4269. */
  4270. pv.hsl = function(h, s, l, a) {
  4271. return new pv.Color.Hsl(h, s, l, (arguments.length == 4) ? a : 1);
  4272. };
  4273. /**
  4274. * Constructs a new HSL color with the specified values.
  4275. *
  4276. * @class Represents a color in HSL space.
  4277. *
  4278. * @param {number} h the hue, an integer in [0, 360].
  4279. * @param {number} s the saturation, a float in [0, 1].
  4280. * @param {number} l the lightness, a float in [0, 1].
  4281. * @param {number} a the opacity, a float in [0, 1].
  4282. * @extends pv.Color
  4283. */
  4284. pv.Color.Hsl = function(h, s, l, a) {
  4285. pv.Color.call(this, "hsl(" + h + "," + (s * 100) + "%," + (l * 100) + "%)", a);
  4286. /**
  4287. * The hue, an integer in [0, 360].
  4288. *
  4289. * @type number
  4290. */
  4291. this.h = h;
  4292. /**
  4293. * The saturation, a float in [0, 1].
  4294. *
  4295. * @type number
  4296. */
  4297. this.s = s;
  4298. /**
  4299. * The lightness, a float in [0, 1].
  4300. *
  4301. * @type number
  4302. */
  4303. this.l = l;
  4304. /**
  4305. * The opacity, a float in [0, 1].
  4306. *
  4307. * @type number
  4308. */
  4309. this.a = a;
  4310. };
  4311. pv.Color.Hsl.prototype = pv.extend(pv.Color);
  4312. /**
  4313. * Constructs a new HSL color with the same saturation, lightness and alpha as
  4314. * this color, and the specified hue.
  4315. *
  4316. * @param {number} h the hue, an integer in [0, 360].
  4317. */
  4318. pv.Color.Hsl.prototype.hue = function(h) {
  4319. return pv.hsl(h, this.s, this.l, this.a);
  4320. };
  4321. /**
  4322. * Constructs a new HSL color with the same hue, lightness and alpha as this
  4323. * color, and the specified saturation.
  4324. *
  4325. * @param {number} s the saturation, a float in [0, 1].
  4326. */
  4327. pv.Color.Hsl.prototype.saturation = function(s) {
  4328. return pv.hsl(this.h, s, this.l, this.a);
  4329. };
  4330. /**
  4331. * Constructs a new HSL color with the same hue, saturation and alpha as this
  4332. * color, and the specified lightness.
  4333. *
  4334. * @param {number} l the lightness, a float in [0, 1].
  4335. */
  4336. pv.Color.Hsl.prototype.lightness = function(l) {
  4337. return pv.hsl(this.h, this.s, l, this.a);
  4338. };
  4339. /**
  4340. * Constructs a new HSL color with the same hue, saturation and lightness as
  4341. * this color, and the specified alpha.
  4342. *
  4343. * @param {number} a the opacity, a float in [0, 1].
  4344. */
  4345. pv.Color.Hsl.prototype.alpha = function(a) {
  4346. return pv.hsl(this.h, this.s, this.l, a);
  4347. };
  4348. /**
  4349. * Returns the RGB color equivalent to this HSL color.
  4350. *
  4351. * @returns {pv.Color.Rgb} an RGB color.
  4352. */
  4353. pv.Color.Hsl.prototype.rgb = function() {
  4354. var h = this.h, s = this.s, l = this.l;
  4355. /* Some simple corrections for h, s and l. */
  4356. h = h % 360; if (h < 0) h += 360;
  4357. s = Math.max(0, Math.min(s, 1));
  4358. l = Math.max(0, Math.min(l, 1));
  4359. /* From FvD 13.37, CSS Color Module Level 3 */
  4360. var m2 = (l <= .5) ? (l * (1 + s)) : (l + s - l * s);
  4361. var m1 = 2 * l - m2;
  4362. function v(h) {
  4363. if (h > 360) h -= 360;
  4364. else if (h < 0) h += 360;
  4365. if (h < 60) return m1 + (m2 - m1) * h / 60;
  4366. if (h < 180) return m2;
  4367. if (h < 240) return m1 + (m2 - m1) * (240 - h) / 60;
  4368. return m1;
  4369. }
  4370. function vv(h) {
  4371. return Math.round(v(h) * 255);
  4372. }
  4373. return pv.rgb(vv(h + 120), vv(h), vv(h - 120), this.a);
  4374. };
  4375. /**
  4376. * @private SVG color keywords, per CSS Color Module Level 3.
  4377. *
  4378. * @see <a href="http://www.w3.org/TR/SVG/types.html#ColorKeywords">SVG color
  4379. * keywords</a>
  4380. */
  4381. pv.Color.names = {
  4382. aliceblue: "#f0f8ff",
  4383. antiquewhite: "#faebd7",
  4384. aqua: "#00ffff",
  4385. aquamarine: "#7fffd4",
  4386. azure: "#f0ffff",
  4387. beige: "#f5f5dc",
  4388. bisque: "#ffe4c4",
  4389. black: "#000000",
  4390. blanchedalmond: "#ffebcd",
  4391. blue: "#0000ff",
  4392. blueviolet: "#8a2be2",
  4393. brown: "#a52a2a",
  4394. burlywood: "#deb887",
  4395. cadetblue: "#5f9ea0",
  4396. chartreuse: "#7fff00",
  4397. chocolate: "#d2691e",
  4398. coral: "#ff7f50",
  4399. cornflowerblue: "#6495ed",
  4400. cornsilk: "#fff8dc",
  4401. crimson: "#dc143c",
  4402. cyan: "#00ffff",
  4403. darkblue: "#00008b",
  4404. darkcyan: "#008b8b",
  4405. darkgoldenrod: "#b8860b",
  4406. darkgray: "#a9a9a9",
  4407. darkgreen: "#006400",
  4408. darkgrey: "#a9a9a9",
  4409. darkkhaki: "#bdb76b",
  4410. darkmagenta: "#8b008b",
  4411. darkolivegreen: "#556b2f",
  4412. darkorange: "#ff8c00",
  4413. darkorchid: "#9932cc",
  4414. darkred: "#8b0000",
  4415. darksalmon: "#e9967a",
  4416. darkseagreen: "#8fbc8f",
  4417. darkslateblue: "#483d8b",
  4418. darkslategray: "#2f4f4f",
  4419. darkslategrey: "#2f4f4f",
  4420. darkturquoise: "#00ced1",
  4421. darkviolet: "#9400d3",
  4422. deeppink: "#ff1493",
  4423. deepskyblue: "#00bfff",
  4424. dimgray: "#696969",
  4425. dimgrey: "#696969",
  4426. dodgerblue: "#1e90ff",
  4427. firebrick: "#b22222",
  4428. floralwhite: "#fffaf0",
  4429. forestgreen: "#228b22",
  4430. fuchsia: "#ff00ff",
  4431. gainsboro: "#dcdcdc",
  4432. ghostwhite: "#f8f8ff",
  4433. gold: "#ffd700",
  4434. goldenrod: "#daa520",
  4435. gray: "#808080",
  4436. green: "#008000",
  4437. greenyellow: "#adff2f",
  4438. grey: "#808080",
  4439. honeydew: "#f0fff0",
  4440. hotpink: "#ff69b4",
  4441. indianred: "#cd5c5c",
  4442. indigo: "#4b0082",
  4443. ivory: "#fffff0",
  4444. khaki: "#f0e68c",
  4445. lavender: "#e6e6fa",
  4446. lavenderblush: "#fff0f5",
  4447. lawngreen: "#7cfc00",
  4448. lemonchiffon: "#fffacd",
  4449. lightblue: "#add8e6",
  4450. lightcoral: "#f08080",
  4451. lightcyan: "#e0ffff",
  4452. lightgoldenrodyellow: "#fafad2",
  4453. lightgray: "#d3d3d3",
  4454. lightgreen: "#90ee90",
  4455. lightgrey: "#d3d3d3",
  4456. lightpink: "#ffb6c1",
  4457. lightsalmon: "#ffa07a",
  4458. lightseagreen: "#20b2aa",
  4459. lightskyblue: "#87cefa",
  4460. lightslategray: "#778899",
  4461. lightslategrey: "#778899",
  4462. lightsteelblue: "#b0c4de",
  4463. lightyellow: "#ffffe0",
  4464. lime: "#00ff00",
  4465. limegreen: "#32cd32",
  4466. linen: "#faf0e6",
  4467. magenta: "#ff00ff",
  4468. maroon: "#800000",
  4469. mediumaquamarine: "#66cdaa",
  4470. mediumblue: "#0000cd",
  4471. mediumorchid: "#ba55d3",
  4472. mediumpurple: "#9370db",
  4473. mediumseagreen: "#3cb371",
  4474. mediumslateblue: "#7b68ee",
  4475. mediumspringgreen: "#00fa9a",
  4476. mediumturquoise: "#48d1cc",
  4477. mediumvioletred: "#c71585",
  4478. midnightblue: "#191970",
  4479. mintcream: "#f5fffa",
  4480. mistyrose: "#ffe4e1",
  4481. moccasin: "#ffe4b5",
  4482. navajowhite: "#ffdead",
  4483. navy: "#000080",
  4484. oldlace: "#fdf5e6",
  4485. olive: "#808000",
  4486. olivedrab: "#6b8e23",
  4487. orange: "#ffa500",
  4488. orangered: "#ff4500",
  4489. orchid: "#da70d6",
  4490. palegoldenrod: "#eee8aa",
  4491. palegreen: "#98fb98",
  4492. paleturquoise: "#afeeee",
  4493. palevioletred: "#db7093",
  4494. papayawhip: "#ffefd5",
  4495. peachpuff: "#ffdab9",
  4496. peru: "#cd853f",
  4497. pink: "#ffc0cb",
  4498. plum: "#dda0dd",
  4499. powderblue: "#b0e0e6",
  4500. purple: "#800080",
  4501. red: "#ff0000",
  4502. rosybrown: "#bc8f8f",
  4503. royalblue: "#4169e1",
  4504. saddlebrown: "#8b4513",
  4505. salmon: "#fa8072",
  4506. sandybrown: "#f4a460",
  4507. seagreen: "#2e8b57",
  4508. seashell: "#fff5ee",
  4509. sienna: "#a0522d",
  4510. silver: "#c0c0c0",
  4511. skyblue: "#87ceeb",
  4512. slateblue: "#6a5acd",
  4513. slategray: "#708090",
  4514. slategrey: "#708090",
  4515. snow: "#fffafa",
  4516. springgreen: "#00ff7f",
  4517. steelblue: "#4682b4",
  4518. tan: "#d2b48c",
  4519. teal: "#008080",
  4520. thistle: "#d8bfd8",
  4521. tomato: "#ff6347",
  4522. turquoise: "#40e0d0",
  4523. violet: "#ee82ee",
  4524. wheat: "#f5deb3",
  4525. white: "#ffffff",
  4526. whitesmoke: "#f5f5f5",
  4527. yellow: "#ffff00",
  4528. yellowgreen: "#9acd32",
  4529. transparent: pv.Color.transparent = pv.rgb(0, 0, 0, 0)
  4530. };
  4531. /* Initialized named colors. */
  4532. (function() {
  4533. var names = pv.Color.names;
  4534. for (var name in names) names[name] = pv.color(names[name]);
  4535. })();
  4536. /**
  4537. * Returns a new categorical color encoding using the specified colors. The
  4538. * arguments to this method are an array of colors; see {@link pv.color}. For
  4539. * example, to create a categorical color encoding using the <tt>species</tt>
  4540. * attribute:
  4541. *
  4542. * <pre>pv.colors("red", "green", "blue").by(function(d) d.species)</pre>
  4543. *
  4544. * The result of this expression can be used as a fill- or stroke-style
  4545. * property. This assumes that the data's <tt>species</tt> attribute is a
  4546. * string.
  4547. *
  4548. * @param {string} colors... categorical colors.
  4549. * @see pv.Scale.ordinal
  4550. * @returns {pv.Scale.ordinal} an ordinal color scale.
  4551. */
  4552. pv.colors = function() {
  4553. var scale = pv.Scale.ordinal();
  4554. scale.range.apply(scale, arguments);
  4555. return scale;
  4556. };
  4557. /**
  4558. * A collection of standard color palettes for categorical encoding.
  4559. *
  4560. * @namespace A collection of standard color palettes for categorical encoding.
  4561. */
  4562. pv.Colors = {};
  4563. /**
  4564. * Returns a new 10-color scheme. The arguments to this constructor are
  4565. * optional, and equivalent to calling {@link pv.Scale.OrdinalScale#domain}. The
  4566. * following colors are used:
  4567. *
  4568. * <div style="background:#1f77b4;">#1f77b4</div>
  4569. * <div style="background:#ff7f0e;">#ff7f0e</div>
  4570. * <div style="background:#2ca02c;">#2ca02c</div>
  4571. * <div style="background:#d62728;">#d62728</div>
  4572. * <div style="background:#9467bd;">#9467bd</div>
  4573. * <div style="background:#8c564b;">#8c564b</div>
  4574. * <div style="background:#e377c2;">#e377c2</div>
  4575. * <div style="background:#7f7f7f;">#7f7f7f</div>
  4576. * <div style="background:#bcbd22;">#bcbd22</div>
  4577. * <div style="background:#17becf;">#17becf</div>
  4578. *
  4579. * @param {number...} domain... domain values.
  4580. * @returns {pv.Scale.ordinal} a new ordinal color scale.
  4581. * @see pv.color
  4582. */
  4583. pv.Colors.category10 = function() {
  4584. var scale = pv.colors(
  4585. "#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd",
  4586. "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf");
  4587. scale.domain.apply(scale, arguments);
  4588. return scale;
  4589. };
  4590. /**
  4591. * Returns a new 20-color scheme. The arguments to this constructor are
  4592. * optional, and equivalent to calling {@link pv.Scale.OrdinalScale#domain}. The
  4593. * following colors are used:
  4594. *
  4595. * <div style="background:#1f77b4;">#1f77b4</div>
  4596. * <div style="background:#aec7e8;">#aec7e8</div>
  4597. * <div style="background:#ff7f0e;">#ff7f0e</div>
  4598. * <div style="background:#ffbb78;">#ffbb78</div>
  4599. * <div style="background:#2ca02c;">#2ca02c</div>
  4600. * <div style="background:#98df8a;">#98df8a</div>
  4601. * <div style="background:#d62728;">#d62728</div>
  4602. * <div style="background:#ff9896;">#ff9896</div>
  4603. * <div style="background:#9467bd;">#9467bd</div>
  4604. * <div style="background:#c5b0d5;">#c5b0d5</div>
  4605. * <div style="background:#8c564b;">#8c564b</div>
  4606. * <div style="background:#c49c94;">#c49c94</div>
  4607. * <div style="background:#e377c2;">#e377c2</div>
  4608. * <div style="background:#f7b6d2;">#f7b6d2</div>
  4609. * <div style="background:#7f7f7f;">#7f7f7f</div>
  4610. * <div style="background:#c7c7c7;">#c7c7c7</div>
  4611. * <div style="background:#bcbd22;">#bcbd22</div>
  4612. * <div style="background:#dbdb8d;">#dbdb8d</div>
  4613. * <div style="background:#17becf;">#17becf</div>
  4614. * <div style="background:#9edae5;">#9edae5</div>
  4615. *
  4616. * @param {number...} domain... domain values.
  4617. * @returns {pv.Scale.ordinal} a new ordinal color scale.
  4618. * @see pv.color
  4619. */
  4620. pv.Colors.category20 = function() {
  4621. var scale = pv.colors(
  4622. "#1f77b4", "#aec7e8", "#ff7f0e", "#ffbb78", "#2ca02c",
  4623. "#98df8a", "#d62728", "#ff9896", "#9467bd", "#c5b0d5",
  4624. "#8c564b", "#c49c94", "#e377c2", "#f7b6d2", "#7f7f7f",
  4625. "#c7c7c7", "#bcbd22", "#dbdb8d", "#17becf", "#9edae5");
  4626. scale.domain.apply(scale, arguments);
  4627. return scale;
  4628. };
  4629. /**
  4630. * Returns a new alternative 19-color scheme. The arguments to this constructor
  4631. * are optional, and equivalent to calling
  4632. * {@link pv.Scale.OrdinalScale#domain}. The following colors are used:
  4633. *
  4634. * <div style="background:#9c9ede;">#9c9ede</div>
  4635. * <div style="background:#7375b5;">#7375b5</div>
  4636. * <div style="background:#4a5584;">#4a5584</div>
  4637. * <div style="background:#cedb9c;">#cedb9c</div>
  4638. * <div style="background:#b5cf6b;">#b5cf6b</div>
  4639. * <div style="background:#8ca252;">#8ca252</div>
  4640. * <div style="background:#637939;">#637939</div>
  4641. * <div style="background:#e7cb94;">#e7cb94</div>
  4642. * <div style="background:#e7ba52;">#e7ba52</div>
  4643. * <div style="background:#bd9e39;">#bd9e39</div>
  4644. * <div style="background:#8c6d31;">#8c6d31</div>
  4645. * <div style="background:#e7969c;">#e7969c</div>
  4646. * <div style="background:#d6616b;">#d6616b</div>
  4647. * <div style="background:#ad494a;">#ad494a</div>
  4648. * <div style="background:#843c39;">#843c39</div>
  4649. * <div style="background:#de9ed6;">#de9ed6</div>
  4650. * <div style="background:#ce6dbd;">#ce6dbd</div>
  4651. * <div style="background:#a55194;">#a55194</div>
  4652. * <div style="background:#7b4173;">#7b4173</div>
  4653. *
  4654. * @param {number...} domain... domain values.
  4655. * @returns {pv.Scale.ordinal} a new ordinal color scale.
  4656. * @see pv.color
  4657. */
  4658. pv.Colors.category19 = function() {
  4659. var scale = pv.colors(
  4660. "#9c9ede", "#7375b5", "#4a5584", "#cedb9c", "#b5cf6b",
  4661. "#8ca252", "#637939", "#e7cb94", "#e7ba52", "#bd9e39",
  4662. "#8c6d31", "#e7969c", "#d6616b", "#ad494a", "#843c39",
  4663. "#de9ed6", "#ce6dbd", "#a55194", "#7b4173");
  4664. scale.domain.apply(scale, arguments);
  4665. return scale;
  4666. };
  4667. /**
  4668. * Returns a linear color ramp from the specified <tt>start</tt> color to the
  4669. * specified <tt>end</tt> color. The color arguments may be specified either as
  4670. * <tt>string</tt>s or as {@link pv.Color}s. This is equivalent to:
  4671. *
  4672. * <pre> pv.Scale.linear().domain(0, 1).range(...)</pre>
  4673. *
  4674. * @param {string} start the start color; may be a <tt>pv.Color</tt>.
  4675. * @param {string} end the end color; may be a <tt>pv.Color</tt>.
  4676. * @returns {Function} a color ramp from <tt>start</tt> to <tt>end</tt>.
  4677. * @see pv.Scale.linear
  4678. */
  4679. pv.ramp = function(start, end) {
  4680. var scale = pv.Scale.linear();
  4681. scale.range.apply(scale, arguments);
  4682. return scale;
  4683. };
  4684. /**
  4685. * @private
  4686. * @namespace
  4687. */
  4688. pv.SvgScene = {
  4689. /* Various namespaces. */
  4690. svg: "http://www.w3.org/2000/svg",
  4691. xmlns: "http://www.w3.org/2000/xmlns",
  4692. xlink: "http://www.w3.org/1999/xlink",
  4693. xhtml: "http://www.w3.org/1999/xhtml",
  4694. /** The pre-multipled scale, based on any enclosing transforms. */
  4695. scale: 1,
  4696. /** The set of supported events. */
  4697. events: [
  4698. "DOMMouseScroll", // for Firefox
  4699. "mousewheel",
  4700. "mousedown",
  4701. "mouseup",
  4702. "mouseover",
  4703. "mouseout",
  4704. "mousemove",
  4705. "click",
  4706. "dblclick"
  4707. ],
  4708. /** Implicit values for SVG and CSS properties. */
  4709. implicit: {
  4710. svg: {
  4711. "shape-rendering": "auto",
  4712. "pointer-events": "painted",
  4713. "x": 0,
  4714. "y": 0,
  4715. "dy": 0,
  4716. "text-anchor": "start",
  4717. "transform": "translate(0,0)",
  4718. "fill": "none",
  4719. "fill-opacity": 1,
  4720. "stroke": "none",
  4721. "stroke-opacity": 1,
  4722. "stroke-width": 1.5,
  4723. "stroke-linejoin": "miter"
  4724. },
  4725. css: {
  4726. "font": "10px sans-serif"
  4727. }
  4728. }
  4729. };
  4730. /**
  4731. * Creates a new SVG element of the specified type.
  4732. *
  4733. * @param type {string} an SVG element type, such as "rect".
  4734. * @returns a new SVG element.
  4735. */
  4736. pv.SvgScene.create = function(type) {
  4737. return document.createElementNS(this.svg, type);
  4738. };
  4739. /**
  4740. * Expects the element <i>e</i> to be the specified type. If the element does
  4741. * not exist, a new one is created. If the element does exist but is the wrong
  4742. * type, it is replaced with the specified element.
  4743. *
  4744. * @param e the current SVG element.
  4745. * @param type {string} an SVG element type, such as "rect".
  4746. * @param attributes an optional attribute map.
  4747. * @param style an optional style map.
  4748. * @returns a new SVG element.
  4749. */
  4750. pv.SvgScene.expect = function(e, type, attributes, style) {
  4751. if (e) {
  4752. if (e.tagName == "a") e = e.firstChild;
  4753. if (e.tagName != type) {
  4754. var n = this.create(type);
  4755. e.parentNode.replaceChild(n, e);
  4756. e = n;
  4757. }
  4758. } else {
  4759. e = this.create(type);
  4760. }
  4761. for (var name in attributes) {
  4762. var value = attributes[name];
  4763. if (value == this.implicit.svg[name]) value = null;
  4764. if (value == null) e.removeAttribute(name);
  4765. else e.setAttribute(name, value);
  4766. }
  4767. for (var name in style) {
  4768. var value = style[name];
  4769. if (value == this.implicit.css[name]) value = null;
  4770. if (value == null) e.style.removeProperty(name);
  4771. else e.style[name] = value;
  4772. }
  4773. return e;
  4774. };
  4775. /** TODO */
  4776. pv.SvgScene.append = function(e, scenes, index) {
  4777. e.$scene = {scenes:scenes, index:index};
  4778. e = this.title(e, scenes[index]);
  4779. if (!e.parentNode) scenes.$g.appendChild(e);
  4780. return e.nextSibling;
  4781. };
  4782. /**
  4783. * Applies a title tooltip to the specified element <tt>e</tt>, using the
  4784. * <tt>title</tt> property of the specified scene node <tt>s</tt>. Note that
  4785. * this implementation does not create an SVG <tt>title</tt> element as a child
  4786. * of <tt>e</tt>; although this is the recommended standard, it is only
  4787. * supported in Opera. Instead, an anchor element is created around the element
  4788. * <tt>e</tt>, and the <tt>xlink:title</tt> attribute is set accordingly.
  4789. *
  4790. * @param e an SVG element.
  4791. * @param s a scene node.
  4792. */
  4793. pv.SvgScene.title = function(e, s) {
  4794. var a = e.parentNode;
  4795. if (a && (a.tagName != "a")) a = null;
  4796. if (s.title) {
  4797. if (!a) {
  4798. a = this.create("a");
  4799. if (e.parentNode) e.parentNode.replaceChild(a, e);
  4800. a.appendChild(e);
  4801. }
  4802. a.setAttributeNS(this.xlink, "title", s.title);
  4803. return a;
  4804. }
  4805. if (a) a.parentNode.replaceChild(e, a);
  4806. return e;
  4807. };
  4808. /** TODO */
  4809. pv.SvgScene.dispatch = pv.listener(function(e) {
  4810. var t = e.target.$scene;
  4811. if (t) {
  4812. var type = e.type;
  4813. /* Fixes for mousewheel support on Firefox & Opera. */
  4814. switch (type) {
  4815. case "DOMMouseScroll": {
  4816. type = "mousewheel";
  4817. e.wheel = -480 * e.detail;
  4818. break;
  4819. }
  4820. case "mousewheel": {
  4821. e.wheel = (window.opera ? 12 : 1) * e.wheelDelta;
  4822. break;
  4823. }
  4824. }
  4825. if (pv.Mark.dispatch(type, t.scenes, t.index)) e.preventDefault();
  4826. }
  4827. });
  4828. /** @private Do nothing when rendering undefined mark types. */
  4829. pv.SvgScene.undefined = function() {};
  4830. /**
  4831. * @private Converts the specified b-spline curve segment to a bezier curve
  4832. * compatible with SVG "C".
  4833. *
  4834. * @param p0 the first control point.
  4835. * @param p1 the second control point.
  4836. * @param p2 the third control point.
  4837. * @param p3 the fourth control point.
  4838. */
  4839. pv.SvgScene.pathBasis = (function() {
  4840. /**
  4841. * Matrix to transform basis (b-spline) control points to bezier control
  4842. * points. Derived from FvD 11.2.8.
  4843. */
  4844. var basis = [
  4845. [ 1/6, 2/3, 1/6, 0 ],
  4846. [ 0, 2/3, 1/3, 0 ],
  4847. [ 0, 1/3, 2/3, 0 ],
  4848. [ 0, 1/6, 2/3, 1/6 ]
  4849. ];
  4850. /**
  4851. * Returns the point that is the weighted sum of the specified control points,
  4852. * using the specified weights. This method requires that there are four
  4853. * weights and four control points.
  4854. */
  4855. function weight(w, p0, p1, p2, p3) {
  4856. return {
  4857. x: w[0] * p0.left + w[1] * p1.left + w[2] * p2.left + w[3] * p3.left,
  4858. y: w[0] * p0.top + w[1] * p1.top + w[2] * p2.top + w[3] * p3.top
  4859. };
  4860. }
  4861. var convert = function(p0, p1, p2, p3) {
  4862. var b1 = weight(basis[1], p0, p1, p2, p3),
  4863. b2 = weight(basis[2], p0, p1, p2, p3),
  4864. b3 = weight(basis[3], p0, p1, p2, p3);
  4865. return "C" + b1.x + "," + b1.y
  4866. + "," + b2.x + "," + b2.y
  4867. + "," + b3.x + "," + b3.y;
  4868. };
  4869. convert.segment = function(p0, p1, p2, p3) {
  4870. var b0 = weight(basis[0], p0, p1, p2, p3),
  4871. b1 = weight(basis[1], p0, p1, p2, p3),
  4872. b2 = weight(basis[2], p0, p1, p2, p3),
  4873. b3 = weight(basis[3], p0, p1, p2, p3);
  4874. return "M" + b0.x + "," + b0.y
  4875. + "C" + b1.x + "," + b1.y
  4876. + "," + b2.x + "," + b2.y
  4877. + "," + b3.x + "," + b3.y;
  4878. };
  4879. return convert;
  4880. })();
  4881. /**
  4882. * @private Interpolates the given points using the basis spline interpolation.
  4883. * Returns an SVG path without the leading M instruction to allow path
  4884. * appending.
  4885. *
  4886. * @param points the array of points.
  4887. */
  4888. pv.SvgScene.curveBasis = function(points) {
  4889. if (points.length <= 2) return "";
  4890. var path = "",
  4891. p0 = points[0],
  4892. p1 = p0,
  4893. p2 = p0,
  4894. p3 = points[1];
  4895. path += this.pathBasis(p0, p1, p2, p3);
  4896. for (var i = 2; i < points.length; i++) {
  4897. p0 = p1;
  4898. p1 = p2;
  4899. p2 = p3;
  4900. p3 = points[i];
  4901. path += this.pathBasis(p0, p1, p2, p3);
  4902. }
  4903. /* Cycle through to get the last point. */
  4904. path += this.pathBasis(p1, p2, p3, p3);
  4905. path += this.pathBasis(p2, p3, p3, p3);
  4906. return path;
  4907. };
  4908. /**
  4909. * @private Interpolates the given points using the basis spline interpolation.
  4910. * If points.length == tangents.length then a regular Hermite interpolation is
  4911. * performed, if points.length == tangents.length + 2 then the first and last
  4912. * segments are filled in with cubic bazier segments. Returns an array of path
  4913. * strings.
  4914. *
  4915. * @param points the array of points.
  4916. */
  4917. pv.SvgScene.curveBasisSegments = function(points) {
  4918. if (points.length <= 2) return "";
  4919. var paths = [],
  4920. p0 = points[0],
  4921. p1 = p0,
  4922. p2 = p0,
  4923. p3 = points[1],
  4924. firstPath = this.pathBasis.segment(p0, p1, p2, p3);
  4925. p0 = p1;
  4926. p1 = p2;
  4927. p2 = p3;
  4928. p3 = points[2];
  4929. paths.push(firstPath + this.pathBasis(p0, p1, p2, p3)); // merge first & second path
  4930. for (var i = 3; i < points.length; i++) {
  4931. p0 = p1;
  4932. p1 = p2;
  4933. p2 = p3;
  4934. p3 = points[i];
  4935. paths.push(this.pathBasis.segment(p0, p1, p2, p3));
  4936. }
  4937. // merge last & second-to-last path
  4938. paths.push(this.pathBasis.segment(p1, p2, p3, p3) + this.pathBasis(p2, p3, p3, p3));
  4939. return paths;
  4940. };
  4941. /**
  4942. * @private Interpolates the given points with respective tangents using the cubic
  4943. * Hermite spline interpolation. If points.length == tangents.length then a regular
  4944. * Hermite interpolation is performed, if points.length == tangents.length + 2 then
  4945. * the first and last segments are filled in with cubic bazier segments.
  4946. * Returns an SVG path without the leading M instruction to allow path appending.
  4947. *
  4948. * @param points the array of points.
  4949. * @param tangents the array of tangent vectors.
  4950. */
  4951. pv.SvgScene.curveHermite = function(points, tangents) {
  4952. if (tangents.length < 1
  4953. || (points.length != tangents.length
  4954. && points.length != tangents.length + 2)) return "";
  4955. var quad = points.length != tangents.length,
  4956. path = "",
  4957. p0 = points[0],
  4958. p = points[1],
  4959. t0 = tangents[0],
  4960. t = t0,
  4961. pi = 1;
  4962. if (quad) {
  4963. path += "Q" + (p.left - t0.x * 2 / 3) + "," + (p.top - t0.y * 2 / 3)
  4964. + "," + p.left + "," + p.top;
  4965. p0 = points[1];
  4966. pi = 2;
  4967. }
  4968. if (tangents.length > 1) {
  4969. t = tangents[1];
  4970. p = points[pi];
  4971. pi++;
  4972. path += "C" + (p0.left + t0.x) + "," + (p0.top + t0.y)
  4973. + "," + (p.left - t.x) + "," + (p.top - t.y)
  4974. + "," + p.left + "," + p.top;
  4975. for (var i = 2; i < tangents.length; i++, pi++) {
  4976. p = points[pi];
  4977. t = tangents[i];
  4978. path += "S" + (p.left - t.x) + "," + (p.top - t.y)
  4979. + "," + p.left + "," + p.top;
  4980. }
  4981. }
  4982. if (quad) {
  4983. var lp = points[pi];
  4984. path += "Q" + (p.left + t.x * 2 / 3) + "," + (p.top + t.y * 2 / 3) + ","
  4985. + lp.left + "," + lp.top;
  4986. }
  4987. return path;
  4988. };
  4989. /**
  4990. * @private Interpolates the given points with respective tangents using the
  4991. * cubic Hermite spline interpolation. Returns an array of path strings.
  4992. *
  4993. * @param points the array of points.
  4994. * @param tangents the array of tangent vectors.
  4995. */
  4996. pv.SvgScene.curveHermiteSegments = function(points, tangents) {
  4997. if (tangents.length < 1
  4998. || (points.length != tangents.length
  4999. && points.length != tangents.length + 2)) return [];
  5000. var quad = points.length != tangents.length,
  5001. paths = [],
  5002. p0 = points[0],
  5003. p = p0,
  5004. t0 = tangents[0],
  5005. t = t0,
  5006. pi = 1;
  5007. if (quad) {
  5008. p = points[1];
  5009. paths.push("M" + p0.left + "," + p0.top
  5010. + "Q" + (p.left - t.x * 2 / 3) + "," + (p.top - t.y * 2 / 3)
  5011. + "," + p.left + "," + p.top);
  5012. pi = 2;
  5013. }
  5014. for (var i = 1; i < tangents.length; i++, pi++) {
  5015. p0 = p;
  5016. t0 = t;
  5017. p = points[pi];
  5018. t = tangents[i];
  5019. paths.push("M" + p0.left + "," + p0.top
  5020. + "C" + (p0.left + t0.x) + "," + (p0.top + t0.y)
  5021. + "," + (p.left - t.x) + "," + (p.top - t.y)
  5022. + "," + p.left + "," + p.top);
  5023. }
  5024. if (quad) {
  5025. var lp = points[pi];
  5026. paths.push("M" + p.left + "," + p.top
  5027. + "Q" + (p.left + t.x * 2 / 3) + "," + (p.top + t.y * 2 / 3) + ","
  5028. + lp.left + "," + lp.top);
  5029. }
  5030. return paths;
  5031. };
  5032. /**
  5033. * @private Computes the tangents for the given points needed for cardinal
  5034. * spline interpolation. Returns an array of tangent vectors. Note: that for n
  5035. * points only the n-2 well defined tangents are returned.
  5036. *
  5037. * @param points the array of points.
  5038. * @param tension the tension of hte cardinal spline.
  5039. */
  5040. pv.SvgScene.cardinalTangents = function(points, tension) {
  5041. var tangents = [],
  5042. a = (1 - tension) / 2,
  5043. p0 = points[0],
  5044. p1 = points[1],
  5045. p2 = points[2];
  5046. for (var i = 3; i < points.length; i++) {
  5047. tangents.push({x: a * (p2.left - p0.left), y: a * (p2.top - p0.top)});
  5048. p0 = p1;
  5049. p1 = p2;
  5050. p2 = points[i];
  5051. }
  5052. tangents.push({x: a * (p2.left - p0.left), y: a * (p2.top - p0.top)});
  5053. return tangents;
  5054. };
  5055. /**
  5056. * @private Interpolates the given points using cardinal spline interpolation.
  5057. * Returns an SVG path without the leading M instruction to allow path
  5058. * appending.
  5059. *
  5060. * @param points the array of points.
  5061. * @param tension the tension of hte cardinal spline.
  5062. */
  5063. pv.SvgScene.curveCardinal = function(points, tension) {
  5064. if (points.length <= 2) return "";
  5065. return this.curveHermite(points, this.cardinalTangents(points, tension));
  5066. };
  5067. /**
  5068. * @private Interpolates the given points using cardinal spline interpolation.
  5069. * Returns an array of path strings.
  5070. *
  5071. * @param points the array of points.
  5072. * @param tension the tension of hte cardinal spline.
  5073. */
  5074. pv.SvgScene.curveCardinalSegments = function(points, tension) {
  5075. if (points.length <= 2) return "";
  5076. return this.curveHermiteSegments(points, this.cardinalTangents(points, tension));
  5077. };
  5078. /**
  5079. * @private Interpolates the given points using Fritsch-Carlson Monotone cubic
  5080. * Hermite interpolation. Returns an array of tangent vectors.
  5081. *
  5082. * @param points the array of points.
  5083. */
  5084. pv.SvgScene.monotoneTangents = function(points) {
  5085. var tangents = [],
  5086. d = [],
  5087. m = [],
  5088. dx = [],
  5089. k = 0;
  5090. /* Compute the slopes of the secant lines between successive points. */
  5091. for (k = 0; k < points.length-1; k++) {
  5092. d[k] = (points[k+1].top - points[k].top)/(points[k+1].left - points[k].left);
  5093. }
  5094. /* Initialize the tangents at every point as the average of the secants. */
  5095. m[0] = d[0];
  5096. dx[0] = points[1].left - points[0].left;
  5097. for (k = 1; k < points.length - 1; k++) {
  5098. m[k] = (d[k-1]+d[k])/2;
  5099. dx[k] = (points[k+1].left - points[k-1].left)/2;
  5100. }
  5101. m[k] = d[k-1];
  5102. dx[k] = (points[k].left - points[k-1].left);
  5103. /* Step 3. Very important, step 3. Yep. Wouldn't miss it. */
  5104. for (k = 0; k < points.length - 1; k++) {
  5105. if (d[k] == 0) {
  5106. m[ k ] = 0;
  5107. m[k+1] = 0;
  5108. }
  5109. }
  5110. /* Step 4 + 5. Out of 5 or more steps. */
  5111. for (k = 0; k < points.length - 1; k++) {
  5112. if ((Math.abs(m[k]) < 1e-5) || (Math.abs(m[k+1]) < 1e-5)) continue;
  5113. var ak = m[k] / d[k],
  5114. bk = m[k + 1] / d[k],
  5115. s = ak * ak + bk * bk; // monotone constant (?)
  5116. if (s > 9) {
  5117. var tk = 3 / Math.sqrt(s);
  5118. m[k] = tk * ak * d[k];
  5119. m[k + 1] = tk * bk * d[k];
  5120. }
  5121. }
  5122. var len;
  5123. for (var i = 0; i < points.length; i++) {
  5124. len = 1 + m[i] * m[i]; // pv.vector(1, m[i]).norm().times(dx[i]/3)
  5125. tangents.push({x: dx[i] / 3 / len, y: m[i] * dx[i] / 3 / len});
  5126. }
  5127. return tangents;
  5128. };
  5129. /**
  5130. * @private Interpolates the given points using Fritsch-Carlson Monotone cubic
  5131. * Hermite interpolation. Returns an SVG path without the leading M instruction
  5132. * to allow path appending.
  5133. *
  5134. * @param points the array of points.
  5135. */
  5136. pv.SvgScene.curveMonotone = function(points) {
  5137. if (points.length <= 2) return "";
  5138. return this.curveHermite(points, this.monotoneTangents(points));
  5139. }
  5140. /**
  5141. * @private Interpolates the given points using Fritsch-Carlson Monotone cubic
  5142. * Hermite interpolation.
  5143. * Returns an array of path strings.
  5144. *
  5145. * @param points the array of points.
  5146. */
  5147. pv.SvgScene.curveMonotoneSegments = function(points) {
  5148. if (points.length <= 2) return "";
  5149. return this.curveHermiteSegments(points, this.monotoneTangents(points));
  5150. };
  5151. pv.SvgScene.area = function(scenes) {
  5152. var e = scenes.$g.firstChild;
  5153. if (!scenes.length) return e;
  5154. var s = scenes[0];
  5155. /* segmented */
  5156. if (s.segmented) return this.areaSegment(scenes);
  5157. /* visible */
  5158. if (!s.visible) return e;
  5159. var fill = s.fillStyle, stroke = s.strokeStyle;
  5160. if (!fill.opacity && !stroke.opacity) return e;
  5161. /** @private Computes the straight path for the range [i, j]. */
  5162. function path(i, j) {
  5163. var p1 = [], p2 = [];
  5164. for (var k = j; i <= k; i++, j--) {
  5165. var si = scenes[i],
  5166. sj = scenes[j],
  5167. pi = si.left + "," + si.top,
  5168. pj = (sj.left + sj.width) + "," + (sj.top + sj.height);
  5169. /* interpolate */
  5170. if (i < k) {
  5171. var sk = scenes[i + 1], sl = scenes[j - 1];
  5172. switch (s.interpolate) {
  5173. case "step-before": {
  5174. pi += "V" + sk.top;
  5175. pj += "H" + (sl.left + sl.width);
  5176. break;
  5177. }
  5178. case "step-after": {
  5179. pi += "H" + sk.left;
  5180. pj += "V" + (sl.top + sl.height);
  5181. break;
  5182. }
  5183. }
  5184. }
  5185. p1.push(pi);
  5186. p2.push(pj);
  5187. }
  5188. return p1.concat(p2).join("L");
  5189. }
  5190. /** @private Computes the curved path for the range [i, j]. */
  5191. function pathCurve(i, j) {
  5192. var pointsT = [], pointsB = [], pathT, pathB;
  5193. for (var k = j; i <= k; i++, j--) {
  5194. var sj = scenes[j];
  5195. pointsT.push(scenes[i]);
  5196. pointsB.push({left: sj.left + sj.width, top: sj.top + sj.height});
  5197. }
  5198. if (s.interpolate == "basis") {
  5199. pathT = pv.SvgScene.curveBasis(pointsT);
  5200. pathB = pv.SvgScene.curveBasis(pointsB);
  5201. } else if (s.interpolate == "cardinal") {
  5202. pathT = pv.SvgScene.curveCardinal(pointsT, s.tension);
  5203. pathB = pv.SvgScene.curveCardinal(pointsB, s.tension);
  5204. } else { // monotone
  5205. pathT = pv.SvgScene.curveMonotone(pointsT);
  5206. pathB = pv.SvgScene.curveMonotone(pointsB);
  5207. }
  5208. return pointsT[0].left + "," + pointsT[0].top + pathT
  5209. + "L" + pointsB[0].left + "," + pointsB[0].top + pathB;
  5210. }
  5211. /* points */
  5212. var d = [], si, sj;
  5213. for (var i = 0; i < scenes.length; i++) {
  5214. si = scenes[i]; if (!si.width && !si.height) continue;
  5215. for (var j = i + 1; j < scenes.length; j++) {
  5216. sj = scenes[j]; if (!sj.width && !sj.height) break;
  5217. }
  5218. if (i && (s.interpolate != "step-after")) i--;
  5219. if ((j < scenes.length) && (s.interpolate != "step-before")) j++;
  5220. d.push(((j - i > 2
  5221. && (s.interpolate == "basis"
  5222. || s.interpolate == "cardinal"
  5223. || s.interpolate == "monotone"))
  5224. ? pathCurve : path)(i, j - 1));
  5225. i = j - 1;
  5226. }
  5227. if (!d.length) return e;
  5228. e = this.expect(e, "path", {
  5229. "shape-rendering": s.antialias ? null : "crispEdges",
  5230. "pointer-events": s.events,
  5231. "cursor": s.cursor,
  5232. "d": "M" + d.join("ZM") + "Z",
  5233. "fill": fill.color,
  5234. "fill-opacity": fill.opacity || null,
  5235. "stroke": stroke.color,
  5236. "stroke-opacity": stroke.opacity || null,
  5237. "stroke-width": stroke.opacity ? s.lineWidth / this.scale : null
  5238. });
  5239. return this.append(e, scenes, 0);
  5240. };
  5241. pv.SvgScene.areaSegment = function(scenes) {
  5242. var e = scenes.$g.firstChild, s = scenes[0], pathsT, pathsB;
  5243. if (s.interpolate == "basis"
  5244. || s.interpolate == "cardinal"
  5245. || s.interpolate == "monotone") {
  5246. var pointsT = [], pointsB = [];
  5247. for (var i = 0, n = scenes.length; i < n; i++) {
  5248. var sj = scenes[n - i - 1];
  5249. pointsT.push(scenes[i]);
  5250. pointsB.push({left: sj.left + sj.width, top: sj.top + sj.height});
  5251. }
  5252. if (s.interpolate == "basis") {
  5253. pathsT = this.curveBasisSegments(pointsT);
  5254. pathsB = this.curveBasisSegments(pointsB);
  5255. } else if (s.interpolate == "cardinal") {
  5256. pathsT = this.curveCardinalSegments(pointsT, s.tension);
  5257. pathsB = this.curveCardinalSegments(pointsB, s.tension);
  5258. } else { // monotone
  5259. pathsT = this.curveMonotoneSegments(pointsT);
  5260. pathsB = this.curveMonotoneSegments(pointsB);
  5261. }
  5262. }
  5263. for (var i = 0, n = scenes.length - 1; i < n; i++) {
  5264. var s1 = scenes[i], s2 = scenes[i + 1];
  5265. /* visible */
  5266. if (!s1.visible || !s2.visible) continue;
  5267. var fill = s1.fillStyle, stroke = s1.strokeStyle;
  5268. if (!fill.opacity && !stroke.opacity) continue;
  5269. var d;
  5270. if (pathsT) {
  5271. var pathT = pathsT[i],
  5272. pathB = "L" + pathsB[n - i - 1].substr(1);
  5273. d = pathT + pathB + "Z";
  5274. } else {
  5275. /* interpolate */
  5276. var si = s1, sj = s2;
  5277. switch (s1.interpolate) {
  5278. case "step-before": si = s2; break;
  5279. case "step-after": sj = s1; break;
  5280. }
  5281. /* path */
  5282. d = "M" + s1.left + "," + si.top
  5283. + "L" + s2.left + "," + sj.top
  5284. + "L" + (s2.left + s2.width) + "," + (sj.top + sj.height)
  5285. + "L" + (s1.left + s1.width) + "," + (si.top + si.height)
  5286. + "Z";
  5287. }
  5288. e = this.expect(e, "path", {
  5289. "shape-rendering": s1.antialias ? null : "crispEdges",
  5290. "pointer-events": s1.events,
  5291. "cursor": s1.cursor,
  5292. "d": d,
  5293. "fill": fill.color,
  5294. "fill-opacity": fill.opacity || null,
  5295. "stroke": stroke.color,
  5296. "stroke-opacity": stroke.opacity || null,
  5297. "stroke-width": stroke.opacity ? s1.lineWidth / this.scale : null
  5298. });
  5299. e = this.append(e, scenes, i);
  5300. }
  5301. return e;
  5302. };
  5303. pv.SvgScene.bar = function(scenes) {
  5304. var e = scenes.$g.firstChild;
  5305. for (var i = 0; i < scenes.length; i++) {
  5306. var s = scenes[i];
  5307. /* visible */
  5308. if (!s.visible) continue;
  5309. var fill = s.fillStyle, stroke = s.strokeStyle;
  5310. if (!fill.opacity && !stroke.opacity) continue;
  5311. e = this.expect(e, "rect", {
  5312. "shape-rendering": s.antialias ? null : "crispEdges",
  5313. "pointer-events": s.events,
  5314. "cursor": s.cursor,
  5315. "x": s.left,
  5316. "y": s.top,
  5317. "width": Math.max(1E-10, s.width),
  5318. "height": Math.max(1E-10, s.height),
  5319. "fill": fill.color,
  5320. "fill-opacity": fill.opacity || null,
  5321. "stroke": stroke.color,
  5322. "stroke-opacity": stroke.opacity || null,
  5323. "stroke-width": stroke.opacity ? s.lineWidth / this.scale : null
  5324. });
  5325. e = this.append(e, scenes, i);
  5326. }
  5327. return e;
  5328. };
  5329. pv.SvgScene.dot = function(scenes) {
  5330. var e = scenes.$g.firstChild;
  5331. for (var i = 0; i < scenes.length; i++) {
  5332. var s = scenes[i];
  5333. /* visible */
  5334. if (!s.visible) continue;
  5335. var fill = s.fillStyle, stroke = s.strokeStyle;
  5336. if (!fill.opacity && !stroke.opacity) continue;
  5337. /* points */
  5338. var radius = s.radius, path = null;
  5339. switch (s.shape) {
  5340. case "cross": {
  5341. path = "M" + -radius + "," + -radius
  5342. + "L" + radius + "," + radius
  5343. + "M" + radius + "," + -radius
  5344. + "L" + -radius + "," + radius;
  5345. break;
  5346. }
  5347. case "triangle": {
  5348. var h = radius, w = radius * 1.1547; // 2 / Math.sqrt(3)
  5349. path = "M0," + h
  5350. + "L" + w +"," + -h
  5351. + " " + -w + "," + -h
  5352. + "Z";
  5353. break;
  5354. }
  5355. case "diamond": {
  5356. radius *= Math.SQRT2;
  5357. path = "M0," + -radius
  5358. + "L" + radius + ",0"
  5359. + " 0," + radius
  5360. + " " + -radius + ",0"
  5361. + "Z";
  5362. break;
  5363. }
  5364. case "square": {
  5365. path = "M" + -radius + "," + -radius
  5366. + "L" + radius + "," + -radius
  5367. + " " + radius + "," + radius
  5368. + " " + -radius + "," + radius
  5369. + "Z";
  5370. break;
  5371. }
  5372. case "tick": {
  5373. path = "M0,0L0," + -s.size;
  5374. break;
  5375. }
  5376. case "bar": {
  5377. path = "M0," + (s.size / 2) + "L0," + -(s.size / 2);
  5378. break;
  5379. }
  5380. }
  5381. /* Use <circle> for circles, <path> for everything else. */
  5382. var svg = {
  5383. "shape-rendering": s.antialias ? null : "crispEdges",
  5384. "pointer-events": s.events,
  5385. "cursor": s.cursor,
  5386. "fill": fill.color,
  5387. "fill-opacity": fill.opacity || null,
  5388. "stroke": stroke.color,
  5389. "stroke-opacity": stroke.opacity || null,
  5390. "stroke-width": stroke.opacity ? s.lineWidth / this.scale : null
  5391. };
  5392. if (path) {
  5393. svg.transform = "translate(" + s.left + "," + s.top + ")";
  5394. if (s.angle) svg.transform += " rotate(" + 180 * s.angle / Math.PI + ")";
  5395. svg.d = path;
  5396. e = this.expect(e, "path", svg);
  5397. } else {
  5398. svg.cx = s.left;
  5399. svg.cy = s.top;
  5400. svg.r = radius;
  5401. e = this.expect(e, "circle", svg);
  5402. }
  5403. e = this.append(e, scenes, i);
  5404. }
  5405. return e;
  5406. };
  5407. pv.SvgScene.image = function(scenes) {
  5408. var e = scenes.$g.firstChild;
  5409. for (var i = 0; i < scenes.length; i++) {
  5410. var s = scenes[i];
  5411. /* visible */
  5412. if (!s.visible) continue;
  5413. /* fill */
  5414. e = this.fill(e, scenes, i);
  5415. /* image */
  5416. if (s.image) {
  5417. e = this.expect(e, "foreignObject", {
  5418. "cursor": s.cursor,
  5419. "x": s.left,
  5420. "y": s.top,
  5421. "width": s.width,
  5422. "height": s.height
  5423. });
  5424. var c = e.firstChild || e.appendChild(document.createElementNS(this.xhtml, "canvas"));
  5425. c.$scene = {scenes:scenes, index:i};
  5426. c.style.width = s.width;
  5427. c.style.height = s.height;
  5428. c.width = s.imageWidth;
  5429. c.height = s.imageHeight;
  5430. c.getContext("2d").putImageData(s.image, 0, 0);
  5431. } else {
  5432. e = this.expect(e, "image", {
  5433. "preserveAspectRatio": "none",
  5434. "cursor": s.cursor,
  5435. "x": s.left,
  5436. "y": s.top,
  5437. "width": s.width,
  5438. "height": s.height
  5439. });
  5440. e.setAttributeNS(this.xlink, "href", s.url);
  5441. }
  5442. e = this.append(e, scenes, i);
  5443. /* stroke */
  5444. e = this.stroke(e, scenes, i);
  5445. }
  5446. return e;
  5447. };
  5448. pv.SvgScene.label = function(scenes) {
  5449. var e = scenes.$g.firstChild;
  5450. for (var i = 0; i < scenes.length; i++) {
  5451. var s = scenes[i];
  5452. /* visible */
  5453. if (!s.visible) continue;
  5454. var fill = s.textStyle;
  5455. if (!fill.opacity || !s.text) continue;
  5456. /* text-baseline, text-align */
  5457. var x = 0, y = 0, dy = 0, anchor = "start";
  5458. switch (s.textBaseline) {
  5459. case "middle": dy = ".35em"; break;
  5460. case "top": dy = ".71em"; y = s.textMargin; break;
  5461. case "bottom": y = "-" + s.textMargin; break;
  5462. }
  5463. switch (s.textAlign) {
  5464. case "right": anchor = "end"; x = "-" + s.textMargin; break;
  5465. case "center": anchor = "middle"; break;
  5466. case "left": x = s.textMargin; break;
  5467. }
  5468. e = this.expect(e, "text", {
  5469. "pointer-events": s.events,
  5470. "cursor": s.cursor,
  5471. "x": x,
  5472. "y": y,
  5473. "dy": dy,
  5474. "transform": "translate(" + s.left + "," + s.top + ")"
  5475. + (s.textAngle ? " rotate(" + 180 * s.textAngle / Math.PI + ")" : "")
  5476. + (this.scale != 1 ? " scale(" + 1 / this.scale + ")" : ""),
  5477. "fill": fill.color,
  5478. "fill-opacity": fill.opacity || null,
  5479. "text-anchor": anchor
  5480. }, {
  5481. "font": s.font,
  5482. "text-shadow": s.textShadow,
  5483. "text-decoration": s.textDecoration
  5484. });
  5485. if (e.firstChild) e.firstChild.nodeValue = s.text;
  5486. else e.appendChild(document.createTextNode(s.text));
  5487. e = this.append(e, scenes, i);
  5488. }
  5489. return e;
  5490. };
  5491. pv.SvgScene.line = function(scenes) {
  5492. var e = scenes.$g.firstChild;
  5493. if (scenes.length < 2) return e;
  5494. var s = scenes[0];
  5495. /* segmented */
  5496. if (s.segmented) return this.lineSegment(scenes);
  5497. /* visible */
  5498. if (!s.visible) return e;
  5499. var fill = s.fillStyle, stroke = s.strokeStyle;
  5500. if (!fill.opacity && !stroke.opacity) return e;
  5501. /* points */
  5502. var d = "M" + s.left + "," + s.top;
  5503. if (scenes.length > 2 && (s.interpolate == "basis" || s.interpolate == "cardinal" || s.interpolate == "monotone")) {
  5504. switch (s.interpolate) {
  5505. case "basis": d += this.curveBasis(scenes); break;
  5506. case "cardinal": d += this.curveCardinal(scenes, s.tension); break;
  5507. case "monotone": d += this.curveMonotone(scenes); break;
  5508. }
  5509. } else {
  5510. for (var i = 1; i < scenes.length; i++) {
  5511. d += this.pathSegment(scenes[i - 1], scenes[i]);
  5512. }
  5513. }
  5514. e = this.expect(e, "path", {
  5515. "shape-rendering": s.antialias ? null : "crispEdges",
  5516. "pointer-events": s.events,
  5517. "cursor": s.cursor,
  5518. "d": d,
  5519. "fill": fill.color,
  5520. "fill-opacity": fill.opacity || null,
  5521. "stroke": stroke.color,
  5522. "stroke-opacity": stroke.opacity || null,
  5523. "stroke-width": stroke.opacity ? s.lineWidth / this.scale : null,
  5524. "stroke-linejoin": s.lineJoin
  5525. });
  5526. return this.append(e, scenes, 0);
  5527. };
  5528. pv.SvgScene.lineSegment = function(scenes) {
  5529. var e = scenes.$g.firstChild;
  5530. var s = scenes[0];
  5531. var paths;
  5532. switch (s.interpolate) {
  5533. case "basis": paths = this.curveBasisSegments(scenes); break;
  5534. case "cardinal": paths = this.curveCardinalSegments(scenes, s.tension); break;
  5535. case "monotone": paths = this.curveMonotoneSegments(scenes); break;
  5536. }
  5537. for (var i = 0, n = scenes.length - 1; i < n; i++) {
  5538. var s1 = scenes[i], s2 = scenes[i + 1];
  5539. /* visible */
  5540. if (!s1.visible || !s2.visible) continue;
  5541. var stroke = s1.strokeStyle, fill = pv.Color.transparent;
  5542. if (!stroke.opacity) continue;
  5543. /* interpolate */
  5544. var d;
  5545. if ((s1.interpolate == "linear") && (s1.lineJoin == "miter")) {
  5546. fill = stroke;
  5547. stroke = pv.Color.transparent;
  5548. d = this.pathJoin(scenes[i - 1], s1, s2, scenes[i + 2]);
  5549. } else if(paths) {
  5550. d = paths[i];
  5551. } else {
  5552. d = "M" + s1.left + "," + s1.top + this.pathSegment(s1, s2);
  5553. }
  5554. e = this.expect(e, "path", {
  5555. "shape-rendering": s1.antialias ? null : "crispEdges",
  5556. "pointer-events": s1.events,
  5557. "cursor": s1.cursor,
  5558. "d": d,
  5559. "fill": fill.color,
  5560. "fill-opacity": fill.opacity || null,
  5561. "stroke": stroke.color,
  5562. "stroke-opacity": stroke.opacity || null,
  5563. "stroke-width": stroke.opacity ? s1.lineWidth / this.scale : null,
  5564. "stroke-linejoin": s1.lineJoin
  5565. });
  5566. e = this.append(e, scenes, i);
  5567. }
  5568. return e;
  5569. };
  5570. /** @private Returns the path segment for the specified points. */
  5571. pv.SvgScene.pathSegment = function(s1, s2) {
  5572. var l = 1; // sweep-flag
  5573. switch (s1.interpolate) {
  5574. case "polar-reverse":
  5575. l = 0;
  5576. case "polar": {
  5577. var dx = s2.left - s1.left,
  5578. dy = s2.top - s1.top,
  5579. e = 1 - s1.eccentricity,
  5580. r = Math.sqrt(dx * dx + dy * dy) / (2 * e);
  5581. if ((e <= 0) || (e > 1)) break; // draw a straight line
  5582. return "A" + r + "," + r + " 0 0," + l + " " + s2.left + "," + s2.top;
  5583. }
  5584. case "step-before": return "V" + s2.top + "H" + s2.left;
  5585. case "step-after": return "H" + s2.left + "V" + s2.top;
  5586. }
  5587. return "L" + s2.left + "," + s2.top;
  5588. };
  5589. /** @private Line-line intersection, per Akenine-Moller 16.16.1. */
  5590. pv.SvgScene.lineIntersect = function(o1, d1, o2, d2) {
  5591. return o1.plus(d1.times(o2.minus(o1).dot(d2.perp()) / d1.dot(d2.perp())));
  5592. }
  5593. /** @private Returns the miter join path for the specified points. */
  5594. pv.SvgScene.pathJoin = function(s0, s1, s2, s3) {
  5595. /*
  5596. * P1-P2 is the current line segment. V is a vector that is perpendicular to
  5597. * the line segment, and has length lineWidth / 2. ABCD forms the initial
  5598. * bounding box of the line segment (i.e., the line segment if we were to do
  5599. * no joins).
  5600. */
  5601. var p1 = pv.vector(s1.left, s1.top),
  5602. p2 = pv.vector(s2.left, s2.top),
  5603. p = p2.minus(p1),
  5604. v = p.perp().norm(),
  5605. w = v.times(s1.lineWidth / (2 * this.scale)),
  5606. a = p1.plus(w),
  5607. b = p2.plus(w),
  5608. c = p2.minus(w),
  5609. d = p1.minus(w);
  5610. /*
  5611. * Start join. P0 is the previous line segment's start point. We define the
  5612. * cutting plane as the average of the vector perpendicular to P0-P1, and
  5613. * the vector perpendicular to P1-P2. This insures that the cross-section of
  5614. * the line on the cutting plane is equal if the line-width is unchanged.
  5615. * Note that we don't implement miter limits, so these can get wild.
  5616. */
  5617. if (s0 && s0.visible) {
  5618. var v1 = p1.minus(s0.left, s0.top).perp().norm().plus(v);
  5619. d = this.lineIntersect(p1, v1, d, p);
  5620. a = this.lineIntersect(p1, v1, a, p);
  5621. }
  5622. /* Similarly, for end join. */
  5623. if (s3 && s3.visible) {
  5624. var v2 = pv.vector(s3.left, s3.top).minus(p2).perp().norm().plus(v);
  5625. c = this.lineIntersect(p2, v2, c, p);
  5626. b = this.lineIntersect(p2, v2, b, p);
  5627. }
  5628. return "M" + a.x + "," + a.y
  5629. + "L" + b.x + "," + b.y
  5630. + " " + c.x + "," + c.y
  5631. + " " + d.x + "," + d.y;
  5632. };
  5633. pv.SvgScene.panel = function(scenes) {
  5634. var g = scenes.$g, e = g && g.firstChild;
  5635. for (var i = 0; i < scenes.length; i++) {
  5636. var s = scenes[i];
  5637. /* visible */
  5638. if (!s.visible) continue;
  5639. /* svg */
  5640. if (!scenes.parent) {
  5641. s.canvas.style.display = "inline-block";
  5642. if (g && (g.parentNode != s.canvas)) {
  5643. g = s.canvas.firstChild;
  5644. e = g && g.firstChild;
  5645. }
  5646. if (!g) {
  5647. g = s.canvas.appendChild(this.create("svg"));
  5648. g.setAttribute("font-size", "10px");
  5649. g.setAttribute("font-family", "sans-serif");
  5650. g.setAttribute("fill", "none");
  5651. g.setAttribute("stroke", "none");
  5652. g.setAttribute("stroke-width", 1.5);
  5653. for (var j = 0; j < this.events.length; j++) {
  5654. g.addEventListener(this.events[j], this.dispatch, false);
  5655. }
  5656. e = g.firstChild;
  5657. }
  5658. scenes.$g = g;
  5659. g.setAttribute("width", s.width + s.left + s.right);
  5660. g.setAttribute("height", s.height + s.top + s.bottom);
  5661. }
  5662. /* clip (nest children) */
  5663. if (s.overflow == "hidden") {
  5664. var id = pv.id().toString(36),
  5665. c = this.expect(e, "g", {"clip-path": "url(#" + id + ")"});
  5666. if (!c.parentNode) g.appendChild(c);
  5667. scenes.$g = g = c;
  5668. e = c.firstChild;
  5669. e = this.expect(e, "clipPath", {"id": id});
  5670. var r = e.firstChild || e.appendChild(this.create("rect"));
  5671. r.setAttribute("x", s.left);
  5672. r.setAttribute("y", s.top);
  5673. r.setAttribute("width", s.width);
  5674. r.setAttribute("height", s.height);
  5675. if (!e.parentNode) g.appendChild(e);
  5676. e = e.nextSibling;
  5677. }
  5678. /* fill */
  5679. e = this.fill(e, scenes, i);
  5680. /* transform (push) */
  5681. var k = this.scale,
  5682. t = s.transform,
  5683. x = s.left + t.x,
  5684. y = s.top + t.y;
  5685. this.scale *= t.k;
  5686. /* children */
  5687. for (var j = 0; j < s.children.length; j++) {
  5688. s.children[j].$g = e = this.expect(e, "g", {
  5689. "transform": "translate(" + x + "," + y + ")"
  5690. + (t.k != 1 ? " scale(" + t.k + ")" : "")
  5691. });
  5692. this.updateAll(s.children[j]);
  5693. if (!e.parentNode) g.appendChild(e);
  5694. e = e.nextSibling;
  5695. }
  5696. /* transform (pop) */
  5697. this.scale = k;
  5698. /* stroke */
  5699. e = this.stroke(e, scenes, i);
  5700. /* clip (restore group) */
  5701. if (s.overflow == "hidden") {
  5702. scenes.$g = g = c.parentNode;
  5703. e = c.nextSibling;
  5704. }
  5705. }
  5706. return e;
  5707. };
  5708. pv.SvgScene.fill = function(e, scenes, i) {
  5709. var s = scenes[i], fill = s.fillStyle;
  5710. if (fill.opacity || s.events == "all") {
  5711. e = this.expect(e, "rect", {
  5712. "shape-rendering": s.antialias ? null : "crispEdges",
  5713. "pointer-events": s.events,
  5714. "cursor": s.cursor,
  5715. "x": s.left,
  5716. "y": s.top,
  5717. "width": s.width,
  5718. "height": s.height,
  5719. "fill": fill.color,
  5720. "fill-opacity": fill.opacity,
  5721. "stroke": null
  5722. });
  5723. e = this.append(e, scenes, i);
  5724. }
  5725. return e;
  5726. };
  5727. pv.SvgScene.stroke = function(e, scenes, i) {
  5728. var s = scenes[i], stroke = s.strokeStyle;
  5729. if (stroke.opacity || s.events == "all") {
  5730. e = this.expect(e, "rect", {
  5731. "shape-rendering": s.antialias ? null : "crispEdges",
  5732. "pointer-events": s.events == "all" ? "stroke" : s.events,
  5733. "cursor": s.cursor,
  5734. "x": s.left,
  5735. "y": s.top,
  5736. "width": Math.max(1E-10, s.width),
  5737. "height": Math.max(1E-10, s.height),
  5738. "fill": null,
  5739. "stroke": stroke.color,
  5740. "stroke-opacity": stroke.opacity,
  5741. "stroke-width": s.lineWidth / this.scale
  5742. });
  5743. e = this.append(e, scenes, i);
  5744. }
  5745. return e;
  5746. };
  5747. pv.SvgScene.rule = function(scenes) {
  5748. var e = scenes.$g.firstChild;
  5749. for (var i = 0; i < scenes.length; i++) {
  5750. var s = scenes[i];
  5751. /* visible */
  5752. if (!s.visible) continue;
  5753. var stroke = s.strokeStyle;
  5754. if (!stroke.opacity) continue;
  5755. e = this.expect(e, "line", {
  5756. "shape-rendering": s.antialias ? null : "crispEdges",
  5757. "pointer-events": s.events,
  5758. "cursor": s.cursor,
  5759. "x1": s.left,
  5760. "y1": s.top,
  5761. "x2": s.left + s.width,
  5762. "y2": s.top + s.height,
  5763. "stroke": stroke.color,
  5764. "stroke-opacity": stroke.opacity,
  5765. "stroke-width": s.lineWidth / this.scale
  5766. });
  5767. e = this.append(e, scenes, i);
  5768. }
  5769. return e;
  5770. };
  5771. pv.SvgScene.wedge = function(scenes) {
  5772. var e = scenes.$g.firstChild;
  5773. for (var i = 0; i < scenes.length; i++) {
  5774. var s = scenes[i];
  5775. /* visible */
  5776. if (!s.visible) continue;
  5777. var fill = s.fillStyle, stroke = s.strokeStyle;
  5778. if (!fill.opacity && !stroke.opacity) continue;
  5779. /* points */
  5780. var r1 = s.innerRadius, r2 = s.outerRadius, a = Math.abs(s.angle), p;
  5781. if (a >= 2 * Math.PI) {
  5782. if (r1) {
  5783. p = "M0," + r2
  5784. + "A" + r2 + "," + r2 + " 0 1,1 0," + (-r2)
  5785. + "A" + r2 + "," + r2 + " 0 1,1 0," + r2
  5786. + "M0," + r1
  5787. + "A" + r1 + "," + r1 + " 0 1,1 0," + (-r1)
  5788. + "A" + r1 + "," + r1 + " 0 1,1 0," + r1
  5789. + "Z";
  5790. } else {
  5791. p = "M0," + r2
  5792. + "A" + r2 + "," + r2 + " 0 1,1 0," + (-r2)
  5793. + "A" + r2 + "," + r2 + " 0 1,1 0," + r2
  5794. + "Z";
  5795. }
  5796. } else {
  5797. var sa = Math.min(s.startAngle, s.endAngle),
  5798. ea = Math.max(s.startAngle, s.endAngle),
  5799. c1 = Math.cos(sa), c2 = Math.cos(ea),
  5800. s1 = Math.sin(sa), s2 = Math.sin(ea);
  5801. if (r1) {
  5802. p = "M" + r2 * c1 + "," + r2 * s1
  5803. + "A" + r2 + "," + r2 + " 0 "
  5804. + ((a < Math.PI) ? "0" : "1") + ",1 "
  5805. + r2 * c2 + "," + r2 * s2
  5806. + "L" + r1 * c2 + "," + r1 * s2
  5807. + "A" + r1 + "," + r1 + " 0 "
  5808. + ((a < Math.PI) ? "0" : "1") + ",0 "
  5809. + r1 * c1 + "," + r1 * s1 + "Z";
  5810. } else {
  5811. p = "M" + r2 * c1 + "," + r2 * s1
  5812. + "A" + r2 + "," + r2 + " 0 "
  5813. + ((a < Math.PI) ? "0" : "1") + ",1 "
  5814. + r2 * c2 + "," + r2 * s2 + "L0,0Z";
  5815. }
  5816. }
  5817. e = this.expect(e, "path", {
  5818. "shape-rendering": s.antialias ? null : "crispEdges",
  5819. "pointer-events": s.events,
  5820. "cursor": s.cursor,
  5821. "transform": "translate(" + s.left + "," + s.top + ")",
  5822. "d": p,
  5823. "fill": fill.color,
  5824. "fill-rule": "evenodd",
  5825. "fill-opacity": fill.opacity || null,
  5826. "stroke": stroke.color,
  5827. "stroke-opacity": stroke.opacity || null,
  5828. "stroke-width": stroke.opacity ? s.lineWidth / this.scale : null
  5829. });
  5830. e = this.append(e, scenes, i);
  5831. }
  5832. return e;
  5833. };
  5834. /**
  5835. *
  5836. */
  5837. pv.VmlScene = {};
  5838. /**
  5839. *
  5840. */
  5841. pv.VmlScene.init = function() {
  5842. ["group", "shape", "path", "fill", "stroke",
  5843. "polyline", "rect", "image", "textpath", "line"].forEach(function(e) {
  5844. document.createStyleSheet().addRule("v\\:" + e, "behavior:url(#default#VML);display:inline-block");
  5845. });
  5846. document.namespaces.add("v", "urn:schemas-microsoft-com:vml");
  5847. this.init = function() {};
  5848. };
  5849. /**
  5850. *
  5851. */
  5852. pv.VmlScene.create = function(type, parent) {
  5853. this.init();
  5854. var e = document.createElement(type);
  5855. if (parent)
  5856. parent.appendChild(e);
  5857. return e;
  5858. };
  5859. /**
  5860. * Expects the element <i>e</i> to be the specified type. If the element does
  5861. * not exist, a new one is created. If the element does exist but is the wrong
  5862. * type, it is replaced with the specified element.
  5863. *
  5864. * @param type {string} a VML element type, such as "v:group".
  5865. * @return a new VML element.
  5866. */
  5867. pv.VmlScene.expect = function(type, e, parent) {
  5868. if (!e) return this.create(type, parent);
  5869. if ("v:" + e.tagName == type) return e;
  5870. var n = this.create(type);
  5871. e.parentNode.replaceChild(n, e);
  5872. return n;
  5873. };
  5874. /** TODO */
  5875. pv.VmlScene.append = function(e, scenes, index) {
  5876. e.$scene = {scenes:scenes, index:index};
  5877. if (!e.parentNode || e.parentNode.nodeType == 11)
  5878. scenes.$g.appendChild(e);
  5879. return e.nextSibling;
  5880. };
  5881. /** TODO */
  5882. pv.VmlScene.dispatch = pv.listener(function(e) {
  5883. var t = e.srcElement.$scene;
  5884. if (t) {
  5885. var type = e.type;
  5886. /* TODO: mousewheel fixes? */
  5887. if (pv.Mark.dispatch(type, t.scenes, t.index)) e.returnValue = false;
  5888. }
  5889. });
  5890. pv.VmlScene.area = function(scenes) {
  5891. var e = scenes.$g.firstChild;
  5892. if (!scenes.length) return e;
  5893. var s = scenes[0];
  5894. /* segmented */
  5895. if (s.segmented) return this.areaSegment(scenes);
  5896. /* visible */
  5897. if (!s.visible) return e;
  5898. var fill = s.fillStyle, stroke = s.strokeStyle;
  5899. if (!fill.opacity && !stroke.opacity) return e;
  5900. /* points */
  5901. var p = "";
  5902. for (var i = 0; i < scenes.length; i++) {
  5903. var si = scenes[i];
  5904. p += si.left + "," + si.top + " ";
  5905. }
  5906. for (var j = scenes.length - 1; j >= 0; j--) {
  5907. var sj = scenes[j];
  5908. p += (sj.left + sj.width) + "," + (sj.top + sj.height) + " ";
  5909. }
  5910. e = this.expect("v:polyline", e);
  5911. var vml = {root: e};
  5912. vml.fill = this.expect("v:fill", vml.root.firstChild, vml.root);
  5913. vml.stroke = this.expect("v:stroke", vml.fill.nextSibling, vml.root);
  5914. /* polygon */
  5915. vml.root.style.cursor = s.cursor;
  5916. vml.root.style.antialias = s.antialias;
  5917. vml.root.title = s.title || "";
  5918. // Changing the 'points' attribute produces the error "Object doesn't
  5919. // support this property or method" when the node is in the DOM. Remove
  5920. // it; we'll add it back at the end.
  5921. if (vml.root.parentNode)
  5922. vml.root.parentNode.removeChild(vml.root);
  5923. vml.root.points = p;
  5924. vml.fill.color = fill.color;
  5925. vml.fill.opacity = fill.opacity;
  5926. vml.stroke.color = stroke.color;
  5927. vml.stroke.opacity = stroke.opacity * Math.min(s.lineWidth, 1);
  5928. vml.stroke.weight = s.lineWidth + "px";
  5929. return this.append(e, scenes, 0);
  5930. };
  5931. pv.VmlScene.bar = function(scenes) {
  5932. var e = scenes.$g.firstChild;
  5933. for (var i = 0; i < scenes.length; i++) {
  5934. var s = scenes[i];
  5935. /* visible */
  5936. if (!s.visible) continue;
  5937. var fill = s.fillStyle, stroke = s.strokeStyle;
  5938. if (!fill.opacity && !stroke.opacity) continue;
  5939. e = this.expect("v:rect", e);
  5940. var vml = {root: e};
  5941. vml.fill = this.expect("v:fill", vml.root.firstChild, vml.root);
  5942. vml.stroke = this.expect("v:stroke", vml.fill.nextSibling, vml.root);
  5943. vml.root.style.left = s.left;
  5944. vml.root.style.top = s.top;
  5945. vml.root.style.width = s.width;
  5946. vml.root.style.height = s.height;
  5947. vml.root.style.cursor = s.cursor;
  5948. vml.root.style.antialias = s.antialias;
  5949. vml.root.title = s.title || "";
  5950. vml.fill.color = fill.color;
  5951. vml.fill.opacity = fill.opacity;
  5952. vml.stroke.color = stroke.color;
  5953. vml.stroke.opacity = stroke.opacity * Math.min(s.lineWidth, 1);
  5954. vml.stroke.weight = s.lineWidth + "px";
  5955. e = this.append(e, scenes, i);
  5956. }
  5957. return e;
  5958. };
  5959. pv.VmlScene.dot = function(scenes) {
  5960. var e = scenes.$g.firstChild;
  5961. for (var i = 0; i < scenes.length; i++) {
  5962. var s = scenes[i];
  5963. /* visible */
  5964. if (!s.visible) continue;
  5965. var fill = s.fillStyle, stroke = s.strokeStyle;
  5966. if (!fill.opacity && !stroke.opacity) continue;
  5967. /* points */
  5968. var radius = Math.round(s.radius);
  5969. var d;
  5970. switch (s.shape) {
  5971. case "cross": {
  5972. d = "m" + -radius + "," + -radius
  5973. + "l" + radius + "," + radius
  5974. + "m" + radius + "," + -radius
  5975. + "l" + -radius + "," + radius;
  5976. break;
  5977. }
  5978. case "triangle": {
  5979. var h = radius, w = Math.round(radius * 1.1547); // 2 / Math.sqrt(3)
  5980. d = "m0," + h
  5981. + "l" + w +"," + -h
  5982. + " " + -w + "," + -h
  5983. + "x";
  5984. break;
  5985. }
  5986. case "diamond": {
  5987. radius = Math.round(radius * 1.414214); // Math.sqrt(2)
  5988. d = "m0," + -radius
  5989. + "l" + radius + ",0"
  5990. + " 0," + radius
  5991. + " " + -radius + ",0"
  5992. + "x";
  5993. break;
  5994. }
  5995. case "square": {
  5996. d = "m" + -radius + "," + -radius
  5997. + "l" + radius + "," + -radius
  5998. + " " + radius + "," + radius
  5999. + " " + -radius + "," + radius
  6000. + "x";
  6001. break;
  6002. }
  6003. case "tick": {
  6004. d = "m0,0l0," + -Math.round(s.size);
  6005. break;
  6006. }
  6007. default: { // circle
  6008. d = "ar-" + radius + ",-" + radius + "," + radius + "," + radius + ",0,0,0,0x";
  6009. break;
  6010. }
  6011. }
  6012. e = this.expect("v:group", e);
  6013. var vml = {root: e};
  6014. vml.shape = this.expect("v:shape", vml.root.firstChild, vml.root);
  6015. vml.path = this.expect("v:path", vml.shape.firstChild, vml.shape);
  6016. vml.fill = this.expect("v:fill", vml.path.nextSibling, vml.shape);
  6017. vml.stroke = this.expect("v:stroke", vml.fill.nextSibling, vml.shape);
  6018. var parent = scenes.parent[scenes.parentIndex];
  6019. /*
  6020. * This total awkwardness is because VML rotates around what it perceives to
  6021. * be the center axis of the shape. The rotation is applied to a containing
  6022. * group, and then I use offsets to undo the cludge.
  6023. */
  6024. /* root + shape */
  6025. var a = s.angle;
  6026. if (a) {
  6027. var x = s.left, y = s.top;
  6028. vml.shape.style.left = Math.cos(-a) * x - Math.sin(-a) * y;
  6029. vml.shape.style.top = Math.sin(-a) * x + Math.cos(-a) * y;
  6030. vml.root.style.left = -parent.width / 2;
  6031. vml.root.style.top = -parent.height / 2;
  6032. vml.root.style.rotation = 180 * a / Math.PI;
  6033. vml.shape.style.marginLeft = parent.width / 2;
  6034. vml.shape.style.marginTop = parent.height / 2;
  6035. } else {
  6036. vml.root.style.rotation = "";
  6037. vml.shape.style.left = s.left;
  6038. vml.shape.style.top = s.top;
  6039. }
  6040. vml.root.style.width = parent.width;
  6041. vml.root.style.height = parent.height;
  6042. vml.shape.style.width = parent.width;
  6043. vml.shape.style.height = parent.height;
  6044. vml.shape.style.cursor = s.cursor;
  6045. vml.shape.style.antialias = s.antialias;
  6046. vml.shape.title = s.title || "";
  6047. /* path */
  6048. vml.path.v = d;
  6049. vml.fill.color = fill.color;
  6050. vml.fill.opacity = fill.opacity;
  6051. vml.stroke.color = stroke.color;
  6052. vml.stroke.opacity = stroke.opacity * Math.min(s.lineWidth, 1);
  6053. vml.stroke.weight = s.lineWidth + "px";
  6054. e = this.append(e, scenes, i);
  6055. }
  6056. return e;
  6057. };
  6058. pv.VmlScene.image = function(scenes) {
  6059. var e = scenes.$g.firstChild;
  6060. for (var i = 0; i < scenes.length; i++) {
  6061. var s = scenes[i];
  6062. /* visible */
  6063. if (!s.visible) continue;
  6064. e = this.expect("v:image", e);
  6065. var vml = {root: e};
  6066. vml.fill = this.expect("v:fill", vml.root.firstChild, vml.root);
  6067. vml.stroke = this.expect("v:stroke", vml.fill.nextSibling, vml.root);
  6068. vml.root.filled = true;
  6069. vml.root.stroked = true;
  6070. vml.root.style.left = s.left;
  6071. vml.root.style.top = s.top;
  6072. vml.root.style.width = s.width;
  6073. vml.root.style.height = s.height;
  6074. vml.root.style.cursor = s.cursor;
  6075. vml.root.src = s.url;
  6076. vml.root.title = s.title || "";
  6077. var fill = s.fillStyle;
  6078. vml.fill.color = fill.color;
  6079. vml.fill.opacity = fill.opacity;
  6080. var stroke = s.strokeStyle;
  6081. vml.stroke.color = stroke.color;
  6082. vml.stroke.opacity = stroke.opacity * Math.min(s.lineWidth, 1);
  6083. vml.stroke.weight = s.lineWidth + "px";
  6084. e = this.append(e, scenes, i);
  6085. }
  6086. return e;
  6087. };
  6088. /* TODO font-size detection for baseline adjustment */
  6089. pv.VmlScene.label = function(scenes) {
  6090. var e = scenes.$g.firstChild;
  6091. for (var i = 0; i < scenes.length; i++) {
  6092. var s = scenes[i];
  6093. /* visible */
  6094. if (!s.visible) continue;
  6095. var fill = s.textStyle;
  6096. if (!fill.opacity || !s.text) continue;
  6097. /* Create VML elements as needed. */
  6098. e = this.expect("v:shape", e);
  6099. var vml = {root: e};
  6100. vml.path = this.expect("v:path", vml.root.firstChild, vml.root);
  6101. vml.fill = this.expect("v:fill", vml.path.nextSibling, vml.root);
  6102. vml.text = this.expect("v:textpath", vml.fill.nextSibling, vml.root);
  6103. vml.root.filled = true;
  6104. vml.root.stroked = false;
  6105. vml.root.style.width = "100%";
  6106. vml.root.style.height = "100%";
  6107. vml.path.textpathok = true;
  6108. vml.text.on = true;
  6109. var dx = 0, dy = 0, size = 10;
  6110. switch (s.textBaseline) {
  6111. case "top": {
  6112. dx = Math.round(-Math.sin(s.textAngle) * size);
  6113. dy = Math.round(Math.cos(s.textAngle) * size);
  6114. break;
  6115. }
  6116. case "bottom": {
  6117. dx = -Math.round(-Math.sin(s.textAngle) * size);
  6118. dy = -Math.round(Math.cos(s.textAngle) * size);
  6119. break;
  6120. }
  6121. }
  6122. vml.root.style.left = s.left + dx;
  6123. vml.root.style.top = s.top + dy;
  6124. vml.fill.color = fill.color;
  6125. vml.fill.opacity = fill.opacity;
  6126. var x = Math.round(Math.cos(s.textAngle) * 1000),
  6127. y = Math.round(Math.sin(s.textAngle) * 1000),
  6128. mx = Math.round(Math.cos(s.textAngle) * s.textMargin),
  6129. my = Math.round(Math.sin(s.textAngle) * s.textMargin),
  6130. p;
  6131. switch (s.textAlign) {
  6132. case "right": {
  6133. p = "M" + -x + "," + -y + "L" + -mx + "," + -my;
  6134. break;
  6135. }
  6136. case "center": {
  6137. p = "M" + -x + "," + -y + "L" + x + "," + y;
  6138. break;
  6139. }
  6140. default: {
  6141. p = "M" + mx + "," + my + "L" + x + "," + y;
  6142. break;
  6143. }
  6144. }
  6145. vml.path.v = p;
  6146. vml.text.style.font = s.font;
  6147. vml.text.style.color = "black";
  6148. vml.text.style.antialias = s.antialias;
  6149. vml.text.style["alignment-baseline"] = "alphabetic";
  6150. vml.text.style["v-text-align"] = s.textAlign;
  6151. vml.text.string = s.text;
  6152. e = this.append(e, scenes, i);
  6153. }
  6154. return e;
  6155. };
  6156. pv.VmlScene.line = function(scenes) {
  6157. var e = scenes.$g.firstChild;
  6158. if (scenes.length < 2) return e;
  6159. var s = scenes[0];
  6160. /* segmented */
  6161. if (s.segmented) return this.lineSegment(scenes);
  6162. /* visible */
  6163. if (!s.visible) return e;
  6164. var fill = s.fillStyle, stroke = s.strokeStyle;
  6165. if (!fill.opacity && !stroke.opacity) return e;
  6166. /* points */
  6167. var p;
  6168. for (var i = 0; i < scenes.length; i++) {
  6169. var si = scenes[i], x = Math.round(si.left), y = Math.round(si.top);
  6170. if (isNaN(x)) x = 0;
  6171. if (isNaN(y)) y = 0;
  6172. if (!p) p = "m" + x + "," + y + "l";
  6173. else p += x + "," + y + " ";
  6174. }
  6175. e = this.expect("v:shape", e);
  6176. var vml = {root: e};
  6177. vml.path = this.expect("v:path", vml.root.firstChild, vml.root);
  6178. vml.fill = this.expect("v:fill", vml.path.nextSibling, vml.root);
  6179. vml.stroke = this.expect("v:stroke", vml.fill.nextSibling, vml.root);
  6180. /* polygon */
  6181. vml.root.style.width = "100%";
  6182. vml.root.style.height = "100%";
  6183. vml.root.style.cursor = s.cursor;
  6184. vml.root.style.antialias = s.antialias;
  6185. vml.root.title = s.title || "";
  6186. vml.path.v = p;
  6187. vml.fill.color = fill.color;
  6188. vml.fill.opacity = fill.opacity;
  6189. vml.stroke.color = stroke.color;
  6190. vml.stroke.opacity = stroke.opacity * Math.min(s.lineWidth, 1);
  6191. vml.stroke.weight = s.lineWidth + "px";
  6192. return this.append(e, scenes, 0);
  6193. };
  6194. /*
  6195. * TODO
  6196. * - optimize: dirty bit
  6197. * - z-index
  6198. */
  6199. pv.VmlScene.panel = function(scenes) {
  6200. var g = scenes.$g, e = g && g.firstChild;
  6201. for (var i = 0; i < scenes.length; i++) {
  6202. var s = scenes[i];
  6203. /* visible */
  6204. if (!s.visible) continue;
  6205. var width = s.width + s.left + s.right;
  6206. var height = s.height + s.top + s.bottom;
  6207. /* vml */
  6208. if (!scenes.parent) {
  6209. s.canvas.style.position = "relative";
  6210. s.canvas.style.display = "inline-block";
  6211. s.canvas.style.width = width;
  6212. s.canvas.style.height = height;
  6213. s.canvas.style.overflow = "hidden";
  6214. g = s.canvas.firstChild;
  6215. if (!g) {
  6216. s.canvas.appendChild(g = this.create("v:group"));
  6217. g.onclick
  6218. = g.onmousedown
  6219. = g.onmouseup
  6220. = g.onmousemove
  6221. = g.onmouseout
  6222. = g.onmouseover
  6223. = pv.VmlScene.dispatch;
  6224. }
  6225. scenes.$g = g;
  6226. g.style.position = "relative";
  6227. g.style.width = width;
  6228. g.style.height = height;
  6229. g.coordsize = width + "," + height;
  6230. g.coordorigin = "0 0";
  6231. // Adjust for 1 pixel VML margin that I can find no other way of removing.
  6232. g.style.top = "-1px";
  6233. g.style.left = "-1px";
  6234. if (typeof e == "undefined") e = g.firstChild;
  6235. }
  6236. // v:group doesn't get the full width and height unless it has
  6237. // an inner shape with full width and height.
  6238. e = this.expect("v:rect", e);
  6239. e.style.position = "absolute";
  6240. e.style.width = width;
  6241. e.style.height = height;
  6242. e.stroked = false;
  6243. e.filled = false;
  6244. e = this.append(e, scenes, i);
  6245. /* fill */
  6246. e = this.fill(e, scenes, i);
  6247. /* children */
  6248. for (var j = 0; j < s.children.length; j++) {
  6249. s.children[j].$g = e = this.expect("v:group", e);
  6250. e.style.position = "absolute";
  6251. e.style.width = s.width;
  6252. e.style.height = s.height;
  6253. e.style.left = s.left;
  6254. e.style.top = s.top;
  6255. e.coordsize = s.width + "," + s.height;
  6256. this.updateAll(s.children[j]);
  6257. if (!e.parentNode || e.parentNode.nodeType == 11) g.appendChild(e);
  6258. e = e.nextSibling;
  6259. }
  6260. /* stroke */
  6261. e = this.stroke(e, scenes, i);
  6262. }
  6263. return e;
  6264. };
  6265. pv.VmlScene.fill = function(e, scenes, i) {
  6266. var s = scenes[i], fill = s.fillStyle;
  6267. if (fill.opacity) {
  6268. e = this.expect("v:rect", e);
  6269. e.style.position = "absolute";
  6270. e.style.left = s.left;
  6271. e.style.top = s.top;
  6272. e.style.width = s.width;
  6273. e.style.height = s.height;
  6274. e.style.cursor = s.cursor;
  6275. e.style.antialias = s.antialias;
  6276. e.stroked = false;
  6277. var c = this.expect("v:fill", e.firstChild, e);
  6278. c.color = fill.color;
  6279. c.opacity = fill.opacity;
  6280. e = this.append(e, scenes, i);
  6281. }
  6282. return e;
  6283. };
  6284. pv.VmlScene.stroke = function(e, scenes, i) {
  6285. var s = scenes[i], stroke = s.strokeStyle;
  6286. if (stroke.opacity) {
  6287. e = this.expect("v:rect", e);
  6288. e.style.position = "absolute";
  6289. e.style.left = s.left;
  6290. e.style.top = s.top;
  6291. e.style.width = s.width;
  6292. e.style.height = s.height;
  6293. e.style.cursor = s.cursor;
  6294. e.style.antialias = s.antialias;
  6295. e.filled = false;
  6296. var c = this.expect("v:stroke", e.firstChild, e);
  6297. c.color = stroke.color;
  6298. c.opacity = stroke.opacity * Math.min(s.lineWidth, 1);
  6299. c.weight = s.lineWidth + "px";
  6300. e = this.append(e, scenes, i);
  6301. }
  6302. return e;
  6303. };
  6304. pv.VmlScene.rule = function(scenes) {
  6305. var e = scenes.$g.firstChild;
  6306. for (var i = 0; i < scenes.length; i++) {
  6307. var s = scenes[i];
  6308. /* visible */
  6309. if (!s.visible) continue;
  6310. var stroke = s.strokeStyle;
  6311. if (!stroke.opacity) continue;
  6312. e = this.expect("v:line", e);
  6313. var vml = {root: e};
  6314. vml.stroke = this.expect("v:stroke", vml.root.firstChild, vml.root);
  6315. /* line */
  6316. vml.root.title = s.title;
  6317. vml.root.style.cursor = s.cursor;
  6318. vml.root.style.antialias = s.antialias;
  6319. vml.root.from = s.left + "," + s.top;
  6320. vml.root.to = (s.left + s.width - (s.width == 0 ? 0 : 1)) + "," + (s.top + s.height - (s.height == 0 ? 0 : 1));
  6321. var color = pv.color(s.strokeStyle);
  6322. vml.stroke.color = color.color;
  6323. vml.stroke.opacity = color.opacity * Math.min(s.lineWidth, 1);
  6324. vml.stroke.weight = s.lineWidth + "px";
  6325. e = this.append(e, scenes, i);
  6326. }
  6327. return e;
  6328. };
  6329. pv.VmlScene.wedge = function(scenes) {
  6330. var e = scenes.$g.firstChild;
  6331. for (var i = 0; i < scenes.length; i++) {
  6332. var s = scenes[i];
  6333. /* visible */
  6334. if (!s.visible) continue;
  6335. var fill = s.fillStyle, stroke = s.strokeStyle;
  6336. if (!fill.opacity && !stroke.opacity) continue;
  6337. /* points */
  6338. var r1 = Math.round(s.innerRadius), r2 = Math.round(s.outerRadius), d;
  6339. if (s.angle >= 2 * Math.PI) {
  6340. if (r1) {
  6341. d = "AE0,0 " + r2 + "," + r2 + " 0 23592960"
  6342. + "AL0,0 " + r1 + "," + r1 + " 0 23592960";
  6343. } else {
  6344. d = "AE0,0 " + r2 + "," + r2 + " 0 23592960";
  6345. }
  6346. } else {
  6347. var sa = Math.round(s.startAngle / Math.PI * 11796480),
  6348. a = Math.round(s.angle / Math.PI * 11796480);
  6349. if (r1) {
  6350. d = "AE 0,0 " + r2 + "," + r2 + " " + -sa + " " + -a
  6351. + " 0,0 " + r1 + "," + r1 + " " + -(sa + a) + " " + a
  6352. + "X";
  6353. } else {
  6354. d = "M0,0"
  6355. + "AE0,0 " + r2 + "," + r2 + " " + -sa + " " + -a
  6356. + "X";
  6357. }
  6358. }
  6359. e = this.expect("v:shape", e);
  6360. var vml = {root: e};
  6361. vml.path = this.expect("v:path", vml.root.firstChild, vml.root);
  6362. vml.fill = this.expect("v:fill", vml.path.nextSibling, vml.root);
  6363. vml.stroke = this.expect("v:stroke", vml.fill.nextSibling, vml.root);
  6364. // vml.root.setAttribute("fill-rule", "evenodd");
  6365. /* path */
  6366. vml.root.style.left = s.left;
  6367. vml.root.style.top = s.top;
  6368. vml.root.style.width = "100%";
  6369. vml.root.style.height = "100%";
  6370. vml.root.style.cursor = s.cursor;
  6371. vml.root.style.antialias = s.antialias;
  6372. vml.root.title = s.title || "";
  6373. vml.fill.color = fill.color;
  6374. vml.fill.opacity = fill.opacity;
  6375. vml.stroke.color = stroke.color;
  6376. vml.stroke.opacity = stroke.opacity * Math.min(s.lineWidth, 1);
  6377. vml.stroke.weight = s.lineWidth + "px";
  6378. vml.path.v = d;
  6379. e = this.append(e, scenes, i);
  6380. }
  6381. return e;
  6382. };
  6383. /**
  6384. * @private
  6385. * @namespace
  6386. */
  6387. pv.Scene = document.implementation.hasFeature(
  6388. "http://www.w3.org/TR/SVG11/feature#BasicStructure", "1.1")
  6389. ? pv.SvgScene : pv.VmlScene;
  6390. /**
  6391. * Updates the display for the specified array of scene nodes.
  6392. *
  6393. * @param scenes {array} an array of scene nodes.
  6394. */
  6395. pv.Scene.updateAll = function(scenes) {
  6396. if (scenes.length
  6397. && scenes[0].reverse
  6398. && (scenes.type != "line")
  6399. && (scenes.type != "area")) {
  6400. var reversed = pv.extend(scenes);
  6401. for (var i = 0, j = scenes.length - 1; j >= 0; i++, j--) {
  6402. reversed[i] = scenes[j];
  6403. }
  6404. scenes = reversed;
  6405. }
  6406. this.removeSiblings(this[scenes.type](scenes));
  6407. };
  6408. /** @private Remove siblings following element <i>e</i>. */
  6409. pv.Scene.removeSiblings = function(e) {
  6410. while (e) {
  6411. var n = e.nextSibling;
  6412. e.parentNode.removeChild(e);
  6413. e = n;
  6414. }
  6415. };
  6416. /**
  6417. * Constructs a new mark with default properties. Marks, with the exception of
  6418. * the root panel, are not typically constructed directly; instead, they are
  6419. * added to a panel or an existing mark via {@link pv.Mark#add}.
  6420. *
  6421. * @class Represents a data-driven graphical mark. The <tt>Mark</tt> class is
  6422. * the base class for all graphical marks in Protovis; it does not provide any
  6423. * specific rendering functionality, but together with {@link Panel} establishes
  6424. * the core framework.
  6425. *
  6426. * <p>Concrete mark types include familiar visual elements such as bars, lines
  6427. * and labels. Although a bar mark may be used to construct a bar chart, marks
  6428. * know nothing about charts; it is only through their specification and
  6429. * composition that charts are produced. These building blocks permit many
  6430. * combinatorial possibilities.
  6431. *
  6432. * <p>Marks are associated with <b>data</b>: a mark is generated once per
  6433. * associated datum, mapping the datum to visual <b>properties</b> such as
  6434. * position and color. Thus, a single mark specification represents a set of
  6435. * visual elements that share the same data and visual encoding. The type of
  6436. * mark defines the names of properties and their meaning. A property may be
  6437. * static, ignoring the associated datum and returning a constant; or, it may be
  6438. * dynamic, derived from the associated datum or index. Such dynamic encodings
  6439. * can be specified succinctly using anonymous functions. Special properties
  6440. * called event handlers can be registered to add interactivity.
  6441. *
  6442. * <p>Protovis uses <b>inheritance</b> to simplify the specification of related
  6443. * marks: a new mark can be derived from an existing mark, inheriting its
  6444. * properties. The new mark can then override properties to specify new
  6445. * behavior, potentially in terms of the old behavior. In this way, the old mark
  6446. * serves as the <b>prototype</b> for the new mark. Most mark types share the
  6447. * same basic properties for consistency and to facilitate inheritance.
  6448. *
  6449. * <p>The prioritization of redundant properties is as follows:<ol>
  6450. *
  6451. * <li>If the <tt>width</tt> property is not specified (i.e., null), its value
  6452. * is the width of the parent panel, minus this mark's left and right margins;
  6453. * the left and right margins are zero if not specified.
  6454. *
  6455. * <li>Otherwise, if the <tt>right</tt> margin is not specified, its value is
  6456. * the width of the parent panel, minus this mark's width and left margin; the
  6457. * left margin is zero if not specified.
  6458. *
  6459. * <li>Otherwise, if the <tt>left</tt> property is not specified, its value is
  6460. * the width of the parent panel, minus this mark's width and the right margin.
  6461. *
  6462. * </ol>This prioritization is then duplicated for the <tt>height</tt>,
  6463. * <tt>bottom</tt> and <tt>top</tt> properties, respectively.
  6464. *
  6465. * <p>While most properties are <i>variable</i>, some mark types, such as lines
  6466. * and areas, generate a single visual element rather than a distinct visual
  6467. * element per datum. With these marks, some properties may be <b>fixed</b>.
  6468. * Fixed properties can vary per mark, but not <i>per datum</i>! These
  6469. * properties are evaluated solely for the first (0-index) datum, and typically
  6470. * are specified as a constant. However, it is valid to use a function if the
  6471. * property varies between panels or is dynamically generated.
  6472. *
  6473. * <p>See also the <a href="../../api/">Protovis guide</a>.
  6474. */
  6475. pv.Mark = function() {
  6476. /*
  6477. * TYPE 0 constant defs
  6478. * TYPE 1 function defs
  6479. * TYPE 2 constant properties
  6480. * TYPE 3 function properties
  6481. * in order of evaluation!
  6482. */
  6483. this.$properties = [];
  6484. this.$handlers = {};
  6485. };
  6486. /** @private Records which properties are defined on this mark type. */
  6487. pv.Mark.prototype.properties = {};
  6488. /** @private Records the cast function for each property. */
  6489. pv.Mark.cast = {};
  6490. /**
  6491. * @private Defines and registers a property method for the property with the
  6492. * given name. This method should be called on a mark class prototype to define
  6493. * each exposed property. (Note this refers to the JavaScript
  6494. * <tt>prototype</tt>, not the Protovis mark prototype, which is the {@link
  6495. * #proto} field.)
  6496. *
  6497. * <p>The created property method supports several modes of invocation: <ol>
  6498. *
  6499. * <li>If invoked with a <tt>Function</tt> argument, this function is evaluated
  6500. * for each associated datum. The return value of the function is used as the
  6501. * computed property value. The context of the function (<tt>this</tt>) is this
  6502. * mark. The arguments to the function are the associated data of this mark and
  6503. * any enclosing panels. For example, a linear encoding of numerical data to
  6504. * height is specified as
  6505. *
  6506. * <pre>m.height(function(d) d * 100);</pre>
  6507. *
  6508. * The expression <tt>d * 100</tt> will be evaluated for the height property of
  6509. * each mark instance. The return value of the property method (e.g.,
  6510. * <tt>m.height</tt>) is this mark (<tt>m</tt>)).<p>
  6511. *
  6512. * <li>If invoked with a non-function argument, the property is treated as a
  6513. * constant. The return value of the property method (e.g., <tt>m.height</tt>)
  6514. * is this mark.<p>
  6515. *
  6516. * <li>If invoked with no arguments, the computed property value for the current
  6517. * mark instance in the scene graph is returned. This facilitates <i>property
  6518. * chaining</i>, where one mark's properties are defined in terms of another's.
  6519. * For example, to offset a mark's location from its prototype, you might say
  6520. *
  6521. * <pre>m.top(function() this.proto.top() + 10);</pre>
  6522. *
  6523. * Note that the index of the mark being evaluated (in the above example,
  6524. * <tt>this.proto</tt>) is inherited from the <tt>Mark</tt> class and set by
  6525. * this mark. So, if the fifth element's top property is being evaluated, the
  6526. * fifth instance of <tt>this.proto</tt> will similarly be queried for the value
  6527. * of its top property. If the mark being evaluated has a different number of
  6528. * instances, or its data is unrelated, the behavior of this method is
  6529. * undefined. In these cases it may be better to index the <tt>scene</tt>
  6530. * explicitly to specify the exact instance.
  6531. *
  6532. * </ol><p>Property names should follow standard JavaScript method naming
  6533. * conventions, using lowerCamel-style capitalization.
  6534. *
  6535. * <p>In addition to creating the property method, every property is registered
  6536. * in the {@link #properties} map on the <tt>prototype</tt>. Although this is an
  6537. * instance field, it is considered immutable and shared by all instances of a
  6538. * given mark type. The <tt>properties</tt> map can be queried to see if a mark
  6539. * type defines a particular property, such as width or height.
  6540. *
  6541. * @param {string} name the property name.
  6542. * @param {function} [cast] the cast function for this property.
  6543. */
  6544. pv.Mark.prototype.property = function(name, cast) {
  6545. if (!this.hasOwnProperty("properties")) {
  6546. this.properties = pv.extend(this.properties);
  6547. }
  6548. this.properties[name] = true;
  6549. /*
  6550. * Define the setter-getter globally, since the default behavior should be the
  6551. * same for all properties, and since the Protovis inheritance chain is
  6552. * independent of the JavaScript inheritance chain. For example, anchors
  6553. * define a "name" property that is evaluated on derived marks, even though
  6554. * those marks don't normally have a name.
  6555. */
  6556. pv.Mark.prototype.propertyMethod(name, false, pv.Mark.cast[name] = cast);
  6557. return this;
  6558. };
  6559. /**
  6560. * @private Defines a setter-getter for the specified property.
  6561. *
  6562. * <p>If a cast function has been assigned to the specified property name, the
  6563. * property function is wrapped by the cast function, or, if a constant is
  6564. * specified, the constant is immediately cast. Note, however, that if the
  6565. * property value is null, the cast function is not invoked.
  6566. *
  6567. * @param {string} name the property name.
  6568. * @param {boolean} [def] whether is a property or a def.
  6569. * @param {function} [cast] the cast function for this property.
  6570. */
  6571. pv.Mark.prototype.propertyMethod = function(name, def, cast) {
  6572. if (!cast) cast = pv.Mark.cast[name];
  6573. this[name] = function(v) {
  6574. /* If this is a def, use it rather than property. */
  6575. if (def && this.scene) {
  6576. var defs = this.scene.defs;
  6577. if (arguments.length) {
  6578. defs[name] = {
  6579. id: (v == null) ? 0 : pv.id(),
  6580. value: ((v != null) && cast) ? cast(v) : v
  6581. };
  6582. return this;
  6583. }
  6584. return defs[name] ? defs[name].value : null;
  6585. }
  6586. /* If arguments are specified, set the property value. */
  6587. if (arguments.length) {
  6588. var type = !def << 1 | (typeof v == "function");
  6589. this.propertyValue(name, (type & 1 && cast) ? function() {
  6590. var x = v.apply(this, arguments);
  6591. return (x != null) ? cast(x) : null;
  6592. } : (((v != null) && cast) ? cast(v) : v)).type = type;
  6593. return this;
  6594. }
  6595. return this.instance()[name];
  6596. };
  6597. };
  6598. /** @private Sets the value of the property <i>name</i> to <i>v</i>. */
  6599. pv.Mark.prototype.propertyValue = function(name, v) {
  6600. var properties = this.$properties, p = {name: name, id: pv.id(), value: v};
  6601. for (var i = 0; i < properties.length; i++) {
  6602. if (properties[i].name == name) {
  6603. properties.splice(i, 1);
  6604. break;
  6605. }
  6606. }
  6607. properties.push(p);
  6608. return p;
  6609. };
  6610. /* Define all global properties. */
  6611. pv.Mark.prototype
  6612. .property("data")
  6613. .property("visible", Boolean)
  6614. .property("left", Number)
  6615. .property("right", Number)
  6616. .property("top", Number)
  6617. .property("bottom", Number)
  6618. .property("cursor", String)
  6619. .property("title", String)
  6620. .property("reverse", Boolean)
  6621. .property("antialias", Boolean)
  6622. .property("events", String);
  6623. /**
  6624. * The mark type; a lower camelCase name. The type name controls rendering
  6625. * behavior, and unless the rendering engine is extended, must be one of the
  6626. * built-in concrete mark types: area, bar, dot, image, label, line, panel,
  6627. * rule, or wedge.
  6628. *
  6629. * @type string
  6630. * @name pv.Mark.prototype.type
  6631. */
  6632. /**
  6633. * The mark prototype, possibly undefined, from which to inherit property
  6634. * functions. The mark prototype is not necessarily of the same type as this
  6635. * mark. Any properties defined on this mark will override properties inherited
  6636. * either from the prototype or from the type-specific defaults.
  6637. *
  6638. * @type pv.Mark
  6639. * @name pv.Mark.prototype.proto
  6640. */
  6641. /**
  6642. * The enclosing parent panel. The parent panel is generally undefined only for
  6643. * the root panel; however, it is possible to create "offscreen" marks that are
  6644. * used only for inheritance purposes.
  6645. *
  6646. * @type pv.Panel
  6647. * @name pv.Mark.prototype.parent
  6648. */
  6649. /**
  6650. * The child index. -1 if the enclosing parent panel is null; otherwise, the
  6651. * zero-based index of this mark into the parent panel's <tt>children</tt> array.
  6652. *
  6653. * @type number
  6654. */
  6655. pv.Mark.prototype.childIndex = -1;
  6656. /**
  6657. * The mark index. The value of this field depends on which instance (i.e.,
  6658. * which element of the data array) is currently being evaluated. During the
  6659. * build phase, the index is incremented over each datum; when handling events,
  6660. * the index is set to the instance that triggered the event.
  6661. *
  6662. * @type number
  6663. */
  6664. pv.Mark.prototype.index = -1;
  6665. /**
  6666. * The current scale factor, based on any enclosing transforms. The current
  6667. * scale can be used to create scale-independent graphics. For example, to
  6668. * define a dot that has a radius of 10 irrespective of any zooming, say:
  6669. *
  6670. * <pre>dot.radius(function() 10 / this.scale)</pre>
  6671. *
  6672. * Note that the stroke width and font size are defined irrespective of scale
  6673. * (i.e., in screen space) already. Also note that when a transform is applied
  6674. * to a panel, the scale affects only the child marks, not the panel itself.
  6675. *
  6676. * @type number
  6677. * @see pv.Panel#transform
  6678. */
  6679. pv.Mark.prototype.scale = 1;
  6680. /**
  6681. * @private The scene graph. The scene graph is an array of objects; each object
  6682. * (or "node") corresponds to an instance of this mark and an element in the
  6683. * data array. The scene graph can be traversed to lookup previously-evaluated
  6684. * properties.
  6685. *
  6686. * @name pv.Mark.prototype.scene
  6687. */
  6688. /**
  6689. * The root parent panel. This may be undefined for "offscreen" marks that are
  6690. * created for inheritance purposes only.
  6691. *
  6692. * @type pv.Panel
  6693. * @name pv.Mark.prototype.root
  6694. */
  6695. /**
  6696. * The data property; an array of objects. The size of the array determines the
  6697. * number of marks that will be instantiated; each element in the array will be
  6698. * passed to property functions to compute the property values. Typically, the
  6699. * data property is specified as a constant array, such as
  6700. *
  6701. * <pre>m.data([1, 2, 3, 4, 5]);</pre>
  6702. *
  6703. * However, it is perfectly acceptable to define the data property as a
  6704. * function. This function might compute the data dynamically, allowing
  6705. * different data to be used per enclosing panel. For instance, in the stacked
  6706. * area graph example (see {@link #scene}), the data function on the area mark
  6707. * dereferences each series.
  6708. *
  6709. * @type array
  6710. * @name pv.Mark.prototype.data
  6711. */
  6712. /**
  6713. * The visible property; a boolean determining whether or not the mark instance
  6714. * is visible. If a mark instance is not visible, its other properties will not
  6715. * be evaluated. Similarly, for panels no child marks will be rendered.
  6716. *
  6717. * @type boolean
  6718. * @name pv.Mark.prototype.visible
  6719. */
  6720. /**
  6721. * The left margin; the distance, in pixels, between the left edge of the
  6722. * enclosing panel and the left edge of this mark. Note that in some cases this
  6723. * property may be redundant with the right property, or with the conjunction of
  6724. * right and width.
  6725. *
  6726. * @type number
  6727. * @name pv.Mark.prototype.left
  6728. */
  6729. /**
  6730. * The right margin; the distance, in pixels, between the right edge of the
  6731. * enclosing panel and the right edge of this mark. Note that in some cases this
  6732. * property may be redundant with the left property, or with the conjunction of
  6733. * left and width.
  6734. *
  6735. * @type number
  6736. * @name pv.Mark.prototype.right
  6737. */
  6738. /**
  6739. * The top margin; the distance, in pixels, between the top edge of the
  6740. * enclosing panel and the top edge of this mark. Note that in some cases this
  6741. * property may be redundant with the bottom property, or with the conjunction
  6742. * of bottom and height.
  6743. *
  6744. * @type number
  6745. * @name pv.Mark.prototype.top
  6746. */
  6747. /**
  6748. * The bottom margin; the distance, in pixels, between the bottom edge of the
  6749. * enclosing panel and the bottom edge of this mark. Note that in some cases
  6750. * this property may be redundant with the top property, or with the conjunction
  6751. * of top and height.
  6752. *
  6753. * @type number
  6754. * @name pv.Mark.prototype.bottom
  6755. */
  6756. /**
  6757. * The cursor property; corresponds to the CSS cursor property. This is
  6758. * typically used in conjunction with event handlers to indicate interactivity.
  6759. *
  6760. * @type string
  6761. * @name pv.Mark.prototype.cursor
  6762. * @see <a href="http://www.w3.org/TR/CSS2/ui.html#propdef-cursor">CSS2 cursor</a>
  6763. */
  6764. /**
  6765. * The title property; corresponds to the HTML/SVG title property, allowing the
  6766. * general of simple plain text tooltips.
  6767. *
  6768. * @type string
  6769. * @name pv.Mark.prototype.title
  6770. */
  6771. /**
  6772. * The events property; corresponds to the SVG pointer-events property,
  6773. * specifying how the mark should participate in mouse events. The default value
  6774. * is "painted". Supported values are:
  6775. *
  6776. * <p>"painted": The given mark may receive events when the mouse is over a
  6777. * "painted" area. The painted areas are the interior (i.e., fill) of the mark
  6778. * if a 'fillStyle' is specified, and the perimeter (i.e., stroke) of the mark
  6779. * if a 'strokeStyle' is specified.
  6780. *
  6781. * <p>"all": The given mark may receive events when the mouse is over either the
  6782. * interior (i.e., fill) or the perimeter (i.e., stroke) of the mark, regardless
  6783. * of the specified fillStyle and strokeStyle.
  6784. *
  6785. * <p>"none": The given mark may not receive events.
  6786. *
  6787. * @type string
  6788. * @name pv.Mark.prototype.events
  6789. */
  6790. /**
  6791. * The reverse property; a boolean determining whether marks are ordered from
  6792. * front-to-back or back-to-front. SVG does not support explicit z-ordering;
  6793. * shapes are rendered in the order they appear. Thus, by default, marks are
  6794. * rendered in data order. Setting the reverse property to false reverses the
  6795. * order in which they are rendered; however, the properties are still evaluated
  6796. * (i.e., built) in forward order.
  6797. *
  6798. * @type boolean
  6799. * @name pv.Mark.prototype.reverse
  6800. */
  6801. /**
  6802. * Default properties for all mark types. By default, the data array is the
  6803. * parent data as a single-element array; if the data property is not specified,
  6804. * this causes each mark to be instantiated as a singleton with the parents
  6805. * datum. The visible property is true by default, and the reverse property is
  6806. * false.
  6807. *
  6808. * @type pv.Mark
  6809. */
  6810. pv.Mark.prototype.defaults = new pv.Mark()
  6811. .data(function(d) { return [d]; })
  6812. .visible(true)
  6813. .antialias(true)
  6814. .events("painted");
  6815. /**
  6816. * Sets the prototype of this mark to the specified mark. Any properties not
  6817. * defined on this mark may be inherited from the specified prototype mark, or
  6818. * its prototype, and so on. The prototype mark need not be the same type of
  6819. * mark as this mark. (Note that for inheritance to be useful, properties with
  6820. * the same name on different mark types should have equivalent meaning.)
  6821. *
  6822. * @param {pv.Mark} proto the new prototype.
  6823. * @returns {pv.Mark} this mark.
  6824. * @see #add
  6825. */
  6826. pv.Mark.prototype.extend = function(proto) {
  6827. this.proto = proto;
  6828. return this;
  6829. };
  6830. /**
  6831. * Adds a new mark of the specified type to the enclosing parent panel, whilst
  6832. * simultaneously setting the prototype of the new mark to be this mark.
  6833. *
  6834. * @param {function} type the type of mark to add; a constructor, such as
  6835. * <tt>pv.Bar</tt>.
  6836. * @returns {pv.Mark} the new mark.
  6837. * @see #extend
  6838. */
  6839. pv.Mark.prototype.add = function(type) {
  6840. return this.parent.add(type).extend(this);
  6841. };
  6842. /**
  6843. * Defines a custom property on this mark. Custom properties are currently
  6844. * fixed, in that they are initialized once per mark set (i.e., per parent panel
  6845. * instance). Custom properties can be used to store local state for the mark,
  6846. * such as data needed by other properties (e.g., a custom scale) or interaction
  6847. * state.
  6848. *
  6849. * <p>WARNING We plan on changing this feature in a future release to define
  6850. * standard properties, as opposed to <i>fixed</i> properties that behave
  6851. * idiosyncratically within event handlers. Furthermore, we recommend storing
  6852. * state in an external data structure, rather than tying it to the
  6853. * visualization specification as with defs.
  6854. *
  6855. * @param {string} name the name of the local variable.
  6856. * @param {function} [v] an optional initializer; may be a constant or a
  6857. * function.
  6858. */
  6859. pv.Mark.prototype.def = function(name, v) {
  6860. this.propertyMethod(name, true);
  6861. return this[name](arguments.length > 1 ? v : null);
  6862. };
  6863. /**
  6864. * Returns an anchor with the specified name. All marks support the five
  6865. * standard anchor names:<ul>
  6866. *
  6867. * <li>top
  6868. * <li>left
  6869. * <li>center
  6870. * <li>bottom
  6871. * <li>right
  6872. *
  6873. * </ul>In addition to positioning properties (left, right, top bottom), the
  6874. * anchors support text rendering properties (text-align, text-baseline). Text is
  6875. * rendered to appear inside the mark by default.
  6876. *
  6877. * <p>To facilitate stacking, anchors are defined in terms of their opposite
  6878. * edge. For example, the top anchor defines the bottom property, such that the
  6879. * mark extends upwards; the bottom anchor instead defines the top property,
  6880. * such that the mark extends downwards. See also {@link pv.Layout.Stack}.
  6881. *
  6882. * <p>While anchor names are typically constants, the anchor name is a true
  6883. * property, which means you can specify a function to compute the anchor name
  6884. * dynamically. See the {@link pv.Anchor#name} property for details.
  6885. *
  6886. * @param {string} name the anchor name; either a string or a property function.
  6887. * @returns {pv.Anchor} the new anchor.
  6888. */
  6889. pv.Mark.prototype.anchor = function(name) {
  6890. var target = this, scene;
  6891. /* Default anchor name. */
  6892. if (!name) name = "center";
  6893. /** @private Find the instances of target that match source. */
  6894. function instances(source) {
  6895. var mark = target, index = [];
  6896. /* Mirrored descent. */
  6897. while (!(scene = mark.scene)) {
  6898. source = source.parent;
  6899. index.push({index: source.index, childIndex: mark.childIndex});
  6900. mark = mark.parent;
  6901. }
  6902. while (index.length) {
  6903. var i = index.pop();
  6904. scene = scene[i.index].children[i.childIndex];
  6905. }
  6906. /*
  6907. * When the anchor target is also an ancestor, as in the case of adding
  6908. * to a panel anchor, only generate one instance per panel. Also, set
  6909. * the margins to zero, since they are offset by the enclosing panel.
  6910. */
  6911. if (target.hasOwnProperty("index")) {
  6912. var s = pv.extend(scene[target.index]);
  6913. s.right = s.top = s.left = s.bottom = 0;
  6914. return [s];
  6915. }
  6916. return scene;
  6917. }
  6918. return new pv.Anchor(this)
  6919. .name(name)
  6920. .def("$mark.anchor", function() {
  6921. scene = this.scene.target = instances(this);
  6922. })
  6923. .data(function() {
  6924. return scene.map(function(s) { return s.data; });
  6925. })
  6926. .visible(function() {
  6927. return scene[this.index].visible;
  6928. })
  6929. .left(function() {
  6930. var s = scene[this.index], w = s.width || 0;
  6931. switch (this.name()) {
  6932. case "bottom":
  6933. case "top":
  6934. case "center": return s.left + w / 2;
  6935. case "left": return null;
  6936. }
  6937. return s.left + w;
  6938. })
  6939. .top(function() {
  6940. var s = scene[this.index], h = s.height || 0;
  6941. switch (this.name()) {
  6942. case "left":
  6943. case "right":
  6944. case "center": return s.top + h / 2;
  6945. case "top": return null;
  6946. }
  6947. return s.top + h;
  6948. })
  6949. .right(function() {
  6950. var s = scene[this.index];
  6951. return this.name() == "left" ? s.right + (s.width || 0) : null;
  6952. })
  6953. .bottom(function() {
  6954. var s = scene[this.index];
  6955. return this.name() == "top" ? s.bottom + (s.height || 0) : null;
  6956. })
  6957. .textAlign(function() {
  6958. switch (this.name()) {
  6959. case "bottom":
  6960. case "top":
  6961. case "center": return "center";
  6962. case "right": return "right";
  6963. }
  6964. return "left";
  6965. })
  6966. .textBaseline(function() {
  6967. switch (this.name()) {
  6968. case "right":
  6969. case "left":
  6970. case "center": return "middle";
  6971. case "top": return "top";
  6972. }
  6973. return "bottom";
  6974. });
  6975. };
  6976. /**
  6977. * Returns the anchor target of this mark, if it is derived from an anchor;
  6978. * otherwise returns null. For example, if a label is derived from a bar anchor,
  6979. *
  6980. * <pre>bar.anchor("top").add(pv.Label);</pre>
  6981. *
  6982. * then property functions on the label can refer to the bar via the
  6983. * <tt>anchorTarget</tt> method. This method is also useful for mark types
  6984. * defining properties on custom anchors.
  6985. *
  6986. * @returns {pv.Mark} the anchor target of this mark; possibly null.
  6987. */
  6988. pv.Mark.prototype.anchorTarget = function() {
  6989. return this.proto.anchorTarget();
  6990. };
  6991. /**
  6992. * Alias for setting the left, right, top and bottom properties simultaneously.
  6993. *
  6994. * @see #left
  6995. * @see #right
  6996. * @see #top
  6997. * @see #bottom
  6998. * @returns {pv.Mark} this.
  6999. */
  7000. pv.Mark.prototype.margin = function(n) {
  7001. return this.left(n).right(n).top(n).bottom(n);
  7002. };
  7003. /**
  7004. * @private Returns the current instance of this mark in the scene graph. This
  7005. * is typically equivalent to <tt>this.scene[this.index]</tt>, however if the
  7006. * scene or index is unset, the default instance of the mark is returned. If no
  7007. * default is set, the default is the last instance. Similarly, if the scene or
  7008. * index of the parent panel is unset, the default instance of this mark in the
  7009. * last instance of the enclosing panel is returned, and so on.
  7010. *
  7011. * @returns a node in the scene graph.
  7012. */
  7013. pv.Mark.prototype.instance = function(defaultIndex) {
  7014. var scene = this.scene || this.parent.instance(-1).children[this.childIndex],
  7015. index = !arguments.length || this.hasOwnProperty("index") ? this.index : defaultIndex;
  7016. return scene[index < 0 ? scene.length - 1 : index];
  7017. };
  7018. /**
  7019. * @private Returns the first instance of this mark in the scene graph. This
  7020. * method can only be called when the mark is bound to the scene graph (for
  7021. * example, from an event handler, or within a property function).
  7022. *
  7023. * @returns a node in the scene graph.
  7024. */
  7025. pv.Mark.prototype.first = function() {
  7026. return this.scene[0];
  7027. };
  7028. /**
  7029. * @private Returns the last instance of this mark in the scene graph. This
  7030. * method can only be called when the mark is bound to the scene graph (for
  7031. * example, from an event handler, or within a property function). In addition,
  7032. * note that mark instances are built sequentially, so the last instance of this
  7033. * mark may not yet be constructed.
  7034. *
  7035. * @returns a node in the scene graph.
  7036. */
  7037. pv.Mark.prototype.last = function() {
  7038. return this.scene[this.scene.length - 1];
  7039. };
  7040. /**
  7041. * @private Returns the previous instance of this mark in the scene graph, or
  7042. * null if this is the first instance.
  7043. *
  7044. * @returns a node in the scene graph, or null.
  7045. */
  7046. pv.Mark.prototype.sibling = function() {
  7047. return (this.index == 0) ? null : this.scene[this.index - 1];
  7048. };
  7049. /**
  7050. * @private Returns the current instance in the scene graph of this mark, in the
  7051. * previous instance of the enclosing parent panel. May return null if this
  7052. * instance could not be found.
  7053. *
  7054. * @returns a node in the scene graph, or null.
  7055. */
  7056. pv.Mark.prototype.cousin = function() {
  7057. var p = this.parent, s = p && p.sibling();
  7058. return (s && s.children) ? s.children[this.childIndex][this.index] : null;
  7059. };
  7060. /**
  7061. * Renders this mark, including recursively rendering all child marks if this is
  7062. * a panel. This method finds all instances of this mark and renders them. This
  7063. * method descends recursively to the level of the mark to be rendered, finding
  7064. * all visible instances of the mark. After the marks are rendered, the scene
  7065. * and index attributes are removed from the mark to restore them to a clean
  7066. * state.
  7067. *
  7068. * <p>If an enclosing panel has an index property set (as is the case inside in
  7069. * an event handler), then only instances of this mark inside the given instance
  7070. * of the panel will be rendered; otherwise, all visible instances of the mark
  7071. * will be rendered.
  7072. */
  7073. pv.Mark.prototype.render = function() {
  7074. var parent = this.parent,
  7075. stack = pv.Mark.stack;
  7076. /* For the first render, take it from the top. */
  7077. if (parent && !this.root.scene) {
  7078. this.root.render();
  7079. return;
  7080. }
  7081. /* Record the path to this mark. */
  7082. var indexes = [];
  7083. for (var mark = this; mark.parent; mark = mark.parent) {
  7084. indexes.unshift(mark.childIndex);
  7085. }
  7086. /** @private */
  7087. function render(mark, depth, scale) {
  7088. mark.scale = scale;
  7089. if (depth < indexes.length) {
  7090. stack.unshift(null);
  7091. if (mark.hasOwnProperty("index")) {
  7092. renderInstance(mark, depth, scale);
  7093. } else {
  7094. for (var i = 0, n = mark.scene.length; i < n; i++) {
  7095. mark.index = i;
  7096. renderInstance(mark, depth, scale);
  7097. }
  7098. delete mark.index;
  7099. }
  7100. stack.shift();
  7101. } else {
  7102. mark.build();
  7103. /*
  7104. * In the update phase, the scene is rendered by creating and updating
  7105. * elements and attributes in the SVG image. No properties are evaluated
  7106. * during the update phase; instead the values computed previously in the
  7107. * build phase are simply translated into SVG. The update phase is
  7108. * decoupled (see pv.Scene) to allow different rendering engines.
  7109. */
  7110. pv.Scene.scale = scale;
  7111. pv.Scene.updateAll(mark.scene);
  7112. }
  7113. delete mark.scale;
  7114. }
  7115. /**
  7116. * @private Recursively renders the current instance of the specified mark.
  7117. * This is slightly tricky because `index` and `scene` properties may or may
  7118. * not already be set; if they are set, it means we are rendering only a
  7119. * specific instance; if they are unset, we are rendering all instances.
  7120. * Furthermore, we must preserve the original context of these properties when
  7121. * rendering completes.
  7122. *
  7123. * <p>Another tricky aspect is that the `scene` attribute should be set for
  7124. * any preceding children, so as to allow property chaining. This is
  7125. * consistent with first-pass rendering.
  7126. */
  7127. function renderInstance(mark, depth, scale) {
  7128. var s = mark.scene[mark.index], i;
  7129. if (s.visible) {
  7130. var childIndex = indexes[depth],
  7131. child = mark.children[childIndex];
  7132. /* Set preceding child scenes. */
  7133. for (i = 0; i < childIndex; i++) {
  7134. mark.children[i].scene = s.children[i];
  7135. }
  7136. /* Set current child scene, if necessary. */
  7137. stack[0] = s.data;
  7138. if (child.scene) {
  7139. render(child, depth + 1, scale * s.transform.k);
  7140. } else {
  7141. child.scene = s.children[childIndex];
  7142. render(child, depth + 1, scale * s.transform.k);
  7143. delete child.scene;
  7144. }
  7145. /* Clear preceding child scenes. */
  7146. for (i = 0; i < childIndex; i++) {
  7147. delete mark.children[i].scene;
  7148. }
  7149. }
  7150. }
  7151. /* Bind this mark's property definitions. */
  7152. this.bind();
  7153. /* The render context is the first ancestor with an explicit index. */
  7154. while (parent && !parent.hasOwnProperty("index")) parent = parent.parent;
  7155. /* Recursively render all instances of this mark. */
  7156. this.context(
  7157. parent ? parent.scene : undefined,
  7158. parent ? parent.index : -1,
  7159. function() { render(this.root, 0, 1); });
  7160. };
  7161. /** @private Stores the current data stack. */
  7162. pv.Mark.stack = [];
  7163. /**
  7164. * @private In the bind phase, inherited property definitions are cached so they
  7165. * do not need to be queried during build.
  7166. */
  7167. pv.Mark.prototype.bind = function() {
  7168. var seen = {}, types = [[], [], [], []], data, visible;
  7169. /** Scans the proto chain for the specified mark. */
  7170. function bind(mark) {
  7171. do {
  7172. var properties = mark.$properties;
  7173. for (var i = properties.length - 1; i >= 0 ; i--) {
  7174. var p = properties[i];
  7175. if (!(p.name in seen)) {
  7176. seen[p.name] = p;
  7177. switch (p.name) {
  7178. case "data": data = p; break;
  7179. case "visible": visible = p; break;
  7180. default: types[p.type].push(p); break;
  7181. }
  7182. }
  7183. }
  7184. } while (mark = mark.proto);
  7185. }
  7186. /* Scan the proto chain for all defined properties. */
  7187. bind(this);
  7188. bind(this.defaults);
  7189. types[1].reverse();
  7190. types[3].reverse();
  7191. /* Any undefined properties are null. */
  7192. var mark = this;
  7193. do for (var name in mark.properties) {
  7194. if (!(name in seen)) {
  7195. types[2].push(seen[name] = {name: name, type: 2, value: null});
  7196. }
  7197. } while (mark = mark.proto);
  7198. /* Define setter-getter for inherited defs. */
  7199. var defs = types[0].concat(types[1]);
  7200. for (var i = 0; i < defs.length; i++) {
  7201. this.propertyMethod(defs[i].name, true);
  7202. }
  7203. /* Setup binds to evaluate constants before functions. */
  7204. this.binds = {
  7205. properties: seen,
  7206. data: data,
  7207. defs: defs,
  7208. required: [visible],
  7209. optional: pv.blend(types)
  7210. };
  7211. };
  7212. /**
  7213. * @private Evaluates properties and computes implied properties. Properties are
  7214. * stored in the {@link #scene} array for each instance of this mark.
  7215. *
  7216. * <p>As marks are built recursively, the {@link #index} property is updated to
  7217. * match the current index into the data array for each mark. Note that the
  7218. * index property is only set for the mark currently being built and its
  7219. * enclosing parent panels. The index property for other marks is unset, but is
  7220. * inherited from the global <tt>Mark</tt> class prototype. This allows mark
  7221. * properties to refer to properties on other marks <i>in the same panel</i>
  7222. * conveniently; however, in general it is better to reference mark instances
  7223. * specifically through the scene graph rather than depending on the magical
  7224. * behavior of {@link #index}.
  7225. *
  7226. * <p>The root scene array has a special property, <tt>data</tt>, which stores
  7227. * the current data stack. The first element in this stack is the current datum,
  7228. * followed by the datum of the enclosing parent panel, and so on. The data
  7229. * stack should not be accessed directly; instead, property functions are passed
  7230. * the current data stack as arguments.
  7231. *
  7232. * <p>The evaluation of the <tt>data</tt> and <tt>visible</tt> properties is
  7233. * special. The <tt>data</tt> property is evaluated first; unlike the other
  7234. * properties, the data stack is from the parent panel, rather than the current
  7235. * mark, since the data is not defined until the data property is evaluated.
  7236. * The <tt>visisble</tt> property is subsequently evaluated for each instance;
  7237. * only if true will the {@link #buildInstance} method be called, evaluating
  7238. * other properties and recursively building the scene graph.
  7239. *
  7240. * <p>If this mark is being re-built, any old instances of this mark that no
  7241. * longer exist (because the new data array contains fewer elements) will be
  7242. * cleared using {@link #clearInstance}.
  7243. *
  7244. * @param parent the instance of the parent panel from the scene graph.
  7245. */
  7246. pv.Mark.prototype.build = function() {
  7247. var scene = this.scene, stack = pv.Mark.stack;
  7248. if (!scene) {
  7249. scene = this.scene = [];
  7250. scene.mark = this;
  7251. scene.type = this.type;
  7252. scene.childIndex = this.childIndex;
  7253. if (this.parent) {
  7254. scene.parent = this.parent.scene;
  7255. scene.parentIndex = this.parent.index;
  7256. }
  7257. }
  7258. /* Evaluate defs. */
  7259. if (this.binds.defs.length) {
  7260. var defs = scene.defs;
  7261. if (!defs) scene.defs = defs = {};
  7262. for (var i = 0; i < this.binds.defs.length; i++) {
  7263. var p = this.binds.defs[i], d = defs[p.name];
  7264. if (!d || (p.id > d.id)) {
  7265. defs[p.name] = {
  7266. id: 0, // this def will be re-evaluated on next build
  7267. value: (p.type & 1) ? p.value.apply(this, stack) : p.value
  7268. };
  7269. }
  7270. }
  7271. }
  7272. /* Evaluate special data property. */
  7273. var data = this.binds.data;
  7274. data = data.type & 1 ? data.value.apply(this, stack) : data.value;
  7275. /* Create, update and delete scene nodes. */
  7276. stack.unshift(null);
  7277. scene.length = data.length;
  7278. for (var i = 0; i < data.length; i++) {
  7279. pv.Mark.prototype.index = this.index = i;
  7280. var s = scene[i];
  7281. if (!s) scene[i] = s = {};
  7282. s.data = stack[0] = data[i];
  7283. this.buildInstance(s);
  7284. }
  7285. pv.Mark.prototype.index = -1;
  7286. delete this.index;
  7287. stack.shift();
  7288. return this;
  7289. };
  7290. /**
  7291. * @private Evaluates the specified array of properties for the specified
  7292. * instance <tt>s</tt> in the scene graph.
  7293. *
  7294. * @param s a node in the scene graph; the instance of the mark to build.
  7295. * @param properties an array of properties.
  7296. */
  7297. pv.Mark.prototype.buildProperties = function(s, properties) {
  7298. for (var i = 0, n = properties.length; i < n; i++) {
  7299. var p = properties[i], v = p.value; // assume case 2 (constant)
  7300. switch (p.type) {
  7301. case 0:
  7302. case 1: v = this.scene.defs[p.name].value; break;
  7303. case 3: v = v.apply(this, pv.Mark.stack); break;
  7304. }
  7305. s[p.name] = v;
  7306. }
  7307. };
  7308. /**
  7309. * @private Evaluates all of the properties for this mark for the specified
  7310. * instance <tt>s</tt> in the scene graph. The set of properties to evaluate is
  7311. * retrieved from the {@link #properties} array for this mark type (see {@link
  7312. * #type}). After these properties are evaluated, any <b>implied</b> properties
  7313. * may be computed by the mark and set on the scene graph; see
  7314. * {@link #buildImplied}.
  7315. *
  7316. * <p>For panels, this method recursively builds the scene graph for all child
  7317. * marks as well. In general, this method should not need to be overridden by
  7318. * concrete mark types.
  7319. *
  7320. * @param s a node in the scene graph; the instance of the mark to build.
  7321. */
  7322. pv.Mark.prototype.buildInstance = function(s) {
  7323. this.buildProperties(s, this.binds.required);
  7324. if (s.visible) {
  7325. this.buildProperties(s, this.binds.optional);
  7326. this.buildImplied(s);
  7327. }
  7328. };
  7329. /**
  7330. * @private Computes the implied properties for this mark for the specified
  7331. * instance <tt>s</tt> in the scene graph. Implied properties are those with
  7332. * dependencies on multiple other properties; for example, the width property
  7333. * may be implied if the left and right properties are set. This method can be
  7334. * overridden by concrete mark types to define new implied properties, if
  7335. * necessary.
  7336. *
  7337. * @param s a node in the scene graph; the instance of the mark to build.
  7338. */
  7339. pv.Mark.prototype.buildImplied = function(s) {
  7340. var l = s.left;
  7341. var r = s.right;
  7342. var t = s.top;
  7343. var b = s.bottom;
  7344. /* Assume width and height are zero if not supported by this mark type. */
  7345. var p = this.properties;
  7346. var w = p.width ? s.width : 0;
  7347. var h = p.height ? s.height : 0;
  7348. /* Compute implied width, right and left. */
  7349. var width = this.parent ? this.parent.width() : (w + l + r);
  7350. if (w == null) {
  7351. w = width - (r = r || 0) - (l = l || 0);
  7352. } else if (r == null) {
  7353. r = width - w - (l = l || 0);
  7354. } else if (l == null) {
  7355. l = width - w - (r = r || 0);
  7356. }
  7357. /* Compute implied height, bottom and top. */
  7358. var height = this.parent ? this.parent.height() : (h + t + b);
  7359. if (h == null) {
  7360. h = height - (t = t || 0) - (b = b || 0);
  7361. } else if (b == null) {
  7362. b = height - h - (t = t || 0);
  7363. } else if (t == null) {
  7364. t = height - h - (b = b || 0);
  7365. }
  7366. s.left = l;
  7367. s.right = r;
  7368. s.top = t;
  7369. s.bottom = b;
  7370. /* Only set width and height if they are supported by this mark type. */
  7371. if (p.width) s.width = w;
  7372. if (p.height) s.height = h;
  7373. /* Set any null colors to pv.Color.transparent. */
  7374. if (p.textStyle && !s.textStyle) s.textStyle = pv.Color.transparent;
  7375. if (p.fillStyle && !s.fillStyle) s.fillStyle = pv.Color.transparent;
  7376. if (p.strokeStyle && !s.strokeStyle) s.strokeStyle = pv.Color.transparent;
  7377. };
  7378. /**
  7379. * Returns the current location of the mouse (cursor) relative to this mark's
  7380. * parent. The <i>x</i> coordinate corresponds to the left margin, while the
  7381. * <i>y</i> coordinate corresponds to the top margin.
  7382. *
  7383. * @returns {pv.Vector} the mouse location.
  7384. */
  7385. pv.Mark.prototype.mouse = function() {
  7386. /* Compute xy-coordinates relative to the panel. */
  7387. var x = pv.event.pageX || 0,
  7388. y = pv.event.pageY || 0,
  7389. n = this.root.canvas();
  7390. // Calculate pageX/Y if missing and clientX/Y available
  7391. /*
  7392. CLOUDERA CHANGE:
  7393. Changed x == undefined to !x, which encompasses the x = 0 which is currently the VML value.
  7394. */
  7395. if ( !x && pv.event.clientX != undefined ) {
  7396. var doc = document.documentElement, body = document.body;
  7397. x = pv.event.clientX + (doc && doc.scrollLeft || body && body.scrollLeft || 0) - (doc && doc.clientLeft || body && body.clientLeft || 0);
  7398. y = pv.event.clientY + (doc && doc.scrollTop || body && body.scrollTop || 0) - (doc && doc.clientTop || body && body.clientTop || 0);
  7399. }
  7400. do {
  7401. /* CLOUDERA CHANGE */
  7402. //Accomodate for the possibility that the current offset parent (n) is in a scrolled object.
  7403. x -= (n.offsetLeft - n.scrollLeft);
  7404. y -= (n.offsetTop - n.scrollTop);
  7405. } while (n = n.offsetParent);
  7406. /* Compute the inverse transform of all enclosing panels. */
  7407. var t = pv.Transform.identity,
  7408. p = this.properties.transform ? this : this.parent,
  7409. pz = [];
  7410. do { pz.push(p); } while (p = p.parent);
  7411. while (p = pz.pop()) t = t.translate(p.left(), p.top()).times(p.transform());
  7412. t = t.invert();
  7413. return pv.vector(x * t.k + t.x, y * t.k + t.y);
  7414. };
  7415. /**
  7416. * Registers an event handler for the specified event type with this mark. When
  7417. * an event of the specified type is triggered, the specified handler will be
  7418. * invoked. The handler is invoked in a similar method to property functions:
  7419. * the context is <tt>this</tt> mark instance, and the arguments are the full
  7420. * data stack. Event handlers can use property methods to manipulate the display
  7421. * properties of the mark:
  7422. *
  7423. * <pre>m.event("click", function() this.fillStyle("red"));</pre>
  7424. *
  7425. * Alternatively, the external data can be manipulated and the visualization
  7426. * redrawn:
  7427. *
  7428. * <pre>m.event("click", function(d) {
  7429. * data = all.filter(function(k) k.name == d);
  7430. * vis.render();
  7431. * });</pre>
  7432. *
  7433. * The return value of the event handler determines which mark gets re-rendered.
  7434. * Use defs ({@link #def}) to set temporary state from event handlers.
  7435. *
  7436. * <p>The complete set of event types is defined by SVG; see the reference
  7437. * below. The set of supported event types is:<ul>
  7438. *
  7439. * <li>click
  7440. * <li>mousedown
  7441. * <li>mouseup
  7442. * <li>mouseover
  7443. * <li>mousemove
  7444. * <li>mouseout
  7445. *
  7446. * </ul>Since Protovis does not specify any concept of focus, it does not
  7447. * support key events; these should be handled outside the visualization using
  7448. * standard JavaScript. In the future, support for interaction may be extended
  7449. * to support additional event types, particularly those most relevant to
  7450. * interactive visualization, such as selection.
  7451. *
  7452. * <p>TODO In the current implementation, event handlers are not inherited from
  7453. * prototype marks. They must be defined explicitly on each interactive mark. In
  7454. * addition, only one event handler for a given event type can be defined; when
  7455. * specifying multiple event handlers for the same type, only the last one will
  7456. * be used.
  7457. *
  7458. * @see <a href="http://www.w3.org/TR/SVGTiny12/interact.html#SVGEvents">SVG events</a>
  7459. * @param {string} type the event type.
  7460. * @param {function} handler the event handler.
  7461. * @returns {pv.Mark} this.
  7462. */
  7463. pv.Mark.prototype.event = function(type, handler) {
  7464. this.$handlers[type] = pv.functor(handler);
  7465. return this;
  7466. };
  7467. /** @private Evaluates the function <i>f</i> with the specified context. */
  7468. pv.Mark.prototype.context = function(scene, index, f) {
  7469. var proto = pv.Mark.prototype,
  7470. stack = pv.Mark.stack,
  7471. oscene = pv.Mark.scene,
  7472. oindex = proto.index;
  7473. /** @private Sets the context. */
  7474. function apply(scene, index) {
  7475. pv.Mark.scene = scene;
  7476. proto.index = index;
  7477. if (!scene) return;
  7478. var that = scene.mark,
  7479. mark = that,
  7480. ancestors = [];
  7481. /* Set ancestors' scene and index; populate data stack. */
  7482. do {
  7483. ancestors.push(mark);
  7484. stack.push(scene[index].data);
  7485. mark.index = index;
  7486. mark.scene = scene;
  7487. index = scene.parentIndex;
  7488. scene = scene.parent;
  7489. } while (mark = mark.parent);
  7490. /* Set ancestors' scale; requires top-down. */
  7491. for (var i = ancestors.length - 1, k = 1; i > 0; i--) {
  7492. mark = ancestors[i];
  7493. mark.scale = k;
  7494. k *= mark.scene[mark.index].transform.k;
  7495. }
  7496. /* Set children's scene and scale. */
  7497. if (that.children) for (var i = 0, n = that.children.length; i < n; i++) {
  7498. mark = that.children[i];
  7499. mark.scene = that.scene[that.index].children[i];
  7500. mark.scale = k;
  7501. }
  7502. }
  7503. /** @private Clears the context. */
  7504. function clear(scene, index) {
  7505. if (!scene) return;
  7506. var that = scene.mark,
  7507. mark;
  7508. /* Reset children. */
  7509. if (that.children) for (var i = 0, n = that.children.length; i < n; i++) {
  7510. mark = that.children[i];
  7511. delete mark.scene;
  7512. delete mark.scale;
  7513. }
  7514. /* Reset ancestors. */
  7515. mark = that;
  7516. do {
  7517. stack.pop();
  7518. if (mark.parent) {
  7519. delete mark.scene;
  7520. delete mark.scale;
  7521. }
  7522. delete mark.index;
  7523. } while (mark = mark.parent);
  7524. }
  7525. /* Context switch, invoke the function, then switch back. */
  7526. clear(oscene, oindex);
  7527. apply(scene, index);
  7528. try {
  7529. f.apply(this, stack);
  7530. } finally {
  7531. clear(scene, index);
  7532. apply(oscene, oindex);
  7533. }
  7534. };
  7535. /** @private Execute the event listener, then re-render. */
  7536. pv.Mark.dispatch = function(type, scene, index) {
  7537. var m = scene.mark, p = scene.parent, l = m.$handlers[type];
  7538. if (!l) return p && pv.Mark.dispatch(type, p, scene.parentIndex);
  7539. m.context(scene, index, function() {
  7540. m = l.apply(m, pv.Mark.stack);
  7541. if (m && m.render) m.render();
  7542. });
  7543. return true;
  7544. };
  7545. /**
  7546. * Constructs a new mark anchor with default properties.
  7547. *
  7548. * @class Represents an anchor on a given mark. An anchor is itself a mark, but
  7549. * without a visual representation. It serves only to provide useful default
  7550. * properties that can be inherited by other marks. Each type of mark can define
  7551. * any number of named anchors for convenience. If the concrete mark type does
  7552. * not define an anchor implementation specifically, one will be inherited from
  7553. * the mark's parent class.
  7554. *
  7555. * <p>For example, the bar mark provides anchors for its four sides: left,
  7556. * right, top and bottom. Adding a label to the top anchor of a bar,
  7557. *
  7558. * <pre>bar.anchor("top").add(pv.Label);</pre>
  7559. *
  7560. * will render a text label on the top edge of the bar; the top anchor defines
  7561. * the appropriate position properties (top and left), as well as text-rendering
  7562. * properties for convenience (textAlign and textBaseline).
  7563. *
  7564. * <p>Note that anchors do not <i>inherit</i> from their targets; the positional
  7565. * properties are copied from the scene graph, which guarantees that the anchors
  7566. * are positioned correctly, even if the positional properties are not defined
  7567. * deterministically. (In addition, it also improves performance by avoiding
  7568. * re-evaluating expensive properties.) If you want the anchor to inherit from
  7569. * the target, use {@link pv.Mark#extend} before adding. For example:
  7570. *
  7571. * <pre>bar.anchor("top").extend(bar).add(pv.Label);</pre>
  7572. *
  7573. * The anchor defines it's own positional properties, but other properties (such
  7574. * as the title property, say) can be inherited using the above idiom. Also note
  7575. * that you can override positional properties in the anchor for custom
  7576. * behavior.
  7577. *
  7578. * @extends pv.Mark
  7579. * @param {pv.Mark} target the anchor target.
  7580. */
  7581. pv.Anchor = function(target) {
  7582. pv.Mark.call(this);
  7583. this.target = target;
  7584. this.parent = target.parent;
  7585. };
  7586. pv.Anchor.prototype = pv.extend(pv.Mark)
  7587. .property("name", String);
  7588. /**
  7589. * The anchor name. The set of supported anchor names is dependent on the
  7590. * concrete mark type; see the mark type for details. For example, bars support
  7591. * left, right, top and bottom anchors.
  7592. *
  7593. * <p>While anchor names are typically constants, the anchor name is a true
  7594. * property, which means you can specify a function to compute the anchor name
  7595. * dynamically. For instance, if you wanted to alternate top and bottom anchors,
  7596. * saying
  7597. *
  7598. * <pre>m.anchor(function() (this.index % 2) ? "top" : "bottom").add(pv.Dot);</pre>
  7599. *
  7600. * would have the desired effect.
  7601. *
  7602. * @type string
  7603. * @name pv.Anchor.prototype.name
  7604. */
  7605. /**
  7606. * Returns the anchor target of this mark, if it is derived from an anchor;
  7607. * otherwise returns null. For example, if a label is derived from a bar anchor,
  7608. *
  7609. * <pre>bar.anchor("top").add(pv.Label);</pre>
  7610. *
  7611. * then property functions on the label can refer to the bar via the
  7612. * <tt>anchorTarget</tt> method. This method is also useful for mark types
  7613. * defining properties on custom anchors.
  7614. *
  7615. * @returns {pv.Mark} the anchor target of this mark; possibly null.
  7616. */
  7617. pv.Anchor.prototype.anchorTarget = function() {
  7618. return this.target;
  7619. };
  7620. /**
  7621. * Constructs a new area mark with default properties. Areas are not typically
  7622. * constructed directly, but by adding to a panel or an existing mark via
  7623. * {@link pv.Mark#add}.
  7624. *
  7625. * @class Represents an area mark: the solid area between two series of
  7626. * connected line segments. Unsurprisingly, areas are used most frequently for
  7627. * area charts.
  7628. *
  7629. * <p>Just as a line represents a polyline, the <tt>Area</tt> mark type
  7630. * represents a <i>polygon</i>. However, an area is not an arbitrary polygon;
  7631. * vertices are paired either horizontally or vertically into parallel
  7632. * <i>spans</i>, and each span corresponds to an associated datum. Either the
  7633. * width or the height must be specified, but not both; this determines whether
  7634. * the area is horizontally-oriented or vertically-oriented. Like lines, areas
  7635. * can be stroked and filled with arbitrary colors.
  7636. *
  7637. * <p>See also the <a href="../../api/Area.html">Area guide</a>.
  7638. *
  7639. * @extends pv.Mark
  7640. */
  7641. pv.Area = function() {
  7642. pv.Mark.call(this);
  7643. };
  7644. pv.Area.prototype = pv.extend(pv.Mark)
  7645. .property("width", Number)
  7646. .property("height", Number)
  7647. .property("lineWidth", Number)
  7648. .property("strokeStyle", pv.color)
  7649. .property("fillStyle", pv.color)
  7650. .property("segmented", Boolean)
  7651. .property("interpolate", String)
  7652. .property("tension", Number);
  7653. pv.Area.prototype.type = "area";
  7654. /**
  7655. * The width of a given span, in pixels; used for horizontal spans. If the width
  7656. * is specified, the height property should be 0 (the default). Either the top
  7657. * or bottom property should be used to space the spans vertically, typically as
  7658. * a multiple of the index.
  7659. *
  7660. * @type number
  7661. * @name pv.Area.prototype.width
  7662. */
  7663. /**
  7664. * The height of a given span, in pixels; used for vertical spans. If the height
  7665. * is specified, the width property should be 0 (the default). Either the left
  7666. * or right property should be used to space the spans horizontally, typically
  7667. * as a multiple of the index.
  7668. *
  7669. * @type number
  7670. * @name pv.Area.prototype.height
  7671. */
  7672. /**
  7673. * The width of stroked lines, in pixels; used in conjunction with
  7674. * <tt>strokeStyle</tt> to stroke the perimeter of the area. Unlike the
  7675. * {@link Line} mark type, the entire perimeter is stroked, rather than just one
  7676. * edge. The default value of this property is 1.5, but since the default stroke
  7677. * style is null, area marks are not stroked by default.
  7678. *
  7679. * <p>This property is <i>fixed</i> for non-segmented areas. See
  7680. * {@link pv.Mark}.
  7681. *
  7682. * @type number
  7683. * @name pv.Area.prototype.lineWidth
  7684. */
  7685. /**
  7686. * The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
  7687. * stroke the perimeter of the area. Unlike the {@link Line} mark type, the
  7688. * entire perimeter is stroked, rather than just one edge. The default value of
  7689. * this property is null, meaning areas are not stroked by default.
  7690. *
  7691. * <p>This property is <i>fixed</i> for non-segmented areas. See
  7692. * {@link pv.Mark}.
  7693. *
  7694. * @type string
  7695. * @name pv.Area.prototype.strokeStyle
  7696. * @see pv.color
  7697. */
  7698. /**
  7699. * The area fill style; if non-null, the interior of the polygon forming the
  7700. * area is filled with the specified color. The default value of this property
  7701. * is a categorical color.
  7702. *
  7703. * <p>This property is <i>fixed</i> for non-segmented areas. See
  7704. * {@link pv.Mark}.
  7705. *
  7706. * @type string
  7707. * @name pv.Area.prototype.fillStyle
  7708. * @see pv.color
  7709. */
  7710. /**
  7711. * Whether the area is segmented; whether variations in fill style, stroke
  7712. * style, and the other properties are treated as fixed. Rendering segmented
  7713. * areas is noticeably slower than non-segmented areas.
  7714. *
  7715. * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
  7716. *
  7717. * @type boolean
  7718. * @name pv.Area.prototype.segmented
  7719. */
  7720. /**
  7721. * How to interpolate between values. Linear interpolation ("linear") is the
  7722. * default, producing a straight line between points. For piecewise constant
  7723. * functions (i.e., step functions), either "step-before" or "step-after" can be
  7724. * specified. To draw open uniform b-splines, specify "basis". To draw cardinal
  7725. * splines, specify "cardinal"; see also {@link #tension}.
  7726. *
  7727. * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
  7728. *
  7729. * @type string
  7730. * @name pv.Area.prototype.interpolate
  7731. */
  7732. /**
  7733. * The tension of cardinal splines; used in conjunction with
  7734. * interpolate("cardinal"). A value between 0 and 1 draws cardinal splines with
  7735. * the given tension. In some sense, the tension can be interpreted as the
  7736. * "length" of the tangent; a tension of 1 will yield all zero tangents (i.e.,
  7737. * linear interpolation), and a tension of 0 yields a Catmull-Rom spline. The
  7738. * default value is 0.7.
  7739. *
  7740. * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
  7741. *
  7742. * @type number
  7743. * @name pv.Area.prototype.tension
  7744. */
  7745. /**
  7746. * Default properties for areas. By default, there is no stroke and the fill
  7747. * style is a categorical color.
  7748. *
  7749. * @type pv.Area
  7750. */
  7751. pv.Area.prototype.defaults = new pv.Area()
  7752. .extend(pv.Mark.prototype.defaults)
  7753. .lineWidth(1.5)
  7754. .fillStyle(pv.Colors.category20().by(pv.parent))
  7755. .interpolate("linear")
  7756. .tension(.7);
  7757. /** @private Sets width and height to zero if null. */
  7758. pv.Area.prototype.buildImplied = function(s) {
  7759. if (s.height == null) s.height = 0;
  7760. if (s.width == null) s.width = 0;
  7761. pv.Mark.prototype.buildImplied.call(this, s);
  7762. };
  7763. /** @private Records which properties may be fixed. */
  7764. pv.Area.fixed = {
  7765. lineWidth: 1,
  7766. lineJoin: 1,
  7767. strokeStyle: 1,
  7768. fillStyle: 1,
  7769. segmented: 1,
  7770. interpolate: 1,
  7771. tension: 1
  7772. };
  7773. /**
  7774. * @private Make segmented required, such that this fixed property is always
  7775. * evaluated, even if the first segment is not visible. Also cache which
  7776. * properties are normally fixed.
  7777. */
  7778. pv.Area.prototype.bind = function() {
  7779. pv.Mark.prototype.bind.call(this);
  7780. var binds = this.binds,
  7781. required = binds.required,
  7782. optional = binds.optional;
  7783. for (var i = 0, n = optional.length; i < n; i++) {
  7784. var p = optional[i];
  7785. p.fixed = p.name in pv.Area.fixed;
  7786. if (p.name == "segmented") {
  7787. required.push(p);
  7788. optional.splice(i, 1);
  7789. i--;
  7790. n--;
  7791. }
  7792. }
  7793. /* Cache the original arrays so they can be restored on build. */
  7794. this.binds.$required = required;
  7795. this.binds.$optional = optional;
  7796. };
  7797. /**
  7798. * @private Override the default build behavior such that fixed properties are
  7799. * determined dynamically, based on the value of the (always) fixed segmented
  7800. * property. Any fixed properties are only evaluated on the first instance,
  7801. * although their values are propagated to subsequent instances, so that they
  7802. * are available for property chaining and the like.
  7803. */
  7804. pv.Area.prototype.buildInstance = function(s) {
  7805. var binds = this.binds;
  7806. /* Handle fixed properties on secondary instances. */
  7807. if (this.index) {
  7808. var fixed = binds.fixed;
  7809. /* Determine which properties are fixed. */
  7810. if (!fixed) {
  7811. fixed = binds.fixed = [];
  7812. function f(p) { return !p.fixed || (fixed.push(p), false); }
  7813. binds.required = binds.required.filter(f);
  7814. if (!this.scene[0].segmented) binds.optional = binds.optional.filter(f);
  7815. }
  7816. /* Copy fixed property values from the first instance. */
  7817. for (var i = 0, n = fixed.length; i < n; i++) {
  7818. var p = fixed[i].name;
  7819. s[p] = this.scene[0][p];
  7820. }
  7821. }
  7822. /* Evaluate all properties on the first instance. */
  7823. else {
  7824. binds.required = binds.$required;
  7825. binds.optional = binds.$optional;
  7826. binds.fixed = null;
  7827. }
  7828. pv.Mark.prototype.buildInstance.call(this, s);
  7829. };
  7830. /**
  7831. * Constructs a new area anchor with default properties. Areas support five
  7832. * different anchors:<ul>
  7833. *
  7834. * <li>top
  7835. * <li>left
  7836. * <li>center
  7837. * <li>bottom
  7838. * <li>right
  7839. *
  7840. * </ul>In addition to positioning properties (left, right, top bottom), the
  7841. * anchors support text rendering properties (text-align, text-baseline). Text
  7842. * is rendered to appear inside the area. The area anchor also propagates the
  7843. * interpolate, eccentricity, and tension properties such that an anchored area
  7844. * or line will match positions between control points.
  7845. *
  7846. * <p>For consistency with the other mark types, the anchor positions are
  7847. * defined in terms of their opposite edge. For example, the top anchor defines
  7848. * the bottom property, such that an area added to the top anchor grows upward.
  7849. *
  7850. * @param {string} name the anchor name; either a string or a property function.
  7851. * @returns {pv.Anchor}
  7852. */
  7853. pv.Area.prototype.anchor = function(name) {
  7854. var scene;
  7855. return pv.Mark.prototype.anchor.call(this, name)
  7856. .def("$area.anchor", function() {
  7857. scene = this.scene.target;
  7858. })
  7859. .interpolate(function() {
  7860. return scene[this.index].interpolate;
  7861. })
  7862. .eccentricity(function() {
  7863. return scene[this.index].eccentricity;
  7864. })
  7865. .tension(function() {
  7866. return scene[this.index].tension;
  7867. });
  7868. };
  7869. /**
  7870. * Constructs a new bar mark with default properties. Bars are not typically
  7871. * constructed directly, but by adding to a panel or an existing mark via
  7872. * {@link pv.Mark#add}.
  7873. *
  7874. * @class Represents a bar: an axis-aligned rectangle that can be stroked and
  7875. * filled. Bars are used for many chart types, including bar charts, histograms
  7876. * and Gantt charts. Bars can also be used as decorations, for example to draw a
  7877. * frame border around a panel; in fact, a panel is a special type (a subclass)
  7878. * of bar.
  7879. *
  7880. * <p>Bars can be positioned in several ways. Most commonly, one of the four
  7881. * corners is fixed using two margins, and then the width and height properties
  7882. * determine the extent of the bar relative to this fixed location. For example,
  7883. * using the bottom and left properties fixes the bottom-left corner; the width
  7884. * then extends to the right, while the height extends to the top. As an
  7885. * alternative to the four corners, a bar can be positioned exclusively using
  7886. * margins; this is convenient as an inset from the containing panel, for
  7887. * example. See {@link pv.Mark} for details on the prioritization of redundant
  7888. * positioning properties.
  7889. *
  7890. * <p>See also the <a href="../../api/Bar.html">Bar guide</a>.
  7891. *
  7892. * @extends pv.Mark
  7893. */
  7894. pv.Bar = function() {
  7895. pv.Mark.call(this);
  7896. };
  7897. pv.Bar.prototype = pv.extend(pv.Mark)
  7898. .property("width", Number)
  7899. .property("height", Number)
  7900. .property("lineWidth", Number)
  7901. .property("strokeStyle", pv.color)
  7902. .property("fillStyle", pv.color);
  7903. pv.Bar.prototype.type = "bar";
  7904. /**
  7905. * The width of the bar, in pixels. If the left position is specified, the bar
  7906. * extends rightward from the left edge; if the right position is specified, the
  7907. * bar extends leftward from the right edge.
  7908. *
  7909. * @type number
  7910. * @name pv.Bar.prototype.width
  7911. */
  7912. /**
  7913. * The height of the bar, in pixels. If the bottom position is specified, the
  7914. * bar extends upward from the bottom edge; if the top position is specified,
  7915. * the bar extends downward from the top edge.
  7916. *
  7917. * @type number
  7918. * @name pv.Bar.prototype.height
  7919. */
  7920. /**
  7921. * The width of stroked lines, in pixels; used in conjunction with
  7922. * <tt>strokeStyle</tt> to stroke the bar's border.
  7923. *
  7924. * @type number
  7925. * @name pv.Bar.prototype.lineWidth
  7926. */
  7927. /**
  7928. * The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
  7929. * stroke the bar's border. The default value of this property is null, meaning
  7930. * bars are not stroked by default.
  7931. *
  7932. * @type string
  7933. * @name pv.Bar.prototype.strokeStyle
  7934. * @see pv.color
  7935. */
  7936. /**
  7937. * The bar fill style; if non-null, the interior of the bar is filled with the
  7938. * specified color. The default value of this property is a categorical color.
  7939. *
  7940. * @type string
  7941. * @name pv.Bar.prototype.fillStyle
  7942. * @see pv.color
  7943. */
  7944. /**
  7945. * Default properties for bars. By default, there is no stroke and the fill
  7946. * style is a categorical color.
  7947. *
  7948. * @type pv.Bar
  7949. */
  7950. pv.Bar.prototype.defaults = new pv.Bar()
  7951. .extend(pv.Mark.prototype.defaults)
  7952. .lineWidth(1.5)
  7953. .fillStyle(pv.Colors.category20().by(pv.parent));
  7954. /**
  7955. * Constructs a new dot mark with default properties. Dots are not typically
  7956. * constructed directly, but by adding to a panel or an existing mark via
  7957. * {@link pv.Mark#add}.
  7958. *
  7959. * @class Represents a dot; a dot is simply a sized glyph centered at a given
  7960. * point that can also be stroked and filled. The <tt>size</tt> property is
  7961. * proportional to the area of the rendered glyph to encourage meaningful visual
  7962. * encodings. Dots can visually encode up to eight dimensions of data, though
  7963. * this may be unwise due to integrality. See {@link pv.Mark} for details on the
  7964. * prioritization of redundant positioning properties.
  7965. *
  7966. * <p>See also the <a href="../../api/Dot.html">Dot guide</a>.
  7967. *
  7968. * @extends pv.Mark
  7969. */
  7970. pv.Dot = function() {
  7971. pv.Mark.call(this);
  7972. };
  7973. pv.Dot.prototype = pv.extend(pv.Mark)
  7974. .property("size", Number)
  7975. .property("radius", Number)
  7976. .property("shape", String)
  7977. .property("angle", Number)
  7978. .property("lineWidth", Number)
  7979. .property("strokeStyle", pv.color)
  7980. .property("fillStyle", pv.color);
  7981. pv.Dot.prototype.type = "dot";
  7982. /**
  7983. * The size of the dot, in square pixels. Square pixels are used such that the
  7984. * area of the dot is linearly proportional to the value of the size property,
  7985. * facilitating representative encodings.
  7986. *
  7987. * @see #radius
  7988. * @type number
  7989. * @name pv.Dot.prototype.size
  7990. */
  7991. /**
  7992. * The radius of the dot, in pixels. This is an alternative to using
  7993. * {@link #size}.
  7994. *
  7995. * @see #size
  7996. * @type number
  7997. * @name pv.Dot.prototype.radius
  7998. */
  7999. /**
  8000. * The shape name. Several shapes are supported:<ul>
  8001. *
  8002. * <li>cross
  8003. * <li>triangle
  8004. * <li>diamond
  8005. * <li>square
  8006. * <li>circle
  8007. * <li>tick
  8008. * <li>bar
  8009. *
  8010. * </ul>These shapes can be further changed using the {@link #angle} property;
  8011. * for instance, a cross can be turned into a plus by rotating. Similarly, the
  8012. * tick, which is vertical by default, can be rotated horizontally. Note that
  8013. * some shapes (cross and tick) do not have interior areas, and thus do not
  8014. * support fill style meaningfully.
  8015. *
  8016. * <p>Note: it may be more natural to use the {@link pv.Rule} mark for
  8017. * horizontal and vertical ticks. The tick shape is only necessary if angled
  8018. * ticks are needed.
  8019. *
  8020. * @type string
  8021. * @name pv.Dot.prototype.shape
  8022. */
  8023. /**
  8024. * The rotation angle, in radians. Used to rotate shapes, such as to turn a
  8025. * cross into a plus.
  8026. *
  8027. * @type number
  8028. * @name pv.Dot.prototype.angle
  8029. */
  8030. /**
  8031. * The width of stroked lines, in pixels; used in conjunction with
  8032. * <tt>strokeStyle</tt> to stroke the dot's shape.
  8033. *
  8034. * @type number
  8035. * @name pv.Dot.prototype.lineWidth
  8036. */
  8037. /**
  8038. * The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
  8039. * stroke the dot's shape. The default value of this property is a categorical
  8040. * color.
  8041. *
  8042. * @type string
  8043. * @name pv.Dot.prototype.strokeStyle
  8044. * @see pv.color
  8045. */
  8046. /**
  8047. * The fill style; if non-null, the interior of the dot is filled with the
  8048. * specified color. The default value of this property is null, meaning dots are
  8049. * not filled by default.
  8050. *
  8051. * @type string
  8052. * @name pv.Dot.prototype.fillStyle
  8053. * @see pv.color
  8054. */
  8055. /**
  8056. * Default properties for dots. By default, there is no fill and the stroke
  8057. * style is a categorical color. The default shape is "circle" with size 20.
  8058. *
  8059. * @type pv.Dot
  8060. */
  8061. pv.Dot.prototype.defaults = new pv.Dot()
  8062. .extend(pv.Mark.prototype.defaults)
  8063. .size(20)
  8064. .shape("circle")
  8065. .lineWidth(1.5)
  8066. .strokeStyle(pv.Colors.category10().by(pv.parent));
  8067. /**
  8068. * Constructs a new dot anchor with default properties. Dots support five
  8069. * different anchors:<ul>
  8070. *
  8071. * <li>top
  8072. * <li>left
  8073. * <li>center
  8074. * <li>bottom
  8075. * <li>right
  8076. *
  8077. * </ul>In addition to positioning properties (left, right, top bottom), the
  8078. * anchors support text rendering properties (text-align, text-baseline). Text is
  8079. * rendered to appear outside the dot. Note that this behavior is different from
  8080. * other mark anchors, which default to rendering text <i>inside</i> the mark.
  8081. *
  8082. * <p>For consistency with the other mark types, the anchor positions are
  8083. * defined in terms of their opposite edge. For example, the top anchor defines
  8084. * the bottom property, such that a bar added to the top anchor grows upward.
  8085. *
  8086. * @param {string} name the anchor name; either a string or a property function.
  8087. * @returns {pv.Anchor}
  8088. */
  8089. pv.Dot.prototype.anchor = function(name) {
  8090. var scene;
  8091. return pv.Mark.prototype.anchor.call(this, name)
  8092. .def("$wedge.anchor", function() {
  8093. scene = this.scene.target;
  8094. })
  8095. .left(function() {
  8096. var s = scene[this.index];
  8097. switch (this.name()) {
  8098. case "bottom":
  8099. case "top":
  8100. case "center": return s.left;
  8101. case "left": return null;
  8102. }
  8103. return s.left + s.radius;
  8104. })
  8105. .right(function() {
  8106. var s = scene[this.index];
  8107. return this.name() == "left" ? s.right + s.radius : null;
  8108. })
  8109. .top(function() {
  8110. var s = scene[this.index];
  8111. switch (this.name()) {
  8112. case "left":
  8113. case "right":
  8114. case "center": return s.top;
  8115. case "top": return null;
  8116. }
  8117. return s.top + s.radius;
  8118. })
  8119. .bottom(function() {
  8120. var s = scene[this.index];
  8121. return this.name() == "top" ? s.bottom + s.radius : null;
  8122. })
  8123. .textAlign(function() {
  8124. switch (this.name()) {
  8125. case "left": return "right";
  8126. case "bottom":
  8127. case "top":
  8128. case "center": return "center";
  8129. }
  8130. return "left";
  8131. })
  8132. .textBaseline(function() {
  8133. switch (this.name()) {
  8134. case "right":
  8135. case "left":
  8136. case "center": return "middle";
  8137. case "bottom": return "top";
  8138. }
  8139. return "bottom";
  8140. });
  8141. };
  8142. /** @private Sets radius based on size or vice versa. */
  8143. pv.Dot.prototype.buildImplied = function(s) {
  8144. if (s.radius == null) s.radius = Math.sqrt(s.size);
  8145. else if (s.size == null) s.size = s.radius * s.radius;
  8146. pv.Mark.prototype.buildImplied.call(this, s);
  8147. };
  8148. /**
  8149. * Constructs a new label mark with default properties. Labels are not typically
  8150. * constructed directly, but by adding to a panel or an existing mark via
  8151. * {@link pv.Mark#add}.
  8152. *
  8153. * @class Represents a text label, allowing textual annotation of other marks or
  8154. * arbitrary text within the visualization. The character data must be plain
  8155. * text (unicode), though the text can be styled using the {@link #font}
  8156. * property. If rich text is needed, external HTML elements can be overlaid on
  8157. * the canvas by hand.
  8158. *
  8159. * <p>Labels are positioned using the box model, similarly to {@link Dot}. Thus,
  8160. * a label has no width or height, but merely a text anchor location. The text
  8161. * is positioned relative to this anchor location based on the
  8162. * {@link #textAlign}, {@link #textBaseline} and {@link #textMargin} properties.
  8163. * Furthermore, the text may be rotated using {@link #textAngle}.
  8164. *
  8165. * <p>Labels ignore events, so as to not interfere with event handlers on
  8166. * underlying marks, such as bars. In the future, we may support event handlers
  8167. * on labels.
  8168. *
  8169. * <p>See also the <a href="../../api/Label.html">Label guide</a>.
  8170. *
  8171. * @extends pv.Mark
  8172. */
  8173. pv.Label = function() {
  8174. pv.Mark.call(this);
  8175. };
  8176. pv.Label.prototype = pv.extend(pv.Mark)
  8177. .property("text", String)
  8178. .property("font", String)
  8179. .property("textAngle", Number)
  8180. .property("textStyle", pv.color)
  8181. .property("textAlign", String)
  8182. .property("textBaseline", String)
  8183. .property("textMargin", Number)
  8184. .property("textDecoration", String)
  8185. .property("textShadow", String);
  8186. pv.Label.prototype.type = "label";
  8187. /**
  8188. * The character data to render; a string. The default value of the text
  8189. * property is the identity function, meaning the label's associated datum will
  8190. * be rendered using its <tt>toString</tt>.
  8191. *
  8192. * @type string
  8193. * @name pv.Label.prototype.text
  8194. */
  8195. /**
  8196. * The font format, per the CSS Level 2 specification. The default font is "10px
  8197. * sans-serif", for consistency with the HTML 5 canvas element specification.
  8198. * Note that since text is not wrapped, any line-height property will be
  8199. * ignored. The other font-style, font-variant, font-weight, font-size and
  8200. * font-family properties are supported.
  8201. *
  8202. * @see <a href="http://www.w3.org/TR/CSS2/fonts.html#font-shorthand">CSS2 fonts</a>
  8203. * @type string
  8204. * @name pv.Label.prototype.font
  8205. */
  8206. /**
  8207. * The rotation angle, in radians. Text is rotated clockwise relative to the
  8208. * anchor location. For example, with the default left alignment, an angle of
  8209. * Math.PI / 2 causes text to proceed downwards. The default angle is zero.
  8210. *
  8211. * @type number
  8212. * @name pv.Label.prototype.textAngle
  8213. */
  8214. /**
  8215. * The text color. The name "textStyle" is used for consistency with "fillStyle"
  8216. * and "strokeStyle", although it might be better to rename this property (and
  8217. * perhaps use the same name as "strokeStyle"). The default color is black.
  8218. *
  8219. * @type string
  8220. * @name pv.Label.prototype.textStyle
  8221. * @see pv.color
  8222. */
  8223. /**
  8224. * The horizontal text alignment. One of:<ul>
  8225. *
  8226. * <li>left
  8227. * <li>center
  8228. * <li>right
  8229. *
  8230. * </ul>The default horizontal alignment is left.
  8231. *
  8232. * @type string
  8233. * @name pv.Label.prototype.textAlign
  8234. */
  8235. /**
  8236. * The vertical text alignment. One of:<ul>
  8237. *
  8238. * <li>top
  8239. * <li>middle
  8240. * <li>bottom
  8241. *
  8242. * </ul>The default vertical alignment is bottom.
  8243. *
  8244. * @type string
  8245. * @name pv.Label.prototype.textBaseline
  8246. */
  8247. /**
  8248. * The text margin; may be specified in pixels, or in font-dependent units (such
  8249. * as ".1ex"). The margin can be used to pad text away from its anchor location,
  8250. * in a direction dependent on the horizontal and vertical alignment
  8251. * properties. For example, if the text is left- and middle-aligned, the margin
  8252. * shifts the text to the right. The default margin is 3 pixels.
  8253. *
  8254. * @type number
  8255. * @name pv.Label.prototype.textMargin
  8256. */
  8257. /**
  8258. * A list of shadow effects to be applied to text, per the CSS Text Level 3
  8259. * text-shadow property. An example specification is "0.1em 0.1em 0.1em
  8260. * rgba(0,0,0,.5)"; the first length is the horizontal offset, the second the
  8261. * vertical offset, and the third the blur radius.
  8262. *
  8263. * @see <a href="http://www.w3.org/TR/css3-text/#text-shadow">CSS3 text</a>
  8264. * @type string
  8265. * @name pv.Label.prototype.textShadow
  8266. */
  8267. /**
  8268. * A list of decoration to be applied to text, per the CSS Text Level 3
  8269. * text-decoration property. An example specification is "underline".
  8270. *
  8271. * @see <a href="http://www.w3.org/TR/css3-text/#text-decoration">CSS3 text</a>
  8272. * @type string
  8273. * @name pv.Label.prototype.textDecoration
  8274. */
  8275. /**
  8276. * Default properties for labels. See the individual properties for the default
  8277. * values.
  8278. *
  8279. * @type pv.Label
  8280. */
  8281. pv.Label.prototype.defaults = new pv.Label()
  8282. .extend(pv.Mark.prototype.defaults)
  8283. .events("none")
  8284. .text(pv.identity)
  8285. .font("10px sans-serif")
  8286. .textAngle(0)
  8287. .textStyle("black")
  8288. .textAlign("left")
  8289. .textBaseline("bottom")
  8290. .textMargin(3);
  8291. /**
  8292. * Constructs a new line mark with default properties. Lines are not typically
  8293. * constructed directly, but by adding to a panel or an existing mark via
  8294. * {@link pv.Mark#add}.
  8295. *
  8296. * @class Represents a series of connected line segments, or <i>polyline</i>,
  8297. * that can be stroked with a configurable color and thickness. Each
  8298. * articulation point in the line corresponds to a datum; for <i>n</i> points,
  8299. * <i>n</i>-1 connected line segments are drawn. The point is positioned using
  8300. * the box model. Arbitrary paths are also possible, allowing radar plots and
  8301. * other custom visualizations.
  8302. *
  8303. * <p>Like areas, lines can be stroked and filled with arbitrary colors. In most
  8304. * cases, lines are only stroked, but the fill style can be used to construct
  8305. * arbitrary polygons.
  8306. *
  8307. * <p>See also the <a href="../../api/Line.html">Line guide</a>.
  8308. *
  8309. * @extends pv.Mark
  8310. */
  8311. pv.Line = function() {
  8312. pv.Mark.call(this);
  8313. };
  8314. pv.Line.prototype = pv.extend(pv.Mark)
  8315. .property("lineWidth", Number)
  8316. .property("lineJoin", String)
  8317. .property("strokeStyle", pv.color)
  8318. .property("fillStyle", pv.color)
  8319. .property("segmented", Boolean)
  8320. .property("interpolate", String)
  8321. .property("eccentricity", Number)
  8322. .property("tension", Number);
  8323. pv.Line.prototype.type = "line";
  8324. /**
  8325. * The width of stroked lines, in pixels; used in conjunction with
  8326. * <tt>strokeStyle</tt> to stroke the line.
  8327. *
  8328. * @type number
  8329. * @name pv.Line.prototype.lineWidth
  8330. */
  8331. /**
  8332. * The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
  8333. * stroke the line. The default value of this property is a categorical color.
  8334. *
  8335. * @type string
  8336. * @name pv.Line.prototype.strokeStyle
  8337. * @see pv.color
  8338. */
  8339. /**
  8340. * The type of corners where two lines meet. Accepted values are "bevel",
  8341. * "round" and "miter". The default value is "miter".
  8342. *
  8343. * <p>For segmented lines, only "miter" joins and "linear" interpolation are
  8344. * currently supported. Any other value, including null, will disable joins,
  8345. * producing disjoint line segments. Note that the miter joins must be computed
  8346. * manually (at least in the current SVG renderer); since this calculation may
  8347. * be expensive and unnecessary for small lines, specifying null can improve
  8348. * performance significantly.
  8349. *
  8350. * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
  8351. *
  8352. * @type string
  8353. * @name pv.Line.prototype.lineJoin
  8354. */
  8355. /**
  8356. * The line fill style; if non-null, the interior of the line is closed and
  8357. * filled with the specified color. The default value of this property is a
  8358. * null, meaning that lines are not filled by default.
  8359. *
  8360. * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
  8361. *
  8362. * @type string
  8363. * @name pv.Line.prototype.fillStyle
  8364. * @see pv.color
  8365. */
  8366. /**
  8367. * Whether the line is segmented; whether variations in stroke style, line width
  8368. * and the other properties are treated as fixed. Rendering segmented lines is
  8369. * noticeably slower than non-segmented lines.
  8370. *
  8371. * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
  8372. *
  8373. * @type boolean
  8374. * @name pv.Line.prototype.segmented
  8375. */
  8376. /**
  8377. * How to interpolate between values. Linear interpolation ("linear") is the
  8378. * default, producing a straight line between points. For piecewise constant
  8379. * functions (i.e., step functions), either "step-before" or "step-after" can be
  8380. * specified. To draw a clockwise circular arc between points, specify "polar";
  8381. * to draw a counterclockwise circular arc between points, specify
  8382. * "polar-reverse". To draw open uniform b-splines, specify "basis". To draw
  8383. * cardinal splines, specify "cardinal"; see also {@link #tension}.
  8384. *
  8385. * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
  8386. *
  8387. * @type string
  8388. * @name pv.Line.prototype.interpolate
  8389. */
  8390. /**
  8391. * The eccentricity of polar line segments; used in conjunction with
  8392. * interpolate("polar"). The default value of 0 means that line segments are
  8393. * drawn as circular arcs. A value of 1 draws a straight line. A value between 0
  8394. * and 1 draws an elliptical arc with the given eccentricity.
  8395. *
  8396. * @type number
  8397. * @name pv.Line.prototype.eccentricity
  8398. */
  8399. /**
  8400. * The tension of cardinal splines; used in conjunction with
  8401. * interpolate("cardinal"). A value between 0 and 1 draws cardinal splines with
  8402. * the given tension. In some sense, the tension can be interpreted as the
  8403. * "length" of the tangent; a tension of 1 will yield all zero tangents (i.e.,
  8404. * linear interpolation), and a tension of 0 yields a Catmull-Rom spline. The
  8405. * default value is 0.7.
  8406. *
  8407. * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
  8408. *
  8409. * @type number
  8410. * @name pv.Line.prototype.tension
  8411. */
  8412. /**
  8413. * Default properties for lines. By default, there is no fill and the stroke
  8414. * style is a categorical color. The default interpolation is linear.
  8415. *
  8416. * @type pv.Line
  8417. */
  8418. pv.Line.prototype.defaults = new pv.Line()
  8419. .extend(pv.Mark.prototype.defaults)
  8420. .lineJoin("miter")
  8421. .lineWidth(1.5)
  8422. .strokeStyle(pv.Colors.category10().by(pv.parent))
  8423. .interpolate("linear")
  8424. .eccentricity(0)
  8425. .tension(.7);
  8426. /** @private Reuse Area's implementation for segmented bind & build. */
  8427. pv.Line.prototype.bind = pv.Area.prototype.bind;
  8428. pv.Line.prototype.buildInstance = pv.Area.prototype.buildInstance;
  8429. /**
  8430. * Constructs a new line anchor with default properties. Lines support five
  8431. * different anchors:<ul>
  8432. *
  8433. * <li>top
  8434. * <li>left
  8435. * <li>center
  8436. * <li>bottom
  8437. * <li>right
  8438. *
  8439. * </ul>In addition to positioning properties (left, right, top bottom), the
  8440. * anchors support text rendering properties (text-align, text-baseline). Text is
  8441. * rendered to appear outside the line. Note that this behavior is different
  8442. * from other mark anchors, which default to rendering text <i>inside</i> the
  8443. * mark.
  8444. *
  8445. * <p>For consistency with the other mark types, the anchor positions are
  8446. * defined in terms of their opposite edge. For example, the top anchor defines
  8447. * the bottom property, such that a bar added to the top anchor grows upward.
  8448. *
  8449. * @param {string} name the anchor name; either a string or a property function.
  8450. * @returns {pv.Anchor}
  8451. */
  8452. pv.Line.prototype.anchor = function(name) {
  8453. return pv.Area.prototype.anchor.call(this, name)
  8454. .textAlign(function(d) {
  8455. switch (this.name()) {
  8456. case "left": return "right";
  8457. case "bottom":
  8458. case "top":
  8459. case "center": return "center";
  8460. case "right": return "left";
  8461. }
  8462. })
  8463. .textBaseline(function(d) {
  8464. switch (this.name()) {
  8465. case "right":
  8466. case "left":
  8467. case "center": return "middle";
  8468. case "top": return "bottom";
  8469. case "bottom": return "top";
  8470. }
  8471. });
  8472. };
  8473. /**
  8474. * Constructs a new rule with default properties. Rules are not typically
  8475. * constructed directly, but by adding to a panel or an existing mark via
  8476. * {@link pv.Mark#add}.
  8477. *
  8478. * @class Represents a horizontal or vertical rule. Rules are frequently used
  8479. * for axes and grid lines. For example, specifying only the bottom property
  8480. * draws horizontal rules, while specifying only the left draws vertical
  8481. * rules. Rules can also be used as thin bars. The visual style is controlled in
  8482. * the same manner as lines.
  8483. *
  8484. * <p>Rules are positioned exclusively the standard box model properties. The
  8485. * following combinations of properties are supported:
  8486. *
  8487. * <table>
  8488. * <thead><th style="width:12em;">Properties</th><th>Orientation</th></thead>
  8489. * <tbody>
  8490. * <tr><td>left</td><td>vertical</td></tr>
  8491. * <tr><td>right</td><td>vertical</td></tr>
  8492. * <tr><td>left, bottom, top</td><td>vertical</td></tr>
  8493. * <tr><td>right, bottom, top</td><td>vertical</td></tr>
  8494. * <tr><td>top</td><td>horizontal</td></tr>
  8495. * <tr><td>bottom</td><td>horizontal</td></tr>
  8496. * <tr><td>top, left, right</td><td>horizontal</td></tr>
  8497. * <tr><td>bottom, left, right</td><td>horizontal</td></tr>
  8498. * <tr><td>left, top, height</td><td>vertical</td></tr>
  8499. * <tr><td>left, bottom, height</td><td>vertical</td></tr>
  8500. * <tr><td>right, top, height</td><td>vertical</td></tr>
  8501. * <tr><td>right, bottom, height</td><td>vertical</td></tr>
  8502. * <tr><td>left, top, width</td><td>horizontal</td></tr>
  8503. * <tr><td>left, bottom, width</td><td>horizontal</td></tr>
  8504. * <tr><td>right, top, width</td><td>horizontal</td></tr>
  8505. * <tr><td>right, bottom, width</td><td>horizontal</td></tr>
  8506. * </tbody>
  8507. * </table>
  8508. *
  8509. * <p>Small rules can be used as tick marks; alternatively, a {@link Dot} with
  8510. * the "tick" shape can be used.
  8511. *
  8512. * <p>See also the <a href="../../api/Rule.html">Rule guide</a>.
  8513. *
  8514. * @see pv.Line
  8515. * @extends pv.Mark
  8516. */
  8517. pv.Rule = function() {
  8518. pv.Mark.call(this);
  8519. };
  8520. pv.Rule.prototype = pv.extend(pv.Mark)
  8521. .property("width", Number)
  8522. .property("height", Number)
  8523. .property("lineWidth", Number)
  8524. .property("strokeStyle", pv.color);
  8525. pv.Rule.prototype.type = "rule";
  8526. /**
  8527. * The width of the rule, in pixels. If the left position is specified, the rule
  8528. * extends rightward from the left edge; if the right position is specified, the
  8529. * rule extends leftward from the right edge.
  8530. *
  8531. * @type number
  8532. * @name pv.Rule.prototype.width
  8533. */
  8534. /**
  8535. * The height of the rule, in pixels. If the bottom position is specified, the
  8536. * rule extends upward from the bottom edge; if the top position is specified,
  8537. * the rule extends downward from the top edge.
  8538. *
  8539. * @type number
  8540. * @name pv.Rule.prototype.height
  8541. */
  8542. /**
  8543. * The width of stroked lines, in pixels; used in conjunction with
  8544. * <tt>strokeStyle</tt> to stroke the rule. The default value is 1 pixel.
  8545. *
  8546. * @type number
  8547. * @name pv.Rule.prototype.lineWidth
  8548. */
  8549. /**
  8550. * The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
  8551. * stroke the rule. The default value of this property is black.
  8552. *
  8553. * @type string
  8554. * @name pv.Rule.prototype.strokeStyle
  8555. * @see pv.color
  8556. */
  8557. /**
  8558. * Default properties for rules. By default, a single-pixel black line is
  8559. * stroked.
  8560. *
  8561. * @type pv.Rule
  8562. */
  8563. pv.Rule.prototype.defaults = new pv.Rule()
  8564. .extend(pv.Mark.prototype.defaults)
  8565. .lineWidth(1)
  8566. .strokeStyle("black")
  8567. .antialias(false);
  8568. /**
  8569. * Constructs a new rule anchor with default properties. Rules support five
  8570. * different anchors:<ul>
  8571. *
  8572. * <li>top
  8573. * <li>left
  8574. * <li>center
  8575. * <li>bottom
  8576. * <li>right
  8577. *
  8578. * </ul>In addition to positioning properties (left, right, top bottom), the
  8579. * anchors support text rendering properties (text-align, text-baseline). Text is
  8580. * rendered to appear outside the rule. Note that this behavior is different
  8581. * from other mark anchors, which default to rendering text <i>inside</i> the
  8582. * mark.
  8583. *
  8584. * <p>For consistency with the other mark types, the anchor positions are
  8585. * defined in terms of their opposite edge. For example, the top anchor defines
  8586. * the bottom property, such that a bar added to the top anchor grows upward.
  8587. *
  8588. * @param {string} name the anchor name; either a string or a property function.
  8589. * @returns {pv.Anchor}
  8590. */
  8591. pv.Rule.prototype.anchor = pv.Line.prototype.anchor;
  8592. /** @private Sets width or height based on orientation. */
  8593. pv.Rule.prototype.buildImplied = function(s) {
  8594. var l = s.left, r = s.right, t = s.top, b = s.bottom;
  8595. /* Determine horizontal or vertical orientation. */
  8596. if ((s.width != null)
  8597. || ((l == null) && (r == null))
  8598. || ((r != null) && (l != null))) {
  8599. s.height = 0;
  8600. } else {
  8601. s.width = 0;
  8602. }
  8603. pv.Mark.prototype.buildImplied.call(this, s);
  8604. };
  8605. /**
  8606. * Constructs a new, empty panel with default properties. Panels, with the
  8607. * exception of the root panel, are not typically constructed directly; instead,
  8608. * they are added to an existing panel or mark via {@link pv.Mark#add}.
  8609. *
  8610. * @class Represents a container mark. Panels allow repeated or nested
  8611. * structures, commonly used in small multiple displays where a small
  8612. * visualization is tiled to facilitate comparison across one or more
  8613. * dimensions. Other types of visualizations may benefit from repeated and
  8614. * possibly overlapping structure as well, such as stacked area charts. Panels
  8615. * can also offset the position of marks to provide padding from surrounding
  8616. * content.
  8617. *
  8618. * <p>All Protovis displays have at least one panel; this is the root panel to
  8619. * which marks are rendered. The box model properties (four margins, width and
  8620. * height) are used to offset the positions of contained marks. The data
  8621. * property determines the panel count: a panel is generated once per associated
  8622. * datum. When nested panels are used, property functions can declare additional
  8623. * arguments to access the data associated with enclosing panels.
  8624. *
  8625. * <p>Panels can be rendered inline, facilitating the creation of sparklines.
  8626. * This allows designers to reuse browser layout features, such as text flow and
  8627. * tables; designers can also overlay HTML elements such as rich text and
  8628. * images.
  8629. *
  8630. * <p>All panels have a <tt>children</tt> array (possibly empty) containing the
  8631. * child marks in the order they were added. Panels also have a <tt>root</tt>
  8632. * field which points to the root (outermost) panel; the root panel's root field
  8633. * points to itself.
  8634. *
  8635. * <p>See also the <a href="../../api/">Protovis guide</a>.
  8636. *
  8637. * @extends pv.Bar
  8638. */
  8639. pv.Panel = function() {
  8640. pv.Bar.call(this);
  8641. /**
  8642. * The child marks; zero or more {@link pv.Mark}s in the order they were
  8643. * added.
  8644. *
  8645. * @see #add
  8646. * @type pv.Mark[]
  8647. */
  8648. this.children = [];
  8649. this.root = this;
  8650. /**
  8651. * The internal $dom field is set by the Protovis loader; see lang/init.js. It
  8652. * refers to the script element that contains the Protovis specification, so
  8653. * that the panel knows where in the DOM to insert the generated SVG element.
  8654. *
  8655. * @private
  8656. */
  8657. this.$dom = pv.$ && pv.$.s;
  8658. };
  8659. pv.Panel.prototype = pv.extend(pv.Bar)
  8660. .property("transform")
  8661. .property("overflow", String)
  8662. .property("canvas", function(c) {
  8663. return (typeof c == "string")
  8664. ? document.getElementById(c)
  8665. : c; // assume that c is the passed-in element
  8666. });
  8667. pv.Panel.prototype.type = "panel";
  8668. /**
  8669. * The canvas element; either the string ID of the canvas element in the current
  8670. * document, or a reference to the canvas element itself. If null, a canvas
  8671. * element will be created and inserted into the document at the location of the
  8672. * script element containing the current Protovis specification. This property
  8673. * only applies to root panels and is ignored on nested panels.
  8674. *
  8675. * <p>Note: the "canvas" element here refers to a <tt>div</tt> (or other suitable
  8676. * HTML container element), <i>not</i> a <tt>canvas</tt> element. The name of
  8677. * this property is a historical anachronism from the first implementation that
  8678. * used HTML 5 canvas, rather than SVG.
  8679. *
  8680. * @type string
  8681. * @name pv.Panel.prototype.canvas
  8682. */
  8683. /**
  8684. * Specifies whether child marks are clipped when they overflow this panel.
  8685. * This affects the clipping of all this panel's descendant marks.
  8686. *
  8687. * @type string
  8688. * @name pv.Panel.prototype.overflow
  8689. * @see <a href="http://www.w3.org/TR/CSS2/visufx.html#overflow">CSS2</a>
  8690. */
  8691. /**
  8692. * The transform to be applied to child marks. The default transform is
  8693. * identity, which has no effect. Note that the panel's own fill and stroke are
  8694. * not affected by the transform, and panel's transform only affects the
  8695. * <tt>scale</tt> of child marks, not the panel itself.
  8696. *
  8697. * @type pv.Transform
  8698. * @name pv.Panel.prototype.transform
  8699. * @see pv.Mark#scale
  8700. */
  8701. /**
  8702. * Default properties for panels. By default, the margins are zero, the fill
  8703. * style is transparent.
  8704. *
  8705. * @type pv.Panel
  8706. */
  8707. pv.Panel.prototype.defaults = new pv.Panel()
  8708. .extend(pv.Bar.prototype.defaults)
  8709. .fillStyle(null) // override Bar default
  8710. .overflow("visible");
  8711. /**
  8712. * Returns an anchor with the specified name. This method is overridden such
  8713. * that adding to a panel's anchor adds to the panel, rather than to the panel's
  8714. * parent.
  8715. *
  8716. * @param {string} name the anchor name; either a string or a property function.
  8717. * @returns {pv.Anchor} the new anchor.
  8718. */
  8719. pv.Panel.prototype.anchor = function(name) {
  8720. var anchor = pv.Bar.prototype.anchor.call(this, name);
  8721. anchor.parent = this;
  8722. return anchor;
  8723. };
  8724. /**
  8725. * Adds a new mark of the specified type to this panel. Unlike the normal
  8726. * {@link Mark#add} behavior, adding a mark to a panel does not cause the mark
  8727. * to inherit from the panel. Since the contained marks are offset by the panel
  8728. * margins already, inheriting properties is generally undesirable; of course,
  8729. * it is always possible to change this behavior by calling {@link Mark#extend}
  8730. * explicitly.
  8731. *
  8732. * @param {function} type the type of the new mark to add.
  8733. * @returns {pv.Mark} the new mark.
  8734. */
  8735. pv.Panel.prototype.add = function(type) {
  8736. var child = new type();
  8737. child.parent = this;
  8738. child.root = this.root;
  8739. child.childIndex = this.children.length;
  8740. this.children.push(child);
  8741. return child;
  8742. };
  8743. /** @private Bind this panel, then any child marks recursively. */
  8744. pv.Panel.prototype.bind = function() {
  8745. pv.Mark.prototype.bind.call(this);
  8746. for (var i = 0; i < this.children.length; i++) {
  8747. this.children[i].bind();
  8748. }
  8749. };
  8750. /**
  8751. * @private Evaluates all of the properties for this panel for the specified
  8752. * instance <tt>s</tt> in the scene graph, including recursively building the
  8753. * scene graph for child marks.
  8754. *
  8755. * @param s a node in the scene graph; the instance of the panel to build.
  8756. * @see Mark#scene
  8757. */
  8758. pv.Panel.prototype.buildInstance = function(s) {
  8759. pv.Bar.prototype.buildInstance.call(this, s);
  8760. if (!s.visible) return;
  8761. if (!s.children) s.children = [];
  8762. /*
  8763. * Multiply the current scale factor by this panel's transform. Also clear the
  8764. * default index as we recurse into child marks; it will be reset to the
  8765. * current index when the next panel instance is built.
  8766. */
  8767. var scale = this.scale * s.transform.k, child, n = this.children.length;
  8768. pv.Mark.prototype.index = -1;
  8769. /*
  8770. * Build each child, passing in the parent (this panel) scene graph node. The
  8771. * child mark's scene is initialized from the corresponding entry in the
  8772. * existing scene graph, such that properties from the previous build can be
  8773. * reused; this is largely to facilitate the recycling of SVG elements.
  8774. */
  8775. for (var i = 0; i < n; i++) {
  8776. child = this.children[i];
  8777. child.scene = s.children[i]; // possibly undefined
  8778. child.scale = scale;
  8779. child.build();
  8780. }
  8781. /*
  8782. * Once the child marks have been built, the new scene graph nodes are removed
  8783. * from the child marks and placed into the scene graph. The nodes cannot
  8784. * remain on the child nodes because this panel (or a parent panel) may be
  8785. * instantiated multiple times!
  8786. */
  8787. for (var i = 0; i < n; i++) {
  8788. child = this.children[i];
  8789. s.children[i] = child.scene;
  8790. delete child.scene;
  8791. delete child.scale;
  8792. }
  8793. /* Delete any expired child scenes. */
  8794. s.children.length = n;
  8795. };
  8796. /**
  8797. * @private Computes the implied properties for this panel for the specified
  8798. * instance <tt>s</tt> in the scene graph. Panels have two implied
  8799. * properties:<ul>
  8800. *
  8801. * <li>The <tt>canvas</tt> property references the DOM element, typically a DIV,
  8802. * that contains the SVG element that is used to display the visualization. This
  8803. * property may be specified as a string, referring to the unique ID of the
  8804. * element in the DOM. The string is converted to a reference to the DOM
  8805. * element. The width and height of the SVG element is inferred from this DOM
  8806. * element. If no canvas property is specified, a new SVG element is created and
  8807. * inserted into the document, using the panel dimensions; see
  8808. * {@link #createCanvas}.
  8809. *
  8810. * <li>The <tt>children</tt> array, while not a property per se, contains the
  8811. * scene graph for each child mark. This array is initialized to be empty, and
  8812. * is populated above in {@link #buildInstance}.
  8813. *
  8814. * </ul>The current implementation creates the SVG element, if necessary, during
  8815. * the build phase; in the future, it may be preferrable to move this to the
  8816. * update phase, although then the canvas property would be undefined. In
  8817. * addition, DOM inspection is necessary to define the implied width and height
  8818. * properties that may be inferred from the DOM.
  8819. *
  8820. * @param s a node in the scene graph; the instance of the panel to build.
  8821. */
  8822. pv.Panel.prototype.buildImplied = function(s) {
  8823. if (!this.parent) {
  8824. var c = s.canvas;
  8825. if (c) {
  8826. /* Clear the container if it's not associated with this panel. */
  8827. if (c.$panel != this) {
  8828. c.$panel = this;
  8829. while (c.lastChild) c.removeChild(c.lastChild);
  8830. }
  8831. /* If width and height weren't specified, inspect the container. */
  8832. var w, h;
  8833. if (s.width == null) {
  8834. w = parseFloat(pv.css(c, "width"));
  8835. s.width = w - s.left - s.right;
  8836. }
  8837. if (s.height == null) {
  8838. h = parseFloat(pv.css(c, "height"));
  8839. s.height = h - s.top - s.bottom;
  8840. }
  8841. } else {
  8842. var cache = this.$canvas || (this.$canvas = []);
  8843. if (!(c = cache[this.index])) {
  8844. c = cache[this.index] = document.createElement("span");
  8845. if (this.$dom) { // script element for text/javascript+protovis
  8846. /*
  8847. * this.$dom.parentNode.insertBefore(c, this.$dom);
  8848. * Changing this line to allow the direct definiton of the element where the graph should be placed
  8849. */
  8850. this.$dom.appendChild(c);
  8851. } else { // find the last element in the body
  8852. var n = document.body;
  8853. while (n.lastChild && n.lastChild.tagName) n = n.lastChild;
  8854. if (n != document.body) n = n.parentNode;
  8855. n.appendChild(c);
  8856. }
  8857. }
  8858. }
  8859. s.canvas = c;
  8860. }
  8861. if (!s.transform) s.transform = pv.Transform.identity;
  8862. pv.Mark.prototype.buildImplied.call(this, s);
  8863. };
  8864. /**
  8865. * Constructs a new image with default properties. Images are not typically
  8866. * constructed directly, but by adding to a panel or an existing mark via
  8867. * {@link pv.Mark#add}.
  8868. *
  8869. * @class Represents an image, either a static resource or a dynamically-
  8870. * generated pixel buffer. Images share the same layout and style properties as
  8871. * bars. The external image resource is specified via the {@link #url}
  8872. * property. The optional fill, if specified, appears beneath the image, while
  8873. * the optional stroke appears above the image.
  8874. *
  8875. * <p>Dynamic images such as heatmaps are supported using the {@link #image}
  8876. * psuedo-property. This function is passed the <i>x</i> and <i>y</i> index, in
  8877. * addition to the current data stack. The return value is a {@link pv.Color},
  8878. * or null for transparent. A string can also be returned, which will be parsed
  8879. * into a color; however, it is typically much faster to return an object with
  8880. * <tt>r</tt>, <tt>g</tt>, <tt>b</tt> and <tt>a</tt> attributes, to avoid the
  8881. * cost of parsing and object instantiation.
  8882. *
  8883. * <p>See {@link pv.Bar} for details on positioning properties.
  8884. *
  8885. * @extends pv.Bar
  8886. */
  8887. pv.Image = function() {
  8888. pv.Bar.call(this);
  8889. };
  8890. pv.Image.prototype = pv.extend(pv.Bar)
  8891. .property("url", String)
  8892. .property("imageWidth", Number)
  8893. .property("imageHeight", Number);
  8894. pv.Image.prototype.type = "image";
  8895. /**
  8896. * The URL of the image to display. The set of supported image types is
  8897. * browser-dependent; PNG and JPEG are recommended.
  8898. *
  8899. * @type string
  8900. * @name pv.Image.prototype.url
  8901. */
  8902. /**
  8903. * The width of the image in pixels. For static images, this property is
  8904. * computed implicitly from the loaded image resources. For dynamic images, this
  8905. * property can be used to specify the width of the pixel buffer; otherwise, the
  8906. * value is derived from the <tt>width</tt> property.
  8907. *
  8908. * @type number
  8909. * @name pv.Image.prototype.imageWidth
  8910. */
  8911. /**
  8912. * The height of the image in pixels. For static images, this property is
  8913. * computed implicitly from the loaded image resources. For dynamic images, this
  8914. * property can be used to specify the height of the pixel buffer; otherwise, the
  8915. * value is derived from the <tt>height</tt> property.
  8916. *
  8917. * @type number
  8918. * @name pv.Image.prototype.imageHeight
  8919. */
  8920. /**
  8921. * Default properties for images. By default, there is no stroke or fill style.
  8922. *
  8923. * @type pv.Image
  8924. */
  8925. pv.Image.prototype.defaults = new pv.Image()
  8926. .extend(pv.Bar.prototype.defaults)
  8927. .fillStyle(null);
  8928. /**
  8929. * Specifies the dynamic image function. By default, no image function is
  8930. * specified and the <tt>url</tt> property is used to load a static image
  8931. * resource. If an image function is specified, it will be invoked for each
  8932. * pixel in the image, based on the related <tt>imageWidth</tt> and
  8933. * <tt>imageHeight</tt> properties.
  8934. *
  8935. * <p>For example, given a two-dimensional array <tt>heatmap</tt>, containing
  8936. * numbers in the range [0, 1] in row-major order, a simple monochrome heatmap
  8937. * image can be specified as:
  8938. *
  8939. * <pre>vis.add(pv.Image)
  8940. * .imageWidth(heatmap[0].length)
  8941. * .imageHeight(heatmap.length)
  8942. * .image(pv.ramp("white", "black").by(function(x, y) heatmap[y][x]));</pre>
  8943. *
  8944. * For fastest performance, use an ordinal scale which caches the fixed color
  8945. * palette, or return an object literal with <tt>r</tt>, <tt>g</tt>, <tt>b</tt>
  8946. * and <tt>a</tt> attributes. A {@link pv.Color} or string can also be returned,
  8947. * though this typically results in slower performance.
  8948. *
  8949. * @param {function} f the new sizing function.
  8950. * @returns {pv.Layout.Pack} this.
  8951. */
  8952. pv.Image.prototype.image = function(f) {
  8953. /** @private */
  8954. this.$image = function() {
  8955. var c = f.apply(this, arguments);
  8956. return c == null ? pv.Color.transparent
  8957. : typeof c == "string" ? pv.color(c)
  8958. : c;
  8959. };
  8960. return this;
  8961. };
  8962. /** @private Scan the proto chain for an image function. */
  8963. pv.Image.prototype.bind = function() {
  8964. pv.Bar.prototype.bind.call(this);
  8965. var binds = this.binds, mark = this;
  8966. do {
  8967. binds.image = mark.$image;
  8968. } while (!binds.image && (mark = mark.proto));
  8969. };
  8970. /** @private */
  8971. pv.Image.prototype.buildImplied = function(s) {
  8972. pv.Bar.prototype.buildImplied.call(this, s);
  8973. if (!s.visible) return;
  8974. /* Compute the implied image dimensions. */
  8975. if (s.imageWidth == null) s.imageWidth = s.width;
  8976. if (s.imageHeight == null) s.imageHeight = s.height;
  8977. /* Compute the pixel values. */
  8978. if ((s.url == null) && this.binds.image) {
  8979. /* Cache the canvas element to reuse across renders. */
  8980. var canvas = this.$canvas || (this.$canvas = document.createElement("canvas")),
  8981. context = canvas.getContext("2d"),
  8982. w = s.imageWidth,
  8983. h = s.imageHeight,
  8984. stack = pv.Mark.stack,
  8985. data;
  8986. /* Evaluate the image function, storing into a CanvasPixelArray. */
  8987. canvas.width = w;
  8988. canvas.height = h;
  8989. data = (s.image = context.createImageData(w, h)).data;
  8990. stack.unshift(null, null);
  8991. for (var y = 0, p = 0; y < h; y++) {
  8992. stack[1] = y;
  8993. for (var x = 0; x < w; x++) {
  8994. stack[0] = x;
  8995. var color = this.binds.image.apply(this, stack);
  8996. data[p++] = color.r;
  8997. data[p++] = color.g;
  8998. data[p++] = color.b;
  8999. data[p++] = 255 * color.a;
  9000. }
  9001. }
  9002. stack.splice(0, 2);
  9003. }
  9004. };
  9005. /**
  9006. * Constructs a new wedge with default properties. Wedges are not typically
  9007. * constructed directly, but by adding to a panel or an existing mark via
  9008. * {@link pv.Mark#add}.
  9009. *
  9010. * @class Represents a wedge, or pie slice. Specified in terms of start and end
  9011. * angle, inner and outer radius, wedges can be used to construct donut charts
  9012. * and polar bar charts as well. If the {@link #angle} property is used, the end
  9013. * angle is implied by adding this value to start angle. By default, the start
  9014. * angle is the previously-generated wedge's end angle. This design allows
  9015. * explicit control over the wedge placement if desired, while offering
  9016. * convenient defaults for the construction of radial graphs.
  9017. *
  9018. * <p>The center point of the circle is positioned using the standard box model.
  9019. * The wedge can be stroked and filled, similar to {@link pv.Bar}.
  9020. *
  9021. * <p>See also the <a href="../../api/Wedge.html">Wedge guide</a>.
  9022. *
  9023. * @extends pv.Mark
  9024. */
  9025. pv.Wedge = function() {
  9026. pv.Mark.call(this);
  9027. };
  9028. pv.Wedge.prototype = pv.extend(pv.Mark)
  9029. .property("startAngle", Number)
  9030. .property("endAngle", Number)
  9031. .property("angle", Number)
  9032. .property("innerRadius", Number)
  9033. .property("outerRadius", Number)
  9034. .property("lineWidth", Number)
  9035. .property("strokeStyle", pv.color)
  9036. .property("fillStyle", pv.color);
  9037. pv.Wedge.prototype.type = "wedge";
  9038. /**
  9039. * The start angle of the wedge, in radians. The start angle is measured
  9040. * clockwise from the 3 o'clock position. The default value of this property is
  9041. * the end angle of the previous instance (the {@link Mark#sibling}), or -PI / 2
  9042. * for the first wedge; for pie and donut charts, typically only the
  9043. * {@link #angle} property needs to be specified.
  9044. *
  9045. * @type number
  9046. * @name pv.Wedge.prototype.startAngle
  9047. */
  9048. /**
  9049. * The end angle of the wedge, in radians. If not specified, the end angle is
  9050. * implied as the start angle plus the {@link #angle}.
  9051. *
  9052. * @type number
  9053. * @name pv.Wedge.prototype.endAngle
  9054. */
  9055. /**
  9056. * The angular span of the wedge, in radians. This property is used if end angle
  9057. * is not specified.
  9058. *
  9059. * @type number
  9060. * @name pv.Wedge.prototype.angle
  9061. */
  9062. /**
  9063. * The inner radius of the wedge, in pixels. The default value of this property
  9064. * is zero; a positive value will produce a donut slice rather than a pie slice.
  9065. * The inner radius can vary per-wedge.
  9066. *
  9067. * @type number
  9068. * @name pv.Wedge.prototype.innerRadius
  9069. */
  9070. /**
  9071. * The outer radius of the wedge, in pixels. This property is required. For
  9072. * pies, only this radius is required; for donuts, the inner radius must be
  9073. * specified as well. The outer radius can vary per-wedge.
  9074. *
  9075. * @type number
  9076. * @name pv.Wedge.prototype.outerRadius
  9077. */
  9078. /**
  9079. * The width of stroked lines, in pixels; used in conjunction with
  9080. * <tt>strokeStyle</tt> to stroke the wedge's border.
  9081. *
  9082. * @type number
  9083. * @name pv.Wedge.prototype.lineWidth
  9084. */
  9085. /**
  9086. * The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
  9087. * stroke the wedge's border. The default value of this property is null,
  9088. * meaning wedges are not stroked by default.
  9089. *
  9090. * @type string
  9091. * @name pv.Wedge.prototype.strokeStyle
  9092. * @see pv.color
  9093. */
  9094. /**
  9095. * The wedge fill style; if non-null, the interior of the wedge is filled with
  9096. * the specified color. The default value of this property is a categorical
  9097. * color.
  9098. *
  9099. * @type string
  9100. * @name pv.Wedge.prototype.fillStyle
  9101. * @see pv.color
  9102. */
  9103. /**
  9104. * Default properties for wedges. By default, there is no stroke and the fill
  9105. * style is a categorical color.
  9106. *
  9107. * @type pv.Wedge
  9108. */
  9109. pv.Wedge.prototype.defaults = new pv.Wedge()
  9110. .extend(pv.Mark.prototype.defaults)
  9111. .startAngle(function() {
  9112. var s = this.sibling();
  9113. return s ? s.endAngle : -Math.PI / 2;
  9114. })
  9115. .innerRadius(0)
  9116. .lineWidth(1.5)
  9117. .strokeStyle(null)
  9118. .fillStyle(pv.Colors.category20().by(pv.index));
  9119. /**
  9120. * Returns the mid-radius of the wedge, which is defined as half-way between the
  9121. * inner and outer radii.
  9122. *
  9123. * @see #innerRadius
  9124. * @see #outerRadius
  9125. * @returns {number} the mid-radius, in pixels.
  9126. */
  9127. pv.Wedge.prototype.midRadius = function() {
  9128. return (this.innerRadius() + this.outerRadius()) / 2;
  9129. };
  9130. /**
  9131. * Returns the mid-angle of the wedge, which is defined as half-way between the
  9132. * start and end angles.
  9133. *
  9134. * @see #startAngle
  9135. * @see #endAngle
  9136. * @returns {number} the mid-angle, in radians.
  9137. */
  9138. pv.Wedge.prototype.midAngle = function() {
  9139. return (this.startAngle() + this.endAngle()) / 2;
  9140. };
  9141. /**
  9142. * Constructs a new wedge anchor with default properties. Wedges support five
  9143. * different anchors:<ul>
  9144. *
  9145. * <li>outer
  9146. * <li>inner
  9147. * <li>center
  9148. * <li>start
  9149. * <li>end
  9150. *
  9151. * </ul>In addition to positioning properties (left, right, top bottom), the
  9152. * anchors support text rendering properties (text-align, text-baseline,
  9153. * textAngle). Text is rendered to appear inside the wedge.
  9154. *
  9155. * @param {string} name the anchor name; either a string or a property function.
  9156. * @returns {pv.Anchor}
  9157. */
  9158. pv.Wedge.prototype.anchor = function(name) {
  9159. function partial(s) { return s.innerRadius || s.angle < 2 * Math.PI; }
  9160. function midRadius(s) { return (s.innerRadius + s.outerRadius) / 2; }
  9161. function midAngle(s) { return (s.startAngle + s.endAngle) / 2; }
  9162. var scene;
  9163. return pv.Mark.prototype.anchor.call(this, name)
  9164. .def("$wedge.anchor", function() {
  9165. scene = this.scene.target;
  9166. })
  9167. .left(function() {
  9168. var s = scene[this.index];
  9169. if (partial(s)) switch (this.name()) {
  9170. case "outer": return s.left + s.outerRadius * Math.cos(midAngle(s));
  9171. case "inner": return s.left + s.innerRadius * Math.cos(midAngle(s));
  9172. case "start": return s.left + midRadius(s) * Math.cos(s.startAngle);
  9173. case "center": return s.left + midRadius(s) * Math.cos(midAngle(s));
  9174. case "end": return s.left + midRadius(s) * Math.cos(s.endAngle);
  9175. }
  9176. return s.left;
  9177. })
  9178. .top(function() {
  9179. var s = scene[this.index];
  9180. if (partial(s)) switch (this.name()) {
  9181. case "outer": return s.top + s.outerRadius * Math.sin(midAngle(s));
  9182. case "inner": return s.top + s.innerRadius * Math.sin(midAngle(s));
  9183. case "start": return s.top + midRadius(s) * Math.sin(s.startAngle);
  9184. case "center": return s.top + midRadius(s) * Math.sin(midAngle(s));
  9185. case "end": return s.top + midRadius(s) * Math.sin(s.endAngle);
  9186. }
  9187. return s.top;
  9188. })
  9189. .textAlign(function() {
  9190. var s = scene[this.index];
  9191. if (partial(s)) switch (this.name()) {
  9192. case "outer": return pv.Wedge.upright(midAngle(s)) ? "right" : "left";
  9193. case "inner": return pv.Wedge.upright(midAngle(s)) ? "left" : "right";
  9194. }
  9195. return "center";
  9196. })
  9197. .textBaseline(function() {
  9198. var s = scene[this.index];
  9199. if (partial(s)) switch (this.name()) {
  9200. case "start": return pv.Wedge.upright(s.startAngle) ? "top" : "bottom";
  9201. case "end": return pv.Wedge.upright(s.endAngle) ? "bottom" : "top";
  9202. }
  9203. return "middle";
  9204. })
  9205. .textAngle(function() {
  9206. var s = scene[this.index], a = 0;
  9207. if (partial(s)) switch (this.name()) {
  9208. case "center":
  9209. case "inner":
  9210. case "outer": a = midAngle(s); break;
  9211. case "start": a = s.startAngle; break;
  9212. case "end": a = s.endAngle; break;
  9213. }
  9214. return pv.Wedge.upright(a) ? a : (a + Math.PI);
  9215. });
  9216. };
  9217. /**
  9218. * Returns true if the specified angle is considered "upright", as in, text
  9219. * rendered at that angle would appear upright. If the angle is not upright,
  9220. * text is rotated 180 degrees to be upright, and the text alignment properties
  9221. * are correspondingly changed.
  9222. *
  9223. * @param {number} angle an angle, in radius.
  9224. * @returns {boolean} true if the specified angle is upright.
  9225. */
  9226. pv.Wedge.upright = function(angle) {
  9227. angle = angle % (2 * Math.PI);
  9228. angle = (angle < 0) ? (2 * Math.PI + angle) : angle;
  9229. return (angle < Math.PI / 2) || (angle >= 3 * Math.PI / 2);
  9230. };
  9231. /** @private Sets angle based on endAngle or vice versa. */
  9232. pv.Wedge.prototype.buildImplied = function(s) {
  9233. if (s.angle == null) s.angle = s.endAngle - s.startAngle;
  9234. else if (s.endAngle == null) s.endAngle = s.startAngle + s.angle;
  9235. pv.Mark.prototype.buildImplied.call(this, s);
  9236. };
  9237. /**
  9238. * Abstract; not implemented. There is no explicit constructor; this class
  9239. * merely serves to document the attributes that are used on particles in
  9240. * physics simulations.
  9241. *
  9242. * @class A weighted particle that can participate in a force simulation.
  9243. *
  9244. * @name pv.Particle
  9245. */
  9246. /**
  9247. * The next particle in the simulation. Particles form a singly-linked list.
  9248. *
  9249. * @field
  9250. * @type pv.Particle
  9251. * @name pv.Particle.prototype.next
  9252. */
  9253. /**
  9254. * The <i>x</i>-position of the particle.
  9255. *
  9256. * @field
  9257. * @type number
  9258. * @name pv.Particle.prototype.x
  9259. */
  9260. /**
  9261. * The <i>y</i>-position of the particle.
  9262. *
  9263. * @field
  9264. * @type number
  9265. * @name pv.Particle.prototype.y
  9266. */
  9267. /**
  9268. * The <i>x</i>-velocity of the particle.
  9269. *
  9270. * @field
  9271. * @type number
  9272. * @name pv.Particle.prototype.vx
  9273. */
  9274. /**
  9275. * The <i>y</i>-velocity of the particle.
  9276. *
  9277. * @field
  9278. * @type number
  9279. * @name pv.Particle.prototype.vy
  9280. */
  9281. /**
  9282. * The <i>x</i>-position of the particle at -dt.
  9283. *
  9284. * @field
  9285. * @type number
  9286. * @name pv.Particle.prototype.px
  9287. */
  9288. /**
  9289. * The <i>y</i>-position of the particle at -dt.
  9290. *
  9291. * @field
  9292. * @type number
  9293. * @name pv.Particle.prototype.py
  9294. */
  9295. /**
  9296. * The <i>x</i>-force on the particle.
  9297. *
  9298. * @field
  9299. * @type number
  9300. * @name pv.Particle.prototype.fx
  9301. */
  9302. /**
  9303. * The <i>y</i>-force on the particle.
  9304. *
  9305. * @field
  9306. * @type number
  9307. * @name pv.Particle.prototype.fy
  9308. */
  9309. /**
  9310. * Constructs a new empty simulation.
  9311. *
  9312. * @param {array} particles
  9313. * @returns {pv.Simulation} a new simulation for the specified particles.
  9314. * @see pv.Simulation
  9315. */
  9316. pv.simulation = function(particles) {
  9317. return new pv.Simulation(particles);
  9318. };
  9319. /**
  9320. * Constructs a new simulation for the specified particles.
  9321. *
  9322. * @class Represents a particle simulation. Particles are massive points in
  9323. * two-dimensional space. Forces can be applied to these particles, causing them
  9324. * to move. Constraints can also be applied to restrict particle movement, for
  9325. * example, constraining particles to a fixed position, or simulating collision
  9326. * between circular particles with area.
  9327. *
  9328. * <p>The simulation uses <a
  9329. * href="http://en.wikipedia.org/wiki/Verlet_integration">Position Verlet</a>
  9330. * integration, due to the ease with which <a
  9331. * href="http://www.teknikus.dk/tj/gdc2001.htm">geometric constraints</a> can be
  9332. * implemented. For each time step, Verlet integration is performed, new forces
  9333. * are accumulated, and then constraints are applied.
  9334. *
  9335. * <p>The simulation makes two simplifying assumptions: all particles are
  9336. * equal-mass, and the time step of the simulation is fixed. It would be easy to
  9337. * incorporate variable-mass particles as a future enhancement. Variable time
  9338. * steps are also possible, but are likely to introduce instability in the
  9339. * simulation.
  9340. *
  9341. * <p>This class can be used directly to simulate particle interaction.
  9342. * Alternatively, for network diagrams, see {@link pv.Layout.Force}.
  9343. *
  9344. * @param {array} particles an array of {@link pv.Particle}s to simulate.
  9345. * @see pv.Layout.Force
  9346. * @see pv.Force
  9347. * @see pv.Constraint
  9348. */
  9349. pv.Simulation = function(particles) {
  9350. for (var i = 0; i < particles.length; i++) this.particle(particles[i]);
  9351. };
  9352. /**
  9353. * The particles in the simulation. Particles are stored as a linked list; this
  9354. * field represents the first particle in the simulation.
  9355. *
  9356. * @field
  9357. * @type pv.Particle
  9358. * @name pv.Simulation.prototype.particles
  9359. */
  9360. /**
  9361. * The forces in the simulation. Forces are stored as a linked list; this field
  9362. * represents the first force in the simulation.
  9363. *
  9364. * @field
  9365. * @type pv.Force
  9366. * @name pv.Simulation.prototype.forces
  9367. */
  9368. /**
  9369. * The constraints in the simulation. Constraints are stored as a linked list;
  9370. * this field represents the first constraint in the simulation.
  9371. *
  9372. * @field
  9373. * @type pv.Constraint
  9374. * @name pv.Simulation.prototype.constraints
  9375. */
  9376. /**
  9377. * Adds the specified particle to the simulation.
  9378. *
  9379. * @param {pv.Particle} p the new particle.
  9380. * @returns {pv.Simulation} this.
  9381. */
  9382. pv.Simulation.prototype.particle = function(p) {
  9383. p.next = this.particles;
  9384. /* Default velocities and forces to zero if unset. */
  9385. if (isNaN(p.px)) p.px = p.x;
  9386. if (isNaN(p.py)) p.py = p.y;
  9387. if (isNaN(p.fx)) p.fx = 0;
  9388. if (isNaN(p.fy)) p.fy = 0;
  9389. this.particles = p;
  9390. return this;
  9391. };
  9392. /**
  9393. * Adds the specified force to the simulation.
  9394. *
  9395. * @param {pv.Force} f the new force.
  9396. * @returns {pv.Simulation} this.
  9397. */
  9398. pv.Simulation.prototype.force = function(f) {
  9399. f.next = this.forces;
  9400. this.forces = f;
  9401. return this;
  9402. };
  9403. /**
  9404. * Adds the specified constraint to the simulation.
  9405. *
  9406. * @param {pv.Constraint} c the new constraint.
  9407. * @returns {pv.Simulation} this.
  9408. */
  9409. pv.Simulation.prototype.constraint = function(c) {
  9410. c.next = this.constraints;
  9411. this.constraints = c;
  9412. return this;
  9413. };
  9414. /**
  9415. * Apply constraints, and then set the velocities to zero.
  9416. *
  9417. * @returns {pv.Simulation} this.
  9418. */
  9419. pv.Simulation.prototype.stabilize = function(n) {
  9420. var c;
  9421. if (!arguments.length) n = 3; // TODO use cooling schedule
  9422. for (var i = 0; i < n; i++) {
  9423. var q = new pv.Quadtree(this.particles);
  9424. for (c = this.constraints; c; c = c.next) c.apply(this.particles, q);
  9425. }
  9426. for (var p = this.particles; p; p = p.next) {
  9427. p.px = p.x;
  9428. p.py = p.y;
  9429. }
  9430. return this;
  9431. };
  9432. /**
  9433. * Advances the simulation one time-step.
  9434. */
  9435. pv.Simulation.prototype.step = function() {
  9436. var p, f, c;
  9437. /*
  9438. * Assumptions:
  9439. * - The mass (m) of every particles is 1.
  9440. * - The time step (dt) is 1.
  9441. */
  9442. /* Position Verlet integration. */
  9443. for (p = this.particles; p; p = p.next) {
  9444. var px = p.px, py = p.py;
  9445. p.px = p.x;
  9446. p.py = p.y;
  9447. p.x += p.vx = ((p.x - px) + p.fx);
  9448. p.y += p.vy = ((p.y - py) + p.fy);
  9449. }
  9450. /* Apply constraints, then accumulate new forces. */
  9451. var q = new pv.Quadtree(this.particles);
  9452. for (c = this.constraints; c; c = c.next) c.apply(this.particles, q);
  9453. for (p = this.particles; p; p = p.next) p.fx = p.fy = 0;
  9454. for (f = this.forces; f; f = f.next) f.apply(this.particles, q);
  9455. };
  9456. /**
  9457. * Constructs a new quadtree for the specified array of particles.
  9458. *
  9459. * @class Represents a quadtree: a two-dimensional recursive spatial
  9460. * subdivision. This particular implementation uses square partitions, dividing
  9461. * each square into four equally-sized squares. Each particle exists in a unique
  9462. * node; if multiple particles are in the same position, some particles may be
  9463. * stored on internal nodes rather than leaf nodes.
  9464. *
  9465. * <p>This quadtree can be used to accelerate various spatial operations, such
  9466. * as the Barnes-Hut approximation for computing n-body forces, or collision
  9467. * detection.
  9468. *
  9469. * @see pv.Force.charge
  9470. * @see pv.Constraint.collision
  9471. * @param {pv.Particle} particles the linked list of particles.
  9472. */
  9473. pv.Quadtree = function(particles) {
  9474. var p;
  9475. /* Compute bounds. */
  9476. var x1 = Number.POSITIVE_INFINITY, y1 = x1,
  9477. x2 = Number.NEGATIVE_INFINITY, y2 = x2;
  9478. for (p = particles; p; p = p.next) {
  9479. if (p.x < x1) x1 = p.x;
  9480. if (p.y < y1) y1 = p.y;
  9481. if (p.x > x2) x2 = p.x;
  9482. if (p.y > y2) y2 = p.y;
  9483. }
  9484. /* Squarify the bounds. */
  9485. var dx = x2 - x1, dy = y2 - y1;
  9486. if (dx > dy) y2 = y1 + dx;
  9487. else x2 = x1 + dy;
  9488. this.xMin = x1;
  9489. this.yMin = y1;
  9490. this.xMax = x2;
  9491. this.yMax = y2;
  9492. /**
  9493. * @ignore Recursively inserts the specified particle <i>p</i> at the node
  9494. * <i>n</i> or one of its descendants. The bounds are defined by [<i>x1</i>,
  9495. * <i>x2</i>] and [<i>y1</i>, <i>y2</i>].
  9496. */
  9497. function insert(n, p, x1, y1, x2, y2) {
  9498. if (isNaN(p.x) || isNaN(p.y)) return; // ignore invalid particles
  9499. if (n.leaf) {
  9500. if (n.p) {
  9501. /*
  9502. * If the particle at this leaf node is at the same position as the new
  9503. * particle we are adding, we leave the particle associated with the
  9504. * internal node while adding the new particle to a child node. This
  9505. * avoids infinite recursion.
  9506. */
  9507. if ((Math.abs(n.p.x - p.x) + Math.abs(n.p.y - p.y)) < .01) {
  9508. insertChild(n, p, x1, y1, x2, y2);
  9509. } else {
  9510. var v = n.p;
  9511. n.p = null;
  9512. insertChild(n, v, x1, y1, x2, y2);
  9513. insertChild(n, p, x1, y1, x2, y2);
  9514. }
  9515. } else {
  9516. n.p = p;
  9517. }
  9518. } else {
  9519. insertChild(n, p, x1, y1, x2, y2);
  9520. }
  9521. }
  9522. /**
  9523. * @ignore Recursively inserts the specified particle <i>p</i> into a
  9524. * descendant of node <i>n</i>. The bounds are defined by [<i>x1</i>,
  9525. * <i>x2</i>] and [<i>y1</i>, <i>y2</i>].
  9526. */
  9527. function insertChild(n, p, x1, y1, x2, y2) {
  9528. /* Compute the split point, and the quadrant in which to insert p. */
  9529. var sx = (x1 + x2) * .5,
  9530. sy = (y1 + y2) * .5,
  9531. right = p.x >= sx,
  9532. bottom = p.y >= sy;
  9533. /* Recursively insert into the child node. */
  9534. n.leaf = false;
  9535. switch ((bottom << 1) + right) {
  9536. case 0: n = n.c1 || (n.c1 = new pv.Quadtree.Node()); break;
  9537. case 1: n = n.c2 || (n.c2 = new pv.Quadtree.Node()); break;
  9538. case 2: n = n.c3 || (n.c3 = new pv.Quadtree.Node()); break;
  9539. case 3: n = n.c4 || (n.c4 = new pv.Quadtree.Node()); break;
  9540. }
  9541. /* Update the bounds as we recurse. */
  9542. if (right) x1 = sx; else x2 = sx;
  9543. if (bottom) y1 = sy; else y2 = sy;
  9544. insert(n, p, x1, y1, x2, y2);
  9545. }
  9546. /* Insert all particles. */
  9547. this.root = new pv.Quadtree.Node();
  9548. for (p = particles; p; p = p.next) insert(this.root, p, x1, y1, x2, y2);
  9549. };
  9550. /**
  9551. * The root node of the quadtree.
  9552. *
  9553. * @type pv.Quadtree.Node
  9554. * @name pv.Quadtree.prototype.root
  9555. */
  9556. /**
  9557. * The minimum x-coordinate value of all contained particles.
  9558. *
  9559. * @type number
  9560. * @name pv.Quadtree.prototype.xMin
  9561. */
  9562. /**
  9563. * The maximum x-coordinate value of all contained particles.
  9564. *
  9565. * @type number
  9566. * @name pv.Quadtree.prototype.xMax
  9567. */
  9568. /**
  9569. * The minimum y-coordinate value of all contained particles.
  9570. *
  9571. * @type number
  9572. * @name pv.Quadtree.prototype.yMin
  9573. */
  9574. /**
  9575. * The maximum y-coordinate value of all contained particles.
  9576. *
  9577. * @type number
  9578. * @name pv.Quadtree.prototype.yMax
  9579. */
  9580. /**
  9581. * Constructs a new node.
  9582. *
  9583. * @class A node in a quadtree.
  9584. *
  9585. * @see pv.Quadtree
  9586. */
  9587. pv.Quadtree.Node = function() {
  9588. /*
  9589. * Prepopulating all attributes significantly increases performance! Also,
  9590. * letting the language interpreter manage garbage collection was moderately
  9591. * faster than creating a cache pool.
  9592. */
  9593. this.leaf = true;
  9594. this.c1 = null;
  9595. this.c2 = null;
  9596. this.c3 = null;
  9597. this.c4 = null;
  9598. this.p = null;
  9599. };
  9600. /**
  9601. * True if this node is a leaf node; i.e., it has no children. Note that both
  9602. * leaf nodes and non-leaf (internal) nodes may have associated particles. If
  9603. * this is a non-leaf node, then at least one of {@link #c1}, {@link #c2},
  9604. * {@link #c3} or {@link #c4} is guaranteed to be non-null.
  9605. *
  9606. * @type boolean
  9607. * @name pv.Quadtree.Node.prototype.leaf
  9608. */
  9609. /**
  9610. * The particle associated with this node, if any.
  9611. *
  9612. * @type pv.Particle
  9613. * @name pv.Quadtree.Node.prototype.p
  9614. */
  9615. /**
  9616. * The child node for the second quadrant, if any.
  9617. *
  9618. * @type pv.Quadtree.Node
  9619. * @name pv.Quadtree.Node.prototype.c2
  9620. */
  9621. /**
  9622. * The child node for the third quadrant, if any.
  9623. *
  9624. * @type pv.Quadtree.Node
  9625. * @name pv.Quadtree.Node.prototype.c3
  9626. */
  9627. /**
  9628. * The child node for the fourth quadrant, if any.
  9629. *
  9630. * @type pv.Quadtree.Node
  9631. * @name pv.Quadtree.Node.prototype.c4
  9632. */
  9633. /**
  9634. * Abstract; see an implementing class.
  9635. *
  9636. * @class Represents a force that acts on particles. Note that this interface
  9637. * does not specify how to bind a force to specific particles; in general,
  9638. * forces are applied globally to all particles. However, some forces may be
  9639. * applied to specific particles or between particles, such as spring forces,
  9640. * through additional specialization.
  9641. *
  9642. * @see pv.Simulation
  9643. * @see pv.Particle
  9644. * @see pv.Force.charge
  9645. * @see pv.Force.drag
  9646. * @see pv.Force.spring
  9647. */
  9648. pv.Force = {};
  9649. /**
  9650. * Applies this force to the specified particles.
  9651. *
  9652. * @function
  9653. * @name pv.Force.prototype.apply
  9654. * @param {pv.Particle} particles particles to which to apply this force.
  9655. * @param {pv.Quadtree} q a quadtree for spatial acceleration.
  9656. */
  9657. /**
  9658. * Constructs a new charge force, with an optional charge constant. The charge
  9659. * constant can be negative for repulsion (e.g., particles with electrical
  9660. * charge of equal sign), or positive for attraction (e.g., massive particles
  9661. * with mutual gravity). The default charge constant is -40.
  9662. *
  9663. * @class An n-body force, as defined by Coulomb's law or Newton's law of
  9664. * gravitation, inversely proportional to the square of the distance between
  9665. * particles. Note that the force is independent of the <i>mass</i> of the
  9666. * associated particles, and that the particles do not have charges of varying
  9667. * magnitude; instead, the attraction or repulsion of all particles is globally
  9668. * specified as the charge {@link #constant}.
  9669. *
  9670. * <p>This particular implementation uses the Barnes-Hut algorithm. For details,
  9671. * see <a
  9672. * href="http://www.nature.com/nature/journal/v324/n6096/abs/324446a0.html">"A
  9673. * hierarchical O(N log N) force-calculation algorithm"</a>, J. Barnes &amp;
  9674. * P. Hut, <i>Nature</i> 1986.
  9675. *
  9676. * @name pv.Force.charge
  9677. * @param {number} [k] the charge constant.
  9678. */
  9679. pv.Force.charge = function(k) {
  9680. var min = 2, // minimum distance at which to observe forces
  9681. min1 = 1 / min,
  9682. max = 500, // maximum distance at which to observe forces
  9683. max1 = 1 / max,
  9684. theta = .9, // Barnes-Hut theta approximation constant
  9685. force = {};
  9686. if (!arguments.length) k = -40; // default charge constant (repulsion)
  9687. /**
  9688. * Sets or gets the charge constant. If an argument is specified, it is the
  9689. * new charge constant. The charge constant can be negative for repulsion
  9690. * (e.g., particles with electrical charge of equal sign), or positive for
  9691. * attraction (e.g., massive particles with mutual gravity). The default
  9692. * charge constant is -40.
  9693. *
  9694. * @function
  9695. * @name pv.Force.charge.prototype.constant
  9696. * @param {number} x the charge constant.
  9697. * @returns {pv.Force.charge} this.
  9698. */
  9699. force.constant = function(x) {
  9700. if (arguments.length) {
  9701. k = Number(x);
  9702. return force;
  9703. }
  9704. return k;
  9705. };
  9706. /**
  9707. * Sets or gets the domain; specifies the minimum and maximum domain within
  9708. * which charge forces are applied. A minimum distance threshold avoids
  9709. * applying forces that are two strong (due to granularity of the simulation's
  9710. * numeric integration). A maximum distance threshold improves performance by
  9711. * skipping force calculations for particles that are far apart.
  9712. *
  9713. * <p>The default domain is [2, 500].
  9714. *
  9715. * @function
  9716. * @name pv.Force.charge.prototype.domain
  9717. * @param {number} a
  9718. * @param {number} b
  9719. * @returns {pv.Force.charge} this.
  9720. */
  9721. force.domain = function(a, b) {
  9722. if (arguments.length) {
  9723. min = Number(a);
  9724. min1 = 1 / min;
  9725. max = Number(b);
  9726. max1 = 1 / max;
  9727. return force;
  9728. }
  9729. return [min, max];
  9730. };
  9731. /**
  9732. * Sets or gets the Barnes-Hut approximation factor. The Barnes-Hut
  9733. * approximation criterion is the ratio of the size of the quadtree node to
  9734. * the distance from the point to the node's center of mass is beneath some
  9735. * threshold.
  9736. *
  9737. * @function
  9738. * @name pv.Force.charge.prototype.theta
  9739. * @param {number} x the new Barnes-Hut approximation factor.
  9740. * @returns {pv.Force.charge} this.
  9741. */
  9742. force.theta = function(x) {
  9743. if (arguments.length) {
  9744. theta = Number(x);
  9745. return force;
  9746. }
  9747. return theta;
  9748. };
  9749. /**
  9750. * @ignore Recursively computes the center of charge for each node in the
  9751. * quadtree. This is equivalent to the center of mass, assuming that all
  9752. * particles have unit weight.
  9753. */
  9754. function accumulate(n) {
  9755. var cx = 0, cy = 0;
  9756. n.cn = 0;
  9757. function accumulateChild(c) {
  9758. accumulate(c);
  9759. n.cn += c.cn;
  9760. cx += c.cn * c.cx;
  9761. cy += c.cn * c.cy;
  9762. }
  9763. if (!n.leaf) {
  9764. if (n.c1) accumulateChild(n.c1);
  9765. if (n.c2) accumulateChild(n.c2);
  9766. if (n.c3) accumulateChild(n.c3);
  9767. if (n.c4) accumulateChild(n.c4);
  9768. }
  9769. if (n.p) {
  9770. n.cn += k;
  9771. cx += k * n.p.x;
  9772. cy += k * n.p.y;
  9773. }
  9774. n.cx = cx / n.cn;
  9775. n.cy = cy / n.cn;
  9776. }
  9777. /**
  9778. * @ignore Recursively computes forces on the given particle using the given
  9779. * quadtree node. The Barnes-Hut approximation criterion is the ratio of the
  9780. * size of the quadtree node to the distance from the point to the node's
  9781. * center of mass is beneath some threshold.
  9782. */
  9783. function forces(n, p, x1, y1, x2, y2) {
  9784. var dx = n.cx - p.x,
  9785. dy = n.cy - p.y,
  9786. dn = 1 / Math.sqrt(dx * dx + dy * dy);
  9787. /* Barnes-Hut criterion. */
  9788. if ((n.leaf && (n.p != p)) || ((x2 - x1) * dn < theta)) {
  9789. if (dn < max1) return;
  9790. if (dn > min1) dn = min1;
  9791. var kc = n.cn * dn * dn * dn,
  9792. fx = dx * kc,
  9793. fy = dy * kc;
  9794. p.fx += fx;
  9795. p.fy += fy;
  9796. } else if (!n.leaf) {
  9797. var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5;
  9798. if (n.c1) forces(n.c1, p, x1, y1, sx, sy);
  9799. if (n.c2) forces(n.c2, p, sx, y1, x2, sy);
  9800. if (n.c3) forces(n.c3, p, x1, sy, sx, y2);
  9801. if (n.c4) forces(n.c4, p, sx, sy, x2, y2);
  9802. if (dn < max1) return;
  9803. if (dn > min1) dn = min1;
  9804. if (n.p && (n.p != p)) {
  9805. var kc = k * dn * dn * dn,
  9806. fx = dx * kc,
  9807. fy = dy * kc;
  9808. p.fx += fx;
  9809. p.fy += fy;
  9810. }
  9811. }
  9812. }
  9813. /**
  9814. * Applies this force to the specified particles. The force is applied between
  9815. * all pairs of particles within the domain, using the specified quadtree to
  9816. * accelerate n-body force calculation using the Barnes-Hut approximation
  9817. * criterion.
  9818. *
  9819. * @function
  9820. * @name pv.Force.charge.prototype.apply
  9821. * @param {pv.Particle} particles particles to which to apply this force.
  9822. * @param {pv.Quadtree} q a quadtree for spatial acceleration.
  9823. */
  9824. force.apply = function(particles, q) {
  9825. accumulate(q.root);
  9826. for (var p = particles; p; p = p.next) {
  9827. forces(q.root, p, q.xMin, q.yMin, q.xMax, q.yMax);
  9828. }
  9829. };
  9830. return force;
  9831. };
  9832. /**
  9833. * Constructs a new drag force with the specified constant.
  9834. *
  9835. * @class Implements a drag force, simulating friction. The drag force is
  9836. * applied in the opposite direction of the particle's velocity. Since Position
  9837. * Verlet integration does not track velocities explicitly, the error term with
  9838. * this estimate of velocity is fairly high, so the drag force may be
  9839. * inaccurate.
  9840. *
  9841. * @extends pv.Force
  9842. * @param {number} k the drag constant.
  9843. * @see #constant
  9844. */
  9845. pv.Force.drag = function(k) {
  9846. var force = {};
  9847. if (!arguments.length) k = .1; // default drag constant
  9848. /**
  9849. * Sets or gets the drag constant, in the range [0,1]. The default drag
  9850. * constant is 0.1. The drag forces scales linearly with the particle's
  9851. * velocity based on the given drag constant.
  9852. *
  9853. * @function
  9854. * @name pv.Force.drag.prototype.constant
  9855. * @param {number} x the new drag constant.
  9856. * @returns {pv.Force.drag} this, or the current drag constant.
  9857. */
  9858. force.constant = function(x) {
  9859. if (arguments.length) { k = x; return force; }
  9860. return k;
  9861. };
  9862. /**
  9863. * Applies this force to the specified particles.
  9864. *
  9865. * @function
  9866. * @name pv.Force.drag.prototype.apply
  9867. * @param {pv.Particle} particles particles to which to apply this force.
  9868. */
  9869. force.apply = function(particles) {
  9870. if (k) for (var p = particles; p; p = p.next) {
  9871. p.fx -= k * p.vx;
  9872. p.fy -= k * p.vy;
  9873. }
  9874. };
  9875. return force;
  9876. };
  9877. /**
  9878. * Constructs a new spring force with the specified constant. The links
  9879. * associated with this spring force must be specified before the spring force
  9880. * can be applied.
  9881. *
  9882. * @class Implements a spring force, per Hooke's law. The spring force can be
  9883. * configured with a tension constant, rest length, and damping factor. The
  9884. * tension and damping will automatically be normalized using the inverse square
  9885. * root of the maximum link degree of attached nodes; this makes springs weaker
  9886. * between nodes of high link degree.
  9887. *
  9888. * <p>Unlike other forces (such as charge and drag forces) which may be applied
  9889. * globally, spring forces are only applied between linked particles. Therefore,
  9890. * an array of links must be specified before this force can be applied; the
  9891. * links should be an array of {@link pv.Layout.Network.Link}s. See also
  9892. * {@link pv.Layout.Force} for an example of using spring and charge forces for
  9893. * network layout.
  9894. *
  9895. * @extends pv.Force
  9896. * @param {number} k the spring constant.
  9897. * @see #constant
  9898. * @see #links
  9899. */
  9900. pv.Force.spring = function(k) {
  9901. var d = .1, // default damping factor
  9902. l = 20, // default rest length
  9903. links, // links on which to apply spring forces
  9904. kl, // per-spring normalization
  9905. force = {};
  9906. if (!arguments.length) k = .1; // default spring constant (tension)
  9907. /**
  9908. * Sets or gets the links associated with this spring force. Unlike other
  9909. * forces (such as charge and drag forces) which may be applied globally,
  9910. * spring forces are only applied between linked particles. Therefore, an
  9911. * array of links must be specified before this force can be applied; the
  9912. * links should be an array of {@link pv.Layout.Network.Link}s.
  9913. *
  9914. * @function
  9915. * @name pv.Force.spring.prototype.links
  9916. * @param {array} x the new array of links.
  9917. * @returns {pv.Force.spring} this, or the current array of links.
  9918. */
  9919. force.links = function(x) {
  9920. if (arguments.length) {
  9921. links = x;
  9922. kl = x.map(function(l) {
  9923. return 1 / Math.sqrt(Math.max(
  9924. l.sourceNode.linkDegree,
  9925. l.targetNode.linkDegree));
  9926. });
  9927. return force;
  9928. }
  9929. return links;
  9930. };
  9931. /**
  9932. * Sets or gets the spring constant. The default value is 0.1; greater values
  9933. * will result in stronger tension. The spring tension is automatically
  9934. * normalized using the inverse square root of the maximum link degree of
  9935. * attached nodes.
  9936. *
  9937. * @function
  9938. * @name pv.Force.spring.prototype.constant
  9939. * @param {number} x the new spring constant.
  9940. * @returns {pv.Force.spring} this, or the current spring constant.
  9941. */
  9942. force.constant = function(x) {
  9943. if (arguments.length) {
  9944. k = Number(x);
  9945. return force;
  9946. }
  9947. return k;
  9948. };
  9949. /**
  9950. * The spring damping factor, in the range [0,1]. Damping functions
  9951. * identically to drag forces, damping spring bounciness by applying a force
  9952. * in the opposite direction of attached nodes' velocities. The default value
  9953. * is 0.1. The spring damping is automatically normalized using the inverse
  9954. * square root of the maximum link degree of attached nodes.
  9955. *
  9956. * @function
  9957. * @name pv.Force.spring.prototype.damping
  9958. * @param {number} x the new spring damping factor.
  9959. * @returns {pv.Force.spring} this, or the current spring damping factor.
  9960. */
  9961. force.damping = function(x) {
  9962. if (arguments.length) {
  9963. d = Number(x);
  9964. return force;
  9965. }
  9966. return d;
  9967. };
  9968. /**
  9969. * The spring rest length. The default value is 20 pixels.
  9970. *
  9971. * @function
  9972. * @name pv.Force.spring.prototype.length
  9973. * @param {number} x the new spring rest length.
  9974. * @returns {pv.Force.spring} this, or the current spring rest length.
  9975. */
  9976. force.length = function(x) {
  9977. if (arguments.length) {
  9978. l = Number(x);
  9979. return force;
  9980. }
  9981. return l;
  9982. };
  9983. /**
  9984. * Applies this force to the specified particles.
  9985. *
  9986. * @function
  9987. * @name pv.Force.spring.prototype.apply
  9988. * @param {pv.Particle} particles particles to which to apply this force.
  9989. */
  9990. force.apply = function(particles) {
  9991. for (var i = 0; i < links.length; i++) {
  9992. var a = links[i].sourceNode,
  9993. b = links[i].targetNode,
  9994. dx = a.x - b.x,
  9995. dy = a.y - b.y,
  9996. dn = Math.sqrt(dx * dx + dy * dy),
  9997. dd = dn ? (1 / dn) : 1,
  9998. ks = k * kl[i], // normalized tension
  9999. kd = d * kl[i], // normalized damping
  10000. kk = (ks * (dn - l) + kd * (dx * (a.vx - b.vx) + dy * (a.vy - b.vy)) * dd) * dd,
  10001. fx = -kk * (dn ? dx : (.01 * (.5 - Math.random()))),
  10002. fy = -kk * (dn ? dy : (.01 * (.5 - Math.random())));
  10003. a.fx += fx;
  10004. a.fy += fy;
  10005. b.fx -= fx;
  10006. b.fy -= fy;
  10007. }
  10008. };
  10009. return force;
  10010. };
  10011. /**
  10012. * Abstract; see an implementing class.
  10013. *
  10014. * @class Represents a constraint that acts on particles. Note that this
  10015. * interface does not specify how to bind a constraint to specific particles; in
  10016. * general, constraints are applied globally to all particles. However, some
  10017. * constraints may be applied to specific particles or between particles, such
  10018. * as position constraints, through additional specialization.
  10019. *
  10020. * @see pv.Simulation
  10021. * @see pv.Particle
  10022. * @see pv.Constraint.bound
  10023. * @see pv.Constraint.collision
  10024. * @see pv.Constraint.position
  10025. */
  10026. pv.Constraint = {};
  10027. /**
  10028. * Applies this constraint to the specified particles.
  10029. *
  10030. * @function
  10031. * @name pv.Constraint.prototype.apply
  10032. * @param {pv.Particle} particles particles to which to apply this constraint.
  10033. * @param {pv.Quadtree} q a quadtree for spatial acceleration.
  10034. * @returns {pv.Constraint} this.
  10035. */
  10036. /**
  10037. * Constructs a new collision constraint. The default search radius is 10, and
  10038. * the default repeat count is 1. A radius function must be specified to compute
  10039. * the radius of particles.
  10040. *
  10041. * @class Constraints circles to avoid overlap. Each particle is treated as a
  10042. * circle, with the radius of the particle computed using a specified function.
  10043. * For example, if the particle has an <tt>r</tt> attribute storing the radius,
  10044. * the radius <tt>function(d) d.r</tt> specifies a collision constraint using
  10045. * this radius. The radius function is passed each {@link pv.Particle} as the
  10046. * first argument.
  10047. *
  10048. * <p>To accelerate collision detection, this implementation uses a quadtree and
  10049. * a search radius. The search radius is computed as the maximum radius of all
  10050. * particles in the simulation.
  10051. *
  10052. * @see pv.Constraint
  10053. * @param {function} radius the radius function.
  10054. */
  10055. pv.Constraint.collision = function(radius) {
  10056. var n = 1, // number of times to repeat the constraint
  10057. r1,
  10058. px1,
  10059. py1,
  10060. px2,
  10061. py2,
  10062. constraint = {};
  10063. if (!arguments.length) r1 = 10; // default search radius
  10064. /**
  10065. * Sets or gets the repeat count. If the repeat count is greater than 1, the
  10066. * constraint will be applied repeatedly; this is a form of the Gauss-Seidel
  10067. * method for constraints relaxation. Repeating the collision constraint makes
  10068. * the constraint have more of an effect when there is a potential for many
  10069. * co-occurring collisions.
  10070. *
  10071. * @function
  10072. * @name pv.Constraint.collision.prototype.repeat
  10073. * @param {number} x the number of times to repeat this constraint.
  10074. * @returns {pv.Constraint.collision} this.
  10075. */
  10076. constraint.repeat = function(x) {
  10077. if (arguments.length) {
  10078. n = Number(x);
  10079. return constraint;
  10080. }
  10081. return n;
  10082. };
  10083. /** @private */
  10084. function constrain(n, p, x1, y1, x2, y2) {
  10085. if (!n.leaf) {
  10086. var sx = (x1 + x2) * .5,
  10087. sy = (y1 + y2) * .5,
  10088. top = sy > py1,
  10089. bottom = sy < py2,
  10090. left = sx > px1,
  10091. right = sx < px2;
  10092. if (top) {
  10093. if (n.c1 && left) constrain(n.c1, p, x1, y1, sx, sy);
  10094. if (n.c2 && right) constrain(n.c2, p, sx, y1, x2, sy);
  10095. }
  10096. if (bottom) {
  10097. if (n.c3 && left) constrain(n.c3, p, x1, sy, sx, y2);
  10098. if (n.c4 && right) constrain(n.c4, p, sx, sy, x2, y2);
  10099. }
  10100. }
  10101. if (n.p && (n.p != p)) {
  10102. var dx = p.x - n.p.x,
  10103. dy = p.y - n.p.y,
  10104. l = Math.sqrt(dx * dx + dy * dy),
  10105. d = r1 + radius(n.p);
  10106. if (l < d) {
  10107. var k = (l - d) / l * .5;
  10108. dx *= k;
  10109. dy *= k;
  10110. p.x -= dx;
  10111. p.y -= dy;
  10112. n.p.x += dx;
  10113. n.p.y += dy;
  10114. }
  10115. }
  10116. }
  10117. /**
  10118. * Applies this constraint to the specified particles.
  10119. *
  10120. * @function
  10121. * @name pv.Constraint.collision.prototype.apply
  10122. * @param {pv.Particle} particles particles to which to apply this constraint.
  10123. * @param {pv.Quadtree} q a quadtree for spatial acceleration.
  10124. */
  10125. constraint.apply = function(particles, q) {
  10126. var p, r, max = -Infinity;
  10127. for (p = particles; p; p = p.next) {
  10128. r = radius(p);
  10129. if (r > max) max = r;
  10130. }
  10131. for (var i = 0; i < n; i++) {
  10132. for (p = particles; p; p = p.next) {
  10133. r = (r1 = radius(p)) + max;
  10134. px1 = p.x - r;
  10135. px2 = p.x + r;
  10136. py1 = p.y - r;
  10137. py2 = p.y + r;
  10138. constrain(q.root, p, q.xMin, q.yMin, q.xMax, q.yMax);
  10139. }
  10140. }
  10141. };
  10142. return constraint;
  10143. };
  10144. /**
  10145. * Constructs a default position constraint using the <tt>fix</tt> attribute.
  10146. * An optional position function can be specified to determine how the fixed
  10147. * position per-particle is determined.
  10148. *
  10149. * @class Constraints particles to a fixed position. The fixed position per
  10150. * particle is determined using a given position function, which defaults to
  10151. * <tt>function(d) d.fix</tt>.
  10152. *
  10153. * <p>If the position function returns null, then no position constraint is
  10154. * applied to the given particle. Otherwise, the particle's position is set to
  10155. * the returned position, as expressed by a {@link pv.Vector}. (Note: the
  10156. * position does not need to be an instance of <tt>pv.Vector</tt>, but simply an
  10157. * object with <tt>x</tt> and <tt>y</tt> attributes.)
  10158. *
  10159. * <p>This constraint also supports a configurable alpha parameter, which
  10160. * defaults to 1. If the alpha parameter is in the range [0,1], then rather than
  10161. * setting the particle's new position directly to the position returned by the
  10162. * supplied position function, the particle's position is interpolated towards
  10163. * the fixed position. This results is a smooth (exponential) drift towards the
  10164. * fixed position, which can increase the stability of the physics simulation.
  10165. * In addition, the alpha parameter can be decayed over time, relaxing the
  10166. * position constraint, which helps to stabilize on an optimal solution.
  10167. *
  10168. * @param {function} [f] the position function.
  10169. */
  10170. pv.Constraint.position = function(f) {
  10171. var a = 1, // default alpha
  10172. constraint = {};
  10173. if (!arguments.length) /** @ignore */ f = function(p) { return p.fix; };
  10174. /**
  10175. * Sets or gets the alpha parameter for position interpolation. If the alpha
  10176. * parameter is in the range [0,1], then rather than setting the particle's
  10177. * new position directly to the position returned by the supplied position
  10178. * function, the particle's position is interpolated towards the fixed
  10179. * position.
  10180. *
  10181. * @function
  10182. * @name pv.Constraint.position.prototype.alpha
  10183. * @param {number} x the new alpha parameter, in the range [0,1].
  10184. * @returns {pv.Constraint.position} this.
  10185. */
  10186. constraint.alpha = function(x) {
  10187. if (arguments.length) {
  10188. a = Number(x);
  10189. return constraint;
  10190. }
  10191. return a;
  10192. };
  10193. /**
  10194. * Applies this constraint to the specified particles.
  10195. *
  10196. * @function
  10197. * @name pv.Constraint.position.prototype.apply
  10198. * @param {pv.Particle} particles particles to which to apply this constraint.
  10199. */
  10200. constraint.apply = function(particles) {
  10201. for (var p = particles; p; p = p.next) {
  10202. var v = f(p);
  10203. if (v) {
  10204. p.x += (v.x - p.x) * a;
  10205. p.y += (v.y - p.y) * a;
  10206. p.fx = p.fy = p.vx = p.vy = 0;
  10207. }
  10208. }
  10209. };
  10210. return constraint;
  10211. };
  10212. /**
  10213. * Constructs a new bound constraint. Before the constraint can be used, the
  10214. * {@link #x} and {@link #y} methods must be call to specify the bounds.
  10215. *
  10216. * @class Constrains particles to within fixed rectangular bounds. For example,
  10217. * this constraint can be used to constrain particles in a physics simulation
  10218. * within the bounds of an enclosing panel.
  10219. *
  10220. * <p>Note that the current implementation treats particles as points, with no
  10221. * area. If the particles are rendered as dots, be sure to include some
  10222. * additional padding to inset the bounds such that the edges of the dots do not
  10223. * get clipped by the panel bounds. If the particles have different radii, this
  10224. * constraint would need to be extended using a radius function, similar to
  10225. * {@link pv.Constraint.collision}.
  10226. *
  10227. * @see pv.Layout.Force
  10228. * @extends pv.Constraint
  10229. */
  10230. pv.Constraint.bound = function() {
  10231. var constraint = {},
  10232. x,
  10233. y;
  10234. /**
  10235. * Sets or gets the bounds on the x-coordinate.
  10236. *
  10237. * @function
  10238. * @name pv.Constraint.bound.prototype.x
  10239. * @param {number} min the minimum allowed x-coordinate.
  10240. * @param {number} max the maximum allowed x-coordinate.
  10241. * @returns {pv.Constraint.bound} this.
  10242. */
  10243. constraint.x = function(min, max) {
  10244. if (arguments.length) {
  10245. x = {min: Math.min(min, max), max: Math.max(min, max)};
  10246. return this;
  10247. }
  10248. return x;
  10249. };
  10250. /**
  10251. * Sets or gets the bounds on the y-coordinate.
  10252. *
  10253. * @function
  10254. * @name pv.Constraint.bound.prototype.y
  10255. * @param {number} min the minimum allowed y-coordinate.
  10256. * @param {number} max the maximum allowed y-coordinate.
  10257. * @returns {pv.Constraint.bound} this.
  10258. */
  10259. constraint.y = function(min, max) {
  10260. if (arguments.length) {
  10261. y = {min: Math.min(min, max), max: Math.max(min, max)};
  10262. return this;
  10263. }
  10264. return y;
  10265. };
  10266. /**
  10267. * Applies this constraint to the specified particles.
  10268. *
  10269. * @function
  10270. * @name pv.Constraint.bound.prototype.apply
  10271. * @param {pv.Particle} particles particles to which to apply this constraint.
  10272. */
  10273. constraint.apply = function(particles) {
  10274. if (x) for (var p = particles; p; p = p.next) {
  10275. p.x = p.x < x.min ? x.min : (p.x > x.max ? x.max : p.x);
  10276. }
  10277. if (y) for (var p = particles; p; p = p.next) {
  10278. p.y = p.y < y.min ? y.min : (p.y > y.max ? y.max : p.y);
  10279. }
  10280. };
  10281. return constraint;
  10282. };
  10283. /**
  10284. * Constructs a new, empty layout with default properties. Layouts are not
  10285. * typically constructed directly; instead, a concrete subclass is added to an
  10286. * existing panel via {@link pv.Mark#add}.
  10287. *
  10288. * @class Represents an abstract layout, encapsulating a visualization technique
  10289. * such as a streamgraph or treemap. Layouts are themselves containers,
  10290. * extending from {@link pv.Panel}, and defining a set of mark prototypes as
  10291. * children. These mark prototypes provide default properties that together
  10292. * implement the given visualization technique.
  10293. *
  10294. * <p>Layouts do not initially contain any marks; any exported marks (such as a
  10295. * network layout's <tt>link</tt> and <tt>node</tt>) are intended to be used as
  10296. * prototypes. By adding a concrete mark, such as a {@link pv.Bar}, to the
  10297. * appropriate mark prototype, the mark is added to the layout and inherits the
  10298. * given properties. This approach allows further customization of the layout,
  10299. * either by choosing a different mark type to add, or more simply by overriding
  10300. * some of the layout's defined properties.
  10301. *
  10302. * <p>Each concrete layout, such as treemap or circle-packing, has different
  10303. * behavior and may export different mark prototypes, depending on what marks
  10304. * are typically needed to render the desired visualization. Therefore it is
  10305. * important to understand how each layout is structured, such that the provided
  10306. * mark prototypes are used appropriately.
  10307. *
  10308. * <p>In addition to the mark prototypes, layouts may define custom properties
  10309. * that affect the overall behavior of the layout. For example, a treemap layout
  10310. * might use a property to specify which layout algorithm to use. These
  10311. * properties are just like other mark properties, and can be defined as
  10312. * constants or as functions. As with panels, the data property can be used to
  10313. * replicate layouts, and properties can be defined to in terms of layout data.
  10314. *
  10315. * @extends pv.Panel
  10316. */
  10317. pv.Layout = function() {
  10318. pv.Panel.call(this);
  10319. };
  10320. pv.Layout.prototype = pv.extend(pv.Panel);
  10321. /**
  10322. * @private Defines a local property with the specified name and cast. Note that
  10323. * although the property method is only defined locally, the cast function is
  10324. * global, which is necessary since properties are inherited!
  10325. *
  10326. * @param {string} name the property name.
  10327. * @param {function} [cast] the cast function for this property.
  10328. */
  10329. pv.Layout.prototype.property = function(name, cast) {
  10330. if (!this.hasOwnProperty("properties")) {
  10331. this.properties = pv.extend(this.properties);
  10332. }
  10333. this.properties[name] = true;
  10334. this.propertyMethod(name, false, pv.Mark.cast[name] = cast);
  10335. return this;
  10336. };
  10337. /**
  10338. * Constructs a new, empty network layout. Layouts are not typically constructed
  10339. * directly; instead, they are added to an existing panel via
  10340. * {@link pv.Mark#add}.
  10341. *
  10342. * @class Represents an abstract layout for network diagrams. This class
  10343. * provides the basic structure for both node-link diagrams (such as
  10344. * force-directed graph layout) and space-filling network diagrams (such as
  10345. * sunbursts and treemaps). Note that "network" here is a general term that
  10346. * includes hierarchical structures; a tree is represented using links from
  10347. * child to parent.
  10348. *
  10349. * <p>Network layouts require the graph data structure to be defined using two
  10350. * properties:<ul>
  10351. *
  10352. * <li><tt>nodes</tt> - an array of objects representing nodes. Objects in this
  10353. * array must conform to the {@link pv.Layout.Network.Node} interface; which is
  10354. * to say, be careful to avoid naming collisions with automatic attributes such
  10355. * as <tt>index</tt> and <tt>linkDegree</tt>. If the nodes property is defined
  10356. * as an array of primitives, such as numbers or strings, these primitives are
  10357. * automatically wrapped in an object; the resulting object's <tt>nodeValue</tt>
  10358. * attribute points to the original primitive value.
  10359. *
  10360. * <p><li><tt>links</tt> - an array of objects representing links. Objects in
  10361. * this array must conform to the {@link pv.Layout.Network.Link} interface; at a
  10362. * minimum, either <tt>source</tt> and <tt>target</tt> indexes or
  10363. * <tt>sourceNode</tt> and <tt>targetNode</tt> references must be set. Note that
  10364. * if the links property is defined after the nodes property, the links can be
  10365. * defined in terms of <tt>this.nodes()</tt>.
  10366. *
  10367. * </ul>
  10368. *
  10369. * <p>Three standard mark prototypes are provided:<ul>
  10370. *
  10371. * <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Dot}. The node
  10372. * mark is added directly to the layout, with the data property defined via the
  10373. * layout's <tt>nodes</tt> property. Properties such as <tt>strokeStyle</tt> and
  10374. * <tt>fillStyle</tt> can be overridden to compute properties from node data
  10375. * dynamically.
  10376. *
  10377. * <p><li><tt>link</tt> - for rendering links; typically a {@link pv.Line}. The
  10378. * link mark is added to a child panel, whose data property is defined as
  10379. * layout's <tt>links</tt> property. The link's data property is then a
  10380. * two-element array of the source node and target node. Thus, poperties such as
  10381. * <tt>strokeStyle</tt> and <tt>fillStyle</tt> can be overridden to compute
  10382. * properties from either the node data (the first argument) or the link data
  10383. * (the second argument; the parent panel data) dynamically.
  10384. *
  10385. * <p><li><tt>label</tt> - for rendering node labels; typically a
  10386. * {@link pv.Label}. The label mark is added directly to the layout, with the
  10387. * data property defined via the layout's <tt>nodes</tt> property. Properties
  10388. * such as <tt>strokeStyle</tt> and <tt>fillStyle</tt> can be overridden to
  10389. * compute properties from node data dynamically.
  10390. *
  10391. * </ul>Note that some network implementations may not support all three
  10392. * standard mark prototypes; for example, space-filling hierarchical layouts
  10393. * typically do not use a <tt>link</tt> prototype, as the parent-child links are
  10394. * implied by the structure of the space-filling <tt>node</tt> marks. Check the
  10395. * specific network layout for implementation details.
  10396. *
  10397. * <p>Network layout properties, including <tt>nodes</tt> and <tt>links</tt>,
  10398. * are typically cached rather than re-evaluated with every call to render. This
  10399. * is a performance optimization, as network layout algorithms can be
  10400. * expensive. If the network structure changes, call {@link #reset} to clear the
  10401. * cache before rendering. Note that although the network layout properties are
  10402. * cached, child mark properties, such as the marks used to render the nodes and
  10403. * links, <i>are not</i>. Therefore, non-structural changes to the network
  10404. * layout, such as changing the color of a mark on mouseover, do not need to
  10405. * reset the layout.
  10406. *
  10407. * @see pv.Layout.Hierarchy
  10408. * @see pv.Layout.Force
  10409. * @see pv.Layout.Matrix
  10410. * @see pv.Layout.Arc
  10411. * @see pv.Layout.Rollup
  10412. * @extends pv.Layout
  10413. */
  10414. pv.Layout.Network = function() {
  10415. pv.Layout.call(this);
  10416. var that = this;
  10417. /* @private Version tracking to cache layout state, improving performance. */
  10418. this.$id = pv.id();
  10419. /**
  10420. * The node prototype. This prototype is intended to be used with a Dot mark
  10421. * in conjunction with the link prototype.
  10422. *
  10423. * @type pv.Mark
  10424. * @name pv.Layout.Network.prototype.node
  10425. */
  10426. (this.node = new pv.Mark()
  10427. .data(function() { return that.nodes(); })
  10428. .strokeStyle("#1f77b4")
  10429. .fillStyle("#fff")
  10430. .left(function(n) { return n.x; })
  10431. .top(function(n) { return n.y; })).parent = this;
  10432. /**
  10433. * The link prototype, which renders edges between source nodes and target
  10434. * nodes. This prototype is intended to be used with a Line mark in
  10435. * conjunction with the node prototype.
  10436. *
  10437. * @type pv.Mark
  10438. * @name pv.Layout.Network.prototype.link
  10439. */
  10440. this.link = new pv.Mark()
  10441. .extend(this.node)
  10442. .data(function(p) { return [p.sourceNode, p.targetNode]; })
  10443. .fillStyle(null)
  10444. .lineWidth(function(d, p) { return p.linkValue * 1.5; })
  10445. .strokeStyle("rgba(0,0,0,.2)");
  10446. this.link.add = function(type) {
  10447. return that.add(pv.Panel)
  10448. .data(function() { return that.links(); })
  10449. .add(type)
  10450. .extend(this);
  10451. };
  10452. /**
  10453. * The node label prototype, which renders the node name adjacent to the node.
  10454. * This prototype is provided as an alternative to using the anchor on the
  10455. * node mark; it is primarily intended to be used with radial node-link
  10456. * layouts, since it provides a convenient mechanism to set the text angle.
  10457. *
  10458. * @type pv.Mark
  10459. * @name pv.Layout.Network.prototype.label
  10460. */
  10461. (this.label = new pv.Mark()
  10462. .extend(this.node)
  10463. .textMargin(7)
  10464. .textBaseline("middle")
  10465. .text(function(n) { return n.nodeName || n.nodeValue; })
  10466. .textAngle(function(n) {
  10467. var a = n.midAngle;
  10468. return pv.Wedge.upright(a) ? a : (a + Math.PI);
  10469. })
  10470. .textAlign(function(n) {
  10471. return pv.Wedge.upright(n.midAngle) ? "left" : "right";
  10472. })).parent = this;
  10473. };
  10474. /**
  10475. * @class Represents a node in a network layout. There is no explicit
  10476. * constructor; this class merely serves to document the attributes that are
  10477. * used on nodes in network layouts. (Note that hierarchical nodes place
  10478. * additional requirements on node representation, vis {@link pv.Dom.Node}.)
  10479. *
  10480. * @see pv.Layout.Network
  10481. * @name pv.Layout.Network.Node
  10482. */
  10483. /**
  10484. * The node index, zero-based. This attribute is populated automatically based
  10485. * on the index in the array returned by the <tt>nodes</tt> property.
  10486. *
  10487. * @type number
  10488. * @name pv.Layout.Network.Node.prototype.index
  10489. */
  10490. /**
  10491. * The link degree; the sum of link values for all incoming and outgoing links.
  10492. * This attribute is populated automatically.
  10493. *
  10494. * @type number
  10495. * @name pv.Layout.Network.Node.prototype.linkDegree
  10496. */
  10497. /**
  10498. * The node name; optional. If present, this attribute will be used to provide
  10499. * the text for node labels. If not present, the label text will fallback to the
  10500. * <tt>nodeValue</tt> attribute.
  10501. *
  10502. * @type string
  10503. * @name pv.Layout.Network.Node.prototype.nodeName
  10504. */
  10505. /**
  10506. * The node value; optional. If present, and no <tt>nodeName</tt> attribute is
  10507. * present, the node value will be used as the label text. This attribute is
  10508. * also automatically populated if the nodes are specified as an array of
  10509. * primitives, such as strings or numbers.
  10510. *
  10511. * @type object
  10512. * @name pv.Layout.Network.Node.prototype.nodeValue
  10513. */
  10514. /**
  10515. * @class Represents a link in a network layout. There is no explicit
  10516. * constructor; this class merely serves to document the attributes that are
  10517. * used on links in network layouts. For hierarchical layouts, this class is
  10518. * used to represent the parent-child links.
  10519. *
  10520. * @see pv.Layout.Network
  10521. * @name pv.Layout.Network.Link
  10522. */
  10523. /**
  10524. * The link value, or weight; optional. If not specified (or not a number), the
  10525. * default value of 1 is used.
  10526. *
  10527. * @type number
  10528. * @name pv.Layout.Network.Link.prototype.linkValue
  10529. */
  10530. /**
  10531. * The link's source node. If not set, this value will be derived from the
  10532. * <tt>source</tt> attribute index.
  10533. *
  10534. * @type pv.Layout.Network.Node
  10535. * @name pv.Layout.Network.Link.prototype.sourceNode
  10536. */
  10537. /**
  10538. * The link's target node. If not set, this value will be derived from the
  10539. * <tt>target</tt> attribute index.
  10540. *
  10541. * @type pv.Layout.Network.Node
  10542. * @name pv.Layout.Network.Link.prototype.targetNode
  10543. */
  10544. /**
  10545. * Alias for <tt>sourceNode</tt>, as expressed by the index of the source node.
  10546. * This attribute is not populated automatically, but may be used as a more
  10547. * convenient identification of the link's source, for example in a static JSON
  10548. * representation.
  10549. *
  10550. * @type number
  10551. * @name pv.Layout.Network.Link.prototype.source
  10552. */
  10553. /**
  10554. * Alias for <tt>targetNode</tt>, as expressed by the index of the target node.
  10555. * This attribute is not populated automatically, but may be used as a more
  10556. * convenient identification of the link's target, for example in a static JSON
  10557. * representation.
  10558. *
  10559. * @type number
  10560. * @name pv.Layout.Network.Link.prototype.target
  10561. */
  10562. /**
  10563. * Alias for <tt>linkValue</tt>. This attribute is not populated automatically,
  10564. * but may be used instead of the <tt>linkValue</tt> attribute when specifying
  10565. * links.
  10566. *
  10567. * @type number
  10568. * @name pv.Layout.Network.Link.prototype.value
  10569. */
  10570. /** @private Transform nodes and links on cast. */
  10571. pv.Layout.Network.prototype = pv.extend(pv.Layout)
  10572. .property("nodes", function(v) {
  10573. return v.map(function(d, i) {
  10574. if (typeof d != "object") d = {nodeValue: d};
  10575. d.index = i;
  10576. d.linkDegree = 0;
  10577. return d;
  10578. });
  10579. })
  10580. .property("links", function(v) {
  10581. return v.map(function(d) {
  10582. if (isNaN(d.linkValue)) d.linkValue = isNaN(d.value) ? 1 : d.value;
  10583. return d;
  10584. });
  10585. });
  10586. /**
  10587. * Resets the cache, such that changes to layout property definitions will be
  10588. * visible on subsequent render. Unlike normal marks (and normal layouts),
  10589. * properties associated with network layouts are not automatically re-evaluated
  10590. * on render; the properties are cached, and any expensive layout algorithms are
  10591. * only run after the layout is explicitly reset.
  10592. *
  10593. * @returns {pv.Layout.Network} this.
  10594. */
  10595. pv.Layout.Network.prototype.reset = function() {
  10596. this.$id = pv.id();
  10597. return this;
  10598. };
  10599. /** @private Skip evaluating properties if cached. */
  10600. pv.Layout.Network.prototype.buildProperties = function(s, properties) {
  10601. if ((s.$id || 0) < this.$id) {
  10602. pv.Layout.prototype.buildProperties.call(this, s, properties);
  10603. }
  10604. };
  10605. /** @private Compute link degrees; map source and target indexes to nodes. */
  10606. pv.Layout.Network.prototype.buildImplied = function(s) {
  10607. pv.Layout.prototype.buildImplied.call(this, s);
  10608. if (s.$id >= this.$id) return true;
  10609. s.$id = this.$id;
  10610. s.links.forEach(function(d) {
  10611. var v = d.linkValue;
  10612. (d.sourceNode || (d.sourceNode = s.nodes[d.source])).linkDegree += v;
  10613. (d.targetNode || (d.targetNode = s.nodes[d.target])).linkDegree += v;
  10614. });
  10615. };
  10616. /**
  10617. * Constructs a new, empty hierarchy layout. Layouts are not typically
  10618. * constructed directly; instead, they are added to an existing panel via
  10619. * {@link pv.Mark#add}.
  10620. *
  10621. * @class Represents an abstract layout for hierarchy diagrams. This class is a
  10622. * specialization of {@link pv.Layout.Network}, providing the basic structure
  10623. * for both hierarchical node-link diagrams (such as Reingold-Tilford trees) and
  10624. * space-filling hierarchy diagrams (such as sunbursts and treemaps).
  10625. *
  10626. * <p>Unlike general network layouts, the <tt>links</tt> property need not be
  10627. * defined explicitly. Instead, the links are computed implicitly from the
  10628. * <tt>parentNode</tt> attribute of the node objects, as defined by the
  10629. * <tt>nodes</tt> property. This implementation is also available as
  10630. * {@link #links}, for reuse with non-hierarchical layouts; for example, to
  10631. * render a tree using force-directed layout.
  10632. *
  10633. * <p>Correspondingly, the <tt>nodes</tt> property is represented as a union of
  10634. * {@link pv.Layout.Network.Node} and {@link pv.Dom.Node}. To construct a node
  10635. * hierarchy from a simple JSON map, use the {@link pv.Dom} operator; this
  10636. * operator also provides an easy way to sort nodes before passing them to the
  10637. * layout.
  10638. *
  10639. * <p>For more details on how to use this layout, see
  10640. * {@link pv.Layout.Network}.
  10641. *
  10642. * @see pv.Layout.Cluster
  10643. * @see pv.Layout.Partition
  10644. * @see pv.Layout.Tree
  10645. * @see pv.Layout.Treemap
  10646. * @see pv.Layout.Indent
  10647. * @see pv.Layout.Pack
  10648. * @extends pv.Layout.Network
  10649. */
  10650. pv.Layout.Hierarchy = function() {
  10651. pv.Layout.Network.call(this);
  10652. this.link.strokeStyle("#ccc");
  10653. };
  10654. pv.Layout.Hierarchy.prototype = pv.extend(pv.Layout.Network);
  10655. /** @private Compute the implied links. (Links are null by default.) */
  10656. pv.Layout.Hierarchy.prototype.buildImplied = function(s) {
  10657. if (!s.links) s.links = pv.Layout.Hierarchy.links.call(this);
  10658. pv.Layout.Network.prototype.buildImplied.call(this, s);
  10659. };
  10660. /** The implied links; computes links using the <tt>parentNode</tt> attribute. */
  10661. pv.Layout.Hierarchy.links = function() {
  10662. return this.nodes()
  10663. .filter(function(n) { return n.parentNode; })
  10664. .map(function(n) {
  10665. return {
  10666. sourceNode: n,
  10667. targetNode: n.parentNode,
  10668. linkValue: 1
  10669. };
  10670. });
  10671. };
  10672. /** @private Provides standard node-link layout based on breadth & depth. */
  10673. pv.Layout.Hierarchy.NodeLink = {
  10674. /** @private */
  10675. buildImplied: function(s) {
  10676. var nodes = s.nodes,
  10677. orient = s.orient,
  10678. horizontal = /^(top|bottom)$/.test(orient),
  10679. w = s.width,
  10680. h = s.height;
  10681. /* Compute default inner and outer radius. */
  10682. if (orient == "radial") {
  10683. var ir = s.innerRadius, or = s.outerRadius;
  10684. if (ir == null) ir = 0;
  10685. if (or == null) or = Math.min(w, h) / 2;
  10686. }
  10687. /** @private Returns the radius of the given node. */
  10688. function radius(n) {
  10689. return n.parentNode ? (n.depth * (or - ir) + ir) : 0;
  10690. }
  10691. /** @private Returns the angle of the given node. */
  10692. function midAngle(n) {
  10693. return (n.parentNode ? (n.breadth - .25) * 2 * Math.PI : 0);
  10694. }
  10695. /** @private */
  10696. function x(n) {
  10697. switch (orient) {
  10698. case "left": return n.depth * w;
  10699. case "right": return w - n.depth * w;
  10700. case "top": return n.breadth * w;
  10701. case "bottom": return w - n.breadth * w;
  10702. case "radial": return w / 2 + radius(n) * Math.cos(n.midAngle);
  10703. }
  10704. }
  10705. /** @private */
  10706. function y(n) {
  10707. switch (orient) {
  10708. case "left": return n.breadth * h;
  10709. case "right": return h - n.breadth * h;
  10710. case "top": return n.depth * h;
  10711. case "bottom": return h - n.depth * h;
  10712. case "radial": return h / 2 + radius(n) * Math.sin(n.midAngle);
  10713. }
  10714. }
  10715. for (var i = 0; i < nodes.length; i++) {
  10716. var n = nodes[i];
  10717. n.midAngle = orient == "radial" ? midAngle(n)
  10718. : horizontal ? Math.PI / 2 : 0;
  10719. n.x = x(n);
  10720. n.y = y(n);
  10721. if (n.firstChild) n.midAngle += Math.PI;
  10722. }
  10723. }
  10724. };
  10725. /** @private Provides standard space-filling layout based on breadth & depth. */
  10726. pv.Layout.Hierarchy.Fill = {
  10727. /** @private */
  10728. constructor: function() {
  10729. this.node
  10730. .strokeStyle("#fff")
  10731. .fillStyle("#ccc")
  10732. .width(function(n) { return n.dx; })
  10733. .height(function(n) { return n.dy; })
  10734. .innerRadius(function(n) { return n.innerRadius; })
  10735. .outerRadius(function(n) { return n.outerRadius; })
  10736. .startAngle(function(n) { return n.startAngle; })
  10737. .angle(function(n) { return n.angle; });
  10738. this.label
  10739. .textAlign("center")
  10740. .left(function(n) { return n.x + (n.dx / 2); })
  10741. .top(function(n) { return n.y + (n.dy / 2); });
  10742. /* Hide unsupported link. */
  10743. delete this.link;
  10744. },
  10745. /** @private */
  10746. buildImplied: function(s) {
  10747. var nodes = s.nodes,
  10748. orient = s.orient,
  10749. horizontal = /^(top|bottom)$/.test(orient),
  10750. w = s.width,
  10751. h = s.height,
  10752. depth = -nodes[0].minDepth;
  10753. /* Compute default inner and outer radius. */
  10754. if (orient == "radial") {
  10755. var ir = s.innerRadius, or = s.outerRadius;
  10756. if (ir == null) ir = 0;
  10757. if (ir) depth *= 2; // use full depth step for root
  10758. if (or == null) or = Math.min(w, h) / 2;
  10759. }
  10760. /** @private Scales the specified depth for a space-filling layout. */
  10761. function scale(d, depth) {
  10762. return (d + depth) / (1 + depth);
  10763. }
  10764. /** @private */
  10765. function x(n) {
  10766. switch (orient) {
  10767. case "left": return scale(n.minDepth, depth) * w;
  10768. case "right": return (1 - scale(n.maxDepth, depth)) * w;
  10769. case "top": return n.minBreadth * w;
  10770. case "bottom": return (1 - n.maxBreadth) * w;
  10771. case "radial": return w / 2;
  10772. }
  10773. }
  10774. /** @private */
  10775. function y(n) {
  10776. switch (orient) {
  10777. case "left": return n.minBreadth * h;
  10778. case "right": return (1 - n.maxBreadth) * h;
  10779. case "top": return scale(n.minDepth, depth) * h;
  10780. case "bottom": return (1 - scale(n.maxDepth, depth)) * h;
  10781. case "radial": return h / 2;
  10782. }
  10783. }
  10784. /** @private */
  10785. function dx(n) {
  10786. switch (orient) {
  10787. case "left":
  10788. case "right": return (n.maxDepth - n.minDepth) / (1 + depth) * w;
  10789. case "top":
  10790. case "bottom": return (n.maxBreadth - n.minBreadth) * w;
  10791. case "radial": return n.parentNode ? (n.innerRadius + n.outerRadius) * Math.cos(n.midAngle) : 0;
  10792. }
  10793. }
  10794. /** @private */
  10795. function dy(n) {
  10796. switch (orient) {
  10797. case "left":
  10798. case "right": return (n.maxBreadth - n.minBreadth) * h;
  10799. case "top":
  10800. case "bottom": return (n.maxDepth - n.minDepth) / (1 + depth) * h;
  10801. case "radial": return n.parentNode ? (n.innerRadius + n.outerRadius) * Math.sin(n.midAngle) : 0;
  10802. }
  10803. }
  10804. /** @private */
  10805. function innerRadius(n) {
  10806. return Math.max(0, scale(n.minDepth, depth / 2)) * (or - ir) + ir;
  10807. }
  10808. /** @private */
  10809. function outerRadius(n) {
  10810. return scale(n.maxDepth, depth / 2) * (or - ir) + ir;
  10811. }
  10812. /** @private */
  10813. function startAngle(n) {
  10814. return (n.parentNode ? n.minBreadth - .25 : 0) * 2 * Math.PI;
  10815. }
  10816. /** @private */
  10817. function angle(n) {
  10818. return (n.parentNode ? n.maxBreadth - n.minBreadth : 1) * 2 * Math.PI;
  10819. }
  10820. for (var i = 0; i < nodes.length; i++) {
  10821. var n = nodes[i];
  10822. n.x = x(n);
  10823. n.y = y(n);
  10824. if (orient == "radial") {
  10825. n.innerRadius = innerRadius(n);
  10826. n.outerRadius = outerRadius(n);
  10827. n.startAngle = startAngle(n);
  10828. n.angle = angle(n);
  10829. n.midAngle = n.startAngle + n.angle / 2;
  10830. } else {
  10831. n.midAngle = horizontal ? -Math.PI / 2 : 0;
  10832. }
  10833. n.dx = dx(n);
  10834. n.dy = dy(n);
  10835. }
  10836. }
  10837. };
  10838. /**
  10839. * Constructs a new, empty grid layout. Layouts are not typically constructed
  10840. * directly; instead, they are added to an existing panel via
  10841. * {@link pv.Mark#add}.
  10842. *
  10843. * @class Implements a grid layout with regularly-sized rows and columns. The
  10844. * number of rows and columns are determined from their respective
  10845. * properties. For example, the 2&times;3 array:
  10846. *
  10847. * <pre>1 2 3
  10848. * 4 5 6</pre>
  10849. *
  10850. * can be represented using the <tt>rows</tt> property as:
  10851. *
  10852. * <pre>[[1, 2, 3], [4, 5, 6]]</pre>
  10853. *
  10854. * If your data is in column-major order, you can equivalently use the
  10855. * <tt>columns</tt> property. If the <tt>rows</tt> property is an array, it
  10856. * takes priority over the <tt>columns</tt> property. The data is implicitly
  10857. * transposed, as if the {@link pv.transpose} operator were applied.
  10858. *
  10859. * <p>This layout exports a single <tt>cell</tt> mark prototype, which is
  10860. * intended to be used with a bar, panel, layout, or subclass thereof. The data
  10861. * property of the cell prototype is defined as the elements in the array. For
  10862. * example, if the array is a two-dimensional array of values in the range
  10863. * [0,1], a simple heatmap can be generated as:
  10864. *
  10865. * <pre>vis.add(pv.Layout.Grid)
  10866. * .rows(arrays)
  10867. * .cell.add(pv.Bar)
  10868. * .fillStyle(pv.ramp("white", "black"))</pre>
  10869. *
  10870. * The grid subdivides the full width and height of the parent panel into equal
  10871. * rectangles. Note, however, that for large, interactive, or animated heatmaps,
  10872. * you may see significantly better performance through dynamic {@link pv.Image}
  10873. * generation.
  10874. *
  10875. * <p>For irregular grids using value-based spatial partitioning, see {@link
  10876. * pv.Layout.Treemap}.
  10877. *
  10878. * @extends pv.Layout
  10879. */
  10880. pv.Layout.Grid = function() {
  10881. pv.Layout.call(this);
  10882. var that = this;
  10883. /**
  10884. * The cell prototype. This prototype is intended to be used with a bar,
  10885. * panel, or layout (or subclass thereof) to render the grid cells.
  10886. *
  10887. * @type pv.Mark
  10888. * @name pv.Layout.Grid.prototype.cell
  10889. */
  10890. (this.cell = new pv.Mark()
  10891. .data(function() {
  10892. return that.scene[that.index].$grid;
  10893. })
  10894. .width(function() {
  10895. return that.width() / that.cols();
  10896. })
  10897. .height(function() {
  10898. return that.height() / that.rows();
  10899. })
  10900. .left(function() {
  10901. return this.width() * (this.index % that.cols());
  10902. })
  10903. .top(function() {
  10904. return this.height() * Math.floor(this.index / that.cols());
  10905. })).parent = this;
  10906. };
  10907. pv.Layout.Grid.prototype = pv.extend(pv.Layout)
  10908. .property("rows")
  10909. .property("cols");
  10910. /**
  10911. * Default properties for grid layouts. By default, there is one row and one
  10912. * column, and the data is the propagated to the child cell.
  10913. *
  10914. * @type pv.Layout.Grid
  10915. */
  10916. pv.Layout.Grid.prototype.defaults = new pv.Layout.Grid()
  10917. .extend(pv.Layout.prototype.defaults)
  10918. .rows(1)
  10919. .cols(1);
  10920. /** @private */
  10921. pv.Layout.Grid.prototype.buildImplied = function(s) {
  10922. pv.Layout.prototype.buildImplied.call(this, s);
  10923. var r = s.rows, c = s.cols;
  10924. if (typeof c == "object") r = pv.transpose(c);
  10925. if (typeof r == "object") {
  10926. s.$grid = pv.blend(r);
  10927. s.rows = r.length;
  10928. s.cols = r[0] ? r[0].length : 0;
  10929. } else {
  10930. s.$grid = pv.repeat([s.data], r * c);
  10931. }
  10932. };
  10933. /**
  10934. * The number of rows. This property can also be specified as the data in
  10935. * row-major order; in this case, the rows property is implicitly set to the
  10936. * length of the array, and the cols property is set to the length of the first
  10937. * element in the array.
  10938. *
  10939. * @type number
  10940. * @name pv.Layout.Grid.prototype.rows
  10941. */
  10942. /**
  10943. * The number of columns. This property can also be specified as the data in
  10944. * column-major order; in this case, the cols property is implicitly set to the
  10945. * length of the array, and the rows property is set to the length of the first
  10946. * element in the array.
  10947. *
  10948. * @type number
  10949. * @name pv.Layout.Grid.prototype.cols
  10950. */
  10951. /**
  10952. * Constructs a new, empty stack layout. Layouts are not typically constructed
  10953. * directly; instead, they are added to an existing panel via
  10954. * {@link pv.Mark#add}.
  10955. *
  10956. * @class Implements a layout for stacked visualizations, ranging from simple
  10957. * stacked bar charts to more elaborate "streamgraphs" composed of stacked
  10958. * areas. Stack layouts uses length as a visual encoding, as opposed to
  10959. * position, as the layers do not share an aligned axis.
  10960. *
  10961. * <p>Marks can be stacked vertically or horizontally. For example,
  10962. *
  10963. * <pre>vis.add(pv.Layout.Stack)
  10964. * .layers([[1, 1.2, 1.7, 1.5, 1.7],
  10965. * [.5, 1, .8, 1.1, 1.3],
  10966. * [.2, .5, .8, .9, 1]])
  10967. * .x(function() this.index * 35)
  10968. * .y(function(d) d * 40)
  10969. * .layer.add(pv.Area);</pre>
  10970. *
  10971. * specifies a vertically-stacked area chart, using the default "bottom-left"
  10972. * orientation with "zero" offset. This visualization can be easily changed into
  10973. * a streamgraph using the "wiggle" offset, which attempts to minimize change in
  10974. * slope weighted by layer thickness. See the {@link #offset} property for more
  10975. * supported streamgraph algorithms.
  10976. *
  10977. * <p>In the simplest case, the layer data can be specified as a two-dimensional
  10978. * array of numbers. The <tt>x</tt> and <tt>y</tt> psuedo-properties are used to
  10979. * define the thickness of each layer at the given position, respectively; in
  10980. * the above example of the "bottom-left" orientation, the <tt>x</tt> and
  10981. * <tt>y</tt> psuedo-properties are equivalent to the <tt>left</tt> and
  10982. * <tt>height</tt> properties that you might use if you implemented a stacked
  10983. * area by hand.
  10984. *
  10985. * <p>The advantage of using the stack layout is that the baseline, i.e., the
  10986. * <tt>bottom</tt> property is computed automatically using the specified offset
  10987. * algorithm. In addition, the order of layers can be computed using a built-in
  10988. * algorithm via the <tt>order</tt> property.
  10989. *
  10990. * <p>With the exception of the "expand" <tt>offset</tt>, the stack layout does
  10991. * not perform any automatic scaling of data; the values returned from
  10992. * <tt>x</tt> and <tt>y</tt> specify pixel sizes. To simplify scaling math, use
  10993. * this layout in conjunction with {@link pv.Scale.linear} or similar.
  10994. *
  10995. * <p>In other cases, the <tt>values</tt> psuedo-property can be used to define
  10996. * the data more flexibly. As with a typical panel &amp; area, the
  10997. * <tt>layers</tt> property corresponds to the data in the enclosing panel,
  10998. * while the <tt>values</tt> psuedo-property corresponds to the data for the
  10999. * area within the panel. For example, given an array of data values:
  11000. *
  11001. * <pre>var crimea = [
  11002. * { date: "4/1854", wounds: 0, other: 110, disease: 110 },
  11003. * { date: "5/1854", wounds: 0, other: 95, disease: 105 },
  11004. * { date: "6/1854", wounds: 0, other: 40, disease: 95 },
  11005. * ...</pre>
  11006. *
  11007. * and a corresponding array of series names:
  11008. *
  11009. * <pre>var causes = ["wounds", "other", "disease"];</pre>
  11010. *
  11011. * Separate layers can be defined for each cause like so:
  11012. *
  11013. * <pre>vis.add(pv.Layout.Stack)
  11014. * .layers(causes)
  11015. * .values(crimea)
  11016. * .x(function(d) x(d.date))
  11017. * .y(function(d, p) y(d[p]))
  11018. * .layer.add(pv.Area)
  11019. * ...</pre>
  11020. *
  11021. * As with the panel &amp; area case, the datum that is passed to the
  11022. * psuedo-properties <tt>x</tt> and <tt>y</tt> are the values (an element in
  11023. * <tt>crimea</tt>); the second argument is the layer data (a string in
  11024. * <tt>causes</tt>). Additional arguments specify the data of enclosing panels,
  11025. * if any.
  11026. *
  11027. * @extends pv.Layout
  11028. */
  11029. pv.Layout.Stack = function() {
  11030. pv.Layout.call(this);
  11031. var that = this,
  11032. /** @ignore */ none = function() { return null; },
  11033. prop = {t: none, l: none, r: none, b: none, w: none, h: none},
  11034. values,
  11035. buildImplied = that.buildImplied;
  11036. /** @private Proxy the given property on the layer. */
  11037. function proxy(name) {
  11038. return function() {
  11039. return prop[name](this.parent.index, this.index);
  11040. };
  11041. }
  11042. /** @private Compute the layout! */
  11043. this.buildImplied = function(s) {
  11044. buildImplied.call(this, s);
  11045. var data = s.layers,
  11046. n = data.length,
  11047. m,
  11048. orient = s.orient,
  11049. horizontal = /^(top|bottom)\b/.test(orient),
  11050. h = this.parent[horizontal ? "height" : "width"](),
  11051. x = [],
  11052. y = [],
  11053. dy = [];
  11054. /*
  11055. * Iterate over the data, evaluating the values, x and y functions. The
  11056. * context in which the x and y psuedo-properties are evaluated is a
  11057. * pseudo-mark that is a grandchild of this layout.
  11058. */
  11059. var stack = pv.Mark.stack, o = {parent: {parent: this}};
  11060. stack.unshift(null);
  11061. values = [];
  11062. for (var i = 0; i < n; i++) {
  11063. dy[i] = [];
  11064. y[i] = [];
  11065. o.parent.index = i;
  11066. stack[0] = data[i];
  11067. values[i] = this.$values.apply(o.parent, stack);
  11068. if (!i) m = values[i].length;
  11069. stack.unshift(null);
  11070. for (var j = 0; j < m; j++) {
  11071. stack[0] = values[i][j];
  11072. o.index = j;
  11073. if (!i) x[j] = this.$x.apply(o, stack);
  11074. dy[i][j] = this.$y.apply(o, stack);
  11075. }
  11076. stack.shift();
  11077. }
  11078. stack.shift();
  11079. /* order */
  11080. var index;
  11081. switch (s.order) {
  11082. case "inside-out": {
  11083. var max = dy.map(function(v) { return pv.max.index(v); }),
  11084. map = pv.range(n).sort(function(a, b) { return max[a] - max[b]; }),
  11085. sums = dy.map(function(v) { return pv.sum(v); }),
  11086. top = 0,
  11087. bottom = 0,
  11088. tops = [],
  11089. bottoms = [];
  11090. for (var i = 0; i < n; i++) {
  11091. var j = map[i];
  11092. if (top < bottom) {
  11093. top += sums[j];
  11094. tops.push(j);
  11095. } else {
  11096. bottom += sums[j];
  11097. bottoms.push(j);
  11098. }
  11099. }
  11100. index = bottoms.reverse().concat(tops);
  11101. break;
  11102. }
  11103. case "reverse": index = pv.range(n - 1, -1, -1); break;
  11104. default: index = pv.range(n); break;
  11105. }
  11106. /* offset */
  11107. switch (s.offset) {
  11108. case "silohouette": {
  11109. for (var j = 0; j < m; j++) {
  11110. var o = 0;
  11111. for (var i = 0; i < n; i++) o += dy[i][j];
  11112. y[index[0]][j] = (h - o) / 2;
  11113. }
  11114. break;
  11115. }
  11116. case "wiggle": {
  11117. var o = 0;
  11118. for (var i = 0; i < n; i++) o += dy[i][0];
  11119. y[index[0]][0] = o = (h - o) / 2;
  11120. for (var j = 1; j < m; j++) {
  11121. var s1 = 0, s2 = 0, dx = x[j] - x[j - 1];
  11122. for (var i = 0; i < n; i++) s1 += dy[i][j];
  11123. for (var i = 0; i < n; i++) {
  11124. var s3 = (dy[index[i]][j] - dy[index[i]][j - 1]) / (2 * dx);
  11125. for (var k = 0; k < i; k++) {
  11126. s3 += (dy[index[k]][j] - dy[index[k]][j - 1]) / dx;
  11127. }
  11128. s2 += s3 * dy[index[i]][j];
  11129. }
  11130. y[index[0]][j] = o -= s1 ? s2 / s1 * dx : 0;
  11131. }
  11132. break;
  11133. }
  11134. case "expand": {
  11135. for (var j = 0; j < m; j++) {
  11136. y[index[0]][j] = 0;
  11137. var k = 0;
  11138. for (var i = 0; i < n; i++) k += dy[i][j];
  11139. if (k) {
  11140. k = h / k;
  11141. for (var i = 0; i < n; i++) dy[i][j] *= k;
  11142. } else {
  11143. k = h / n;
  11144. for (var i = 0; i < n; i++) dy[i][j] = k;
  11145. }
  11146. }
  11147. break;
  11148. }
  11149. default: {
  11150. for (var j = 0; j < m; j++) y[index[0]][j] = 0;
  11151. break;
  11152. }
  11153. }
  11154. /* Propagate the offset to the other series. */
  11155. for (var j = 0; j < m; j++) {
  11156. var o = y[index[0]][j];
  11157. for (var i = 1; i < n; i++) {
  11158. o += dy[index[i - 1]][j];
  11159. y[index[i]][j] = o;
  11160. }
  11161. }
  11162. /* Find the property definitions for dynamic substitution. */
  11163. var i = orient.indexOf("-"),
  11164. pdy = horizontal ? "h" : "w",
  11165. px = i < 0 ? (horizontal ? "l" : "b") : orient.charAt(i + 1),
  11166. py = orient.charAt(0);
  11167. for (var p in prop) prop[p] = none;
  11168. prop[px] = function(i, j) { return x[j]; };
  11169. prop[py] = function(i, j) { return y[i][j]; };
  11170. prop[pdy] = function(i, j) { return dy[i][j]; };
  11171. };
  11172. /**
  11173. * The layer prototype. This prototype is intended to be used with an area,
  11174. * bar or panel mark (or subclass thereof). Other mark types may be possible,
  11175. * though note that the stack layout is not currently designed to support
  11176. * radial stacked visualizations using wedges.
  11177. *
  11178. * <p>The layer is not a direct child of the stack layout; a hidden panel is
  11179. * used to replicate layers.
  11180. *
  11181. * @type pv.Mark
  11182. * @name pv.Layout.Stack.prototype.layer
  11183. */
  11184. this.layer = new pv.Mark()
  11185. .data(function() { return values[this.parent.index]; })
  11186. .top(proxy("t"))
  11187. .left(proxy("l"))
  11188. .right(proxy("r"))
  11189. .bottom(proxy("b"))
  11190. .width(proxy("w"))
  11191. .height(proxy("h"));
  11192. this.layer.add = function(type) {
  11193. return that.add(pv.Panel)
  11194. .data(function() { return that.layers(); })
  11195. .add(type)
  11196. .extend(this);
  11197. };
  11198. };
  11199. pv.Layout.Stack.prototype = pv.extend(pv.Layout)
  11200. .property("orient", String)
  11201. .property("offset", String)
  11202. .property("order", String)
  11203. .property("layers");
  11204. /**
  11205. * Default properties for stack layouts. The default orientation is
  11206. * "bottom-left", the default offset is "zero", and the default layers is
  11207. * <tt>[[]]</tt>.
  11208. *
  11209. * @type pv.Layout.Stack
  11210. */
  11211. pv.Layout.Stack.prototype.defaults = new pv.Layout.Stack()
  11212. .extend(pv.Layout.prototype.defaults)
  11213. .orient("bottom-left")
  11214. .offset("zero")
  11215. .layers([[]]);
  11216. /** @private */
  11217. pv.Layout.Stack.prototype.$x
  11218. = /** @private */ pv.Layout.Stack.prototype.$y
  11219. = function() { return 0; };
  11220. /**
  11221. * The x psuedo-property; determines the position of the value within the layer.
  11222. * This typically corresponds to the independent variable. For example, with the
  11223. * default "bottom-left" orientation, this function defines the "left" property.
  11224. *
  11225. * @param {function} f the x function.
  11226. * @returns {pv.Layout.Stack} this.
  11227. */
  11228. pv.Layout.Stack.prototype.x = function(f) {
  11229. /** @private */ this.$x = pv.functor(f);
  11230. return this;
  11231. };
  11232. /**
  11233. * The y psuedo-property; determines the thickness of the layer at the given
  11234. * value. This typically corresponds to the dependent variable. For example,
  11235. * with the default "bottom-left" orientation, this function defines the
  11236. * "height" property.
  11237. *
  11238. * @param {function} f the y function.
  11239. * @returns {pv.Layout.Stack} this.
  11240. */
  11241. pv.Layout.Stack.prototype.y = function(f) {
  11242. /** @private */ this.$y = pv.functor(f);
  11243. return this;
  11244. };
  11245. /** @private The default value function; identity. */
  11246. pv.Layout.Stack.prototype.$values = pv.identity;
  11247. /**
  11248. * The values function; determines the values for a given layer. The default
  11249. * value is the identity function, which assumes that the layers property is
  11250. * specified as a two-dimensional (i.e., nested) array.
  11251. *
  11252. * @param {function} f the values function.
  11253. * @returns {pv.Layout.Stack} this.
  11254. */
  11255. pv.Layout.Stack.prototype.values = function(f) {
  11256. this.$values = pv.functor(f);
  11257. return this;
  11258. };
  11259. /**
  11260. * The layer data in row-major order. The value of this property is typically a
  11261. * two-dimensional (i.e., nested) array, but any array can be used, provided the
  11262. * values psuedo-property is defined accordingly.
  11263. *
  11264. * @type array[]
  11265. * @name pv.Layout.Stack.prototype.layers
  11266. */
  11267. /**
  11268. * The layer orientation. The following values are supported:<ul>
  11269. *
  11270. * <li>bottom-left == bottom
  11271. * <li>bottom-right
  11272. * <li>top-left == top
  11273. * <li>top-right
  11274. * <li>left-top
  11275. * <li>left-bottom == left
  11276. * <li>right-top
  11277. * <li>right-bottom == right
  11278. *
  11279. * </ul>. The default value is "bottom-left", which means that the layers will
  11280. * be built from the bottom-up, and the values within layers will be laid out
  11281. * from left-to-right.
  11282. *
  11283. * <p>Note that with non-zero baselines, some orientations may give similar
  11284. * results. For example, offset("silohouette") centers the layers, resulting in
  11285. * a streamgraph. Thus, the orientations "bottom-left" and "top-left" will
  11286. * produce similar results, differing only in the layer order.
  11287. *
  11288. * @type string
  11289. * @name pv.Layout.Stack.prototype.orient
  11290. */
  11291. /**
  11292. * The layer order. The following values are supported:<ul>
  11293. *
  11294. * <li><i>null</i> - use given layer order.
  11295. * <li>inside-out - sort by maximum value, with balanced order.
  11296. * <li>reverse - use reverse of given layer order.
  11297. *
  11298. * </ul>For details on the inside-out order algorithm, refer to "Stacked Graphs
  11299. * -- Geometry &amp; Aesthetics" by L. Byron and M. Wattenberg, IEEE TVCG
  11300. * November/December 2008.
  11301. *
  11302. * @type string
  11303. * @name pv.Layout.Stack.prototype.order
  11304. */
  11305. /**
  11306. * The layer offset; the y-position of the bottom of the lowest layer. The
  11307. * following values are supported:<ul>
  11308. *
  11309. * <li>zero - use a zero baseline, i.e., the y-axis.
  11310. * <li>silohouette - center the stream, i.e., ThemeRiver.
  11311. * <li>wiggle - minimize weighted change in slope.
  11312. * <li>expand - expand layers to fill the enclosing layout dimensions.
  11313. *
  11314. * </ul>For details on these offset algorithms, refer to "Stacked Graphs --
  11315. * Geometry &amp; Aesthetics" by L. Byron and M. Wattenberg, IEEE TVCG
  11316. * November/December 2008.
  11317. *
  11318. * @type string
  11319. * @name pv.Layout.Stack.prototype.offset
  11320. */
  11321. /**
  11322. * Constructs a new, empty treemap layout. Layouts are not typically
  11323. * constructed directly; instead, they are added to an existing panel via
  11324. * {@link pv.Mark#add}.
  11325. *
  11326. * @class Implements a space-filling rectangular layout, with the hierarchy
  11327. * represented via containment. Treemaps represent nodes as boxes, with child
  11328. * nodes placed within parent boxes. The size of each box is proportional to the
  11329. * size of the node in the tree. This particular algorithm is taken from Bruls,
  11330. * D.M., C. Huizing, and J.J. van Wijk, <a
  11331. * href="http://www.win.tue.nl/~vanwijk/stm.pdf">"Squarified Treemaps"</a> in
  11332. * <i>Data Visualization 2000, Proceedings of the Joint Eurographics and IEEE
  11333. * TCVG Sumposium on Visualization</i>, 2000, pp. 33-42.
  11334. *
  11335. * <p>The meaning of the exported mark prototypes changes slightly in the
  11336. * space-filling implementation:<ul>
  11337. *
  11338. * <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Bar}. The node
  11339. * data is populated with <tt>dx</tt> and <tt>dy</tt> attributes, in addition to
  11340. * the standard <tt>x</tt> and <tt>y</tt> position attributes.
  11341. *
  11342. * <p><li><tt>leaf</tt> - for rendering leaf nodes only, with no fill or stroke
  11343. * style by default; typically a {@link pv.Panel} or another layout!
  11344. *
  11345. * <p><li><tt>link</tt> - unsupported; undefined. Links are encoded implicitly
  11346. * in the arrangement of the space-filling nodes.
  11347. *
  11348. * <p><li><tt>label</tt> - for rendering node labels; typically a
  11349. * {@link pv.Label}.
  11350. *
  11351. * </ul>For more details on how to use this layout, see
  11352. * {@link pv.Layout.Hierarchy}.
  11353. *
  11354. * @extends pv.Layout.Hierarchy
  11355. */
  11356. pv.Layout.Treemap = function() {
  11357. pv.Layout.Hierarchy.call(this);
  11358. this.node
  11359. .strokeStyle("#fff")
  11360. .fillStyle("rgba(31, 119, 180, .25)")
  11361. .width(function(n) { return n.dx; })
  11362. .height(function(n) { return n.dy; });
  11363. this.label
  11364. .visible(function(n) { return !n.firstChild; })
  11365. .left(function(n) { return n.x + (n.dx / 2); })
  11366. .top(function(n) { return n.y + (n.dy / 2); })
  11367. .textAlign("center")
  11368. .textAngle(function(n) { return n.dx > n.dy ? 0 : -Math.PI / 2; });
  11369. (this.leaf = new pv.Mark()
  11370. .extend(this.node)
  11371. .fillStyle(null)
  11372. .strokeStyle(null)
  11373. .visible(function(n) { return !n.firstChild; })).parent = this;
  11374. /* Hide unsupported link. */
  11375. delete this.link;
  11376. };
  11377. pv.Layout.Treemap.prototype = pv.extend(pv.Layout.Hierarchy)
  11378. .property("round", Boolean)
  11379. .property("paddingLeft", Number)
  11380. .property("paddingRight", Number)
  11381. .property("paddingTop", Number)
  11382. .property("paddingBottom", Number)
  11383. .property("mode", String)
  11384. .property("order", String);
  11385. /**
  11386. * Default propertiess for treemap layouts. The default mode is "squarify" and
  11387. * the default order is "ascending".
  11388. *
  11389. * @type pv.Layout.Treemap
  11390. */
  11391. pv.Layout.Treemap.prototype.defaults = new pv.Layout.Treemap()
  11392. .extend(pv.Layout.Hierarchy.prototype.defaults)
  11393. .mode("squarify") // squarify, slice-and-dice, slice, dice
  11394. .order("ascending"); // ascending, descending, reverse, null
  11395. /**
  11396. * Whether node sizes should be rounded to integer values. This has a similar
  11397. * effect to setting <tt>antialias(false)</tt> for node values, but allows the
  11398. * treemap algorithm to accumulate error related to pixel rounding.
  11399. *
  11400. * @type boolean
  11401. * @name pv.Layout.Treemap.prototype.round
  11402. */
  11403. /**
  11404. * The left inset between parent add child in pixels. Defaults to 0.
  11405. *
  11406. * @type number
  11407. * @name pv.Layout.Treemap.prototype.paddingLeft
  11408. * @see #padding
  11409. */
  11410. /**
  11411. * The right inset between parent add child in pixels. Defaults to 0.
  11412. *
  11413. * @type number
  11414. * @name pv.Layout.Treemap.prototype.paddingRight
  11415. * @see #padding
  11416. */
  11417. /**
  11418. * The top inset between parent and child in pixels. Defaults to 0.
  11419. *
  11420. * @type number
  11421. * @name pv.Layout.Treemap.prototype.paddingTop
  11422. * @see #padding
  11423. */
  11424. /**
  11425. * The bottom inset between parent and child in pixels. Defaults to 0.
  11426. *
  11427. * @type number
  11428. * @name pv.Layout.Treemap.prototype.paddingBottom
  11429. * @see #padding
  11430. */
  11431. /**
  11432. * The treemap algorithm. The default value is "squarify". The "slice-and-dice"
  11433. * algorithm may also be used, which alternates between horizontal and vertical
  11434. * slices for different depths. In addition, the "slice" and "dice" algorithms
  11435. * may be specified explicitly to control whether horizontal or vertical slices
  11436. * are used, which may be useful for nested treemap layouts.
  11437. *
  11438. * @type string
  11439. * @name pv.Layout.Treemap.prototype.mode
  11440. * @see <a
  11441. * href="ftp://ftp.cs.umd.edu/pub/hcil/Reports-Abstracts-Bibliography/2001-06html/2001-06.pdf"
  11442. * >"Ordered Treemap Layouts"</a> by B. Shneiderman &amp; M. Wattenberg, IEEE
  11443. * InfoVis 2001.
  11444. */
  11445. /**
  11446. * The sibling node order. A <tt>null</tt> value means to use the sibling order
  11447. * specified by the nodes property as-is; "reverse" will reverse the given
  11448. * order. The default value "ascending" will sort siblings in ascending order of
  11449. * size, while "descending" will do the reverse. For sorting based on data
  11450. * attributes other than size, use the default <tt>null</tt> for the order
  11451. * property, and sort the nodes beforehand using the {@link pv.Dom} operator.
  11452. *
  11453. * @type string
  11454. * @name pv.Layout.Treemap.prototype.order
  11455. */
  11456. /**
  11457. * Alias for setting the left, right, top and bottom padding properties
  11458. * simultaneously.
  11459. *
  11460. * @see #paddingLeft
  11461. * @see #paddingRight
  11462. * @see #paddingTop
  11463. * @see #paddingBottom
  11464. * @returns {pv.Layout.Treemap} this.
  11465. */
  11466. pv.Layout.Treemap.prototype.padding = function(n) {
  11467. return this.paddingLeft(n).paddingRight(n).paddingTop(n).paddingBottom(n);
  11468. };
  11469. /** @private The default size function. */
  11470. pv.Layout.Treemap.prototype.$size = function(d) {
  11471. return Number(d.nodeValue);
  11472. };
  11473. /**
  11474. * Specifies the sizing function. By default, the size function uses the
  11475. * <tt>nodeValue</tt> attribute of nodes as a numeric value: <tt>function(d)
  11476. * Number(d.nodeValue)</tt>.
  11477. *
  11478. * <p>The sizing function is invoked for each leaf node in the tree, per the
  11479. * <tt>nodes</tt> property. For example, if the tree data structure represents a
  11480. * file system, with files as leaf nodes, and each file has a <tt>bytes</tt>
  11481. * attribute, you can specify a size function as:
  11482. *
  11483. * <pre> .size(function(d) d.bytes)</pre>
  11484. *
  11485. * @param {function} f the new sizing function.
  11486. * @returns {pv.Layout.Treemap} this.
  11487. */
  11488. pv.Layout.Treemap.prototype.size = function(f) {
  11489. this.$size = pv.functor(f);
  11490. return this;
  11491. };
  11492. /** @private */
  11493. pv.Layout.Treemap.prototype.buildImplied = function(s) {
  11494. if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) return;
  11495. var that = this,
  11496. nodes = s.nodes,
  11497. root = nodes[0],
  11498. stack = pv.Mark.stack,
  11499. left = s.paddingLeft,
  11500. right = s.paddingRight,
  11501. top = s.paddingTop,
  11502. bottom = s.paddingBottom,
  11503. /** @ignore */ size = function(n) { return n.size; },
  11504. round = s.round ? Math.round : Number,
  11505. mode = s.mode;
  11506. /** @private */
  11507. function slice(row, sum, horizontal, x, y, w, h) {
  11508. for (var i = 0, d = 0; i < row.length; i++) {
  11509. var n = row[i];
  11510. if (horizontal) {
  11511. n.x = x + d;
  11512. n.y = y;
  11513. d += n.dx = round(w * n.size / sum);
  11514. n.dy = h;
  11515. } else {
  11516. n.x = x;
  11517. n.y = y + d;
  11518. n.dx = w;
  11519. d += n.dy = round(h * n.size / sum);
  11520. }
  11521. }
  11522. if (n) { // correct on-axis rounding error
  11523. if (horizontal) {
  11524. n.dx += w - d;
  11525. } else {
  11526. n.dy += h - d;
  11527. }
  11528. }
  11529. }
  11530. /** @private */
  11531. function ratio(row, l) {
  11532. var rmax = -Infinity, rmin = Infinity, s = 0;
  11533. for (var i = 0; i < row.length; i++) {
  11534. var r = row[i].size;
  11535. if (r < rmin) rmin = r;
  11536. if (r > rmax) rmax = r;
  11537. s += r;
  11538. }
  11539. s = s * s;
  11540. l = l * l;
  11541. return Math.max(l * rmax / s, s / (l * rmin));
  11542. }
  11543. /** @private */
  11544. function layout(n, i) {
  11545. var x = n.x + left,
  11546. y = n.y + top,
  11547. w = n.dx - left - right,
  11548. h = n.dy - top - bottom;
  11549. /* Assume squarify by default. */
  11550. if (mode != "squarify") {
  11551. slice(n.childNodes, n.size,
  11552. mode == "slice" ? true
  11553. : mode == "dice" ? false
  11554. : i & 1, x, y, w, h);
  11555. return;
  11556. }
  11557. var row = [],
  11558. mink = Infinity,
  11559. l = Math.min(w, h),
  11560. k = w * h / n.size;
  11561. /* Abort if the size is nonpositive. */
  11562. if (n.size <= 0) return;
  11563. /* Scale the sizes to fill the current subregion. */
  11564. n.visitBefore(function(n) { n.size *= k; });
  11565. /** @private Position the specified nodes along one dimension. */
  11566. function position(row) {
  11567. var horizontal = w == l,
  11568. sum = pv.sum(row, size),
  11569. r = l ? round(sum / l) : 0;
  11570. slice(row, sum, horizontal, x, y, horizontal ? w : r, horizontal ? r : h);
  11571. if (horizontal) {
  11572. y += r;
  11573. h -= r;
  11574. } else {
  11575. x += r;
  11576. w -= r;
  11577. }
  11578. l = Math.min(w, h);
  11579. return horizontal;
  11580. }
  11581. var children = n.childNodes.slice(); // copy
  11582. while (children.length) {
  11583. var child = children[children.length - 1];
  11584. if (!child.size) {
  11585. children.pop();
  11586. continue;
  11587. }
  11588. row.push(child);
  11589. var k = ratio(row, l);
  11590. if (k <= mink) {
  11591. children.pop();
  11592. mink = k;
  11593. } else {
  11594. row.pop();
  11595. position(row);
  11596. row.length = 0;
  11597. mink = Infinity;
  11598. }
  11599. }
  11600. /* correct off-axis rounding error */
  11601. if (position(row)) for (var i = 0; i < row.length; i++) {
  11602. row[i].dy += h;
  11603. } else for (var i = 0; i < row.length; i++) {
  11604. row[i].dx += w;
  11605. }
  11606. }
  11607. /* Recursively compute the node depth and size. */
  11608. stack.unshift(null);
  11609. root.visitAfter(function(n, i) {
  11610. n.depth = i;
  11611. n.x = n.y = n.dx = n.dy = 0;
  11612. n.size = n.firstChild
  11613. ? pv.sum(n.childNodes, function(n) { return n.size; })
  11614. : that.$size.apply(that, (stack[0] = n, stack));
  11615. });
  11616. stack.shift();
  11617. /* Sort. */
  11618. switch (s.order) {
  11619. case "ascending": {
  11620. root.sort(function(a, b) { return a.size - b.size; });
  11621. break;
  11622. }
  11623. case "descending": {
  11624. root.sort(function(a, b) { return b.size - a.size; });
  11625. break;
  11626. }
  11627. case "reverse": root.reverse(); break;
  11628. }
  11629. /* Recursively compute the layout. */
  11630. root.x = 0;
  11631. root.y = 0;
  11632. root.dx = s.width;
  11633. root.dy = s.height;
  11634. root.visitBefore(layout);
  11635. };
  11636. /**
  11637. * Constructs a new, empty tree layout. Layouts are not typically constructed
  11638. * directly; instead, they are added to an existing panel via
  11639. * {@link pv.Mark#add}.
  11640. *
  11641. * @class Implements a node-link tree diagram using the Reingold-Tilford "tidy"
  11642. * tree layout algorithm. The specific algorithm used by this layout is based on
  11643. * <a href="http://citeseer.ist.psu.edu/buchheim02improving.html">"Improving
  11644. * Walker's Algorithm to Run in Linear Time"</A> by C. Buchheim, M. J&uuml;nger
  11645. * &amp; S. Leipert, Graph Drawing 2002. This layout supports both cartesian and
  11646. * radial orientations orientations for node-link diagrams.
  11647. *
  11648. * <p>The tree layout supports a "group" property, which if true causes siblings
  11649. * to be positioned closer together than unrelated nodes at the same depth. The
  11650. * layout can be configured using the <tt>depth</tt> and <tt>breadth</tt>
  11651. * properties, which control the increments in pixel space between nodes in both
  11652. * dimensions, similar to the indent layout.
  11653. *
  11654. * <p>For more details on how to use this layout, see
  11655. * {@link pv.Layout.Hierarchy}.
  11656. *
  11657. * @extends pv.Layout.Hierarchy
  11658. */
  11659. pv.Layout.Tree = function() {
  11660. pv.Layout.Hierarchy.call(this);
  11661. };
  11662. pv.Layout.Tree.prototype = pv.extend(pv.Layout.Hierarchy)
  11663. .property("group", Number)
  11664. .property("breadth", Number)
  11665. .property("depth", Number)
  11666. .property("orient", String);
  11667. /**
  11668. * Default properties for tree layouts. The default orientation is "top", the
  11669. * default group parameter is 1, and the default breadth and depth offsets are
  11670. * 15 and 60 respectively.
  11671. *
  11672. * @type pv.Layout.Tree
  11673. */
  11674. pv.Layout.Tree.prototype.defaults = new pv.Layout.Tree()
  11675. .extend(pv.Layout.Hierarchy.prototype.defaults)
  11676. .group(1)
  11677. .breadth(15)
  11678. .depth(60)
  11679. .orient("top");
  11680. /** @private */
  11681. pv.Layout.Tree.prototype.buildImplied = function(s) {
  11682. if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) return;
  11683. var nodes = s.nodes,
  11684. orient = s.orient,
  11685. depth = s.depth,
  11686. breadth = s.breadth,
  11687. group = s.group,
  11688. w = s.width,
  11689. h = s.height;
  11690. /** @private */
  11691. function firstWalk(v) {
  11692. var l, r, a;
  11693. if (!v.firstChild) {
  11694. if (l = v.previousSibling) {
  11695. v.prelim = l.prelim + distance(v.depth, true);
  11696. }
  11697. } else {
  11698. l = v.firstChild;
  11699. r = v.lastChild;
  11700. a = l; // default ancestor
  11701. for (var c = l; c; c = c.nextSibling) {
  11702. firstWalk(c);
  11703. a = apportion(c, a);
  11704. }
  11705. executeShifts(v);
  11706. var midpoint = .5 * (l.prelim + r.prelim);
  11707. if (l = v.previousSibling) {
  11708. v.prelim = l.prelim + distance(v.depth, true);
  11709. v.mod = v.prelim - midpoint;
  11710. } else {
  11711. v.prelim = midpoint;
  11712. }
  11713. }
  11714. }
  11715. /** @private */
  11716. function secondWalk(v, m, depth) {
  11717. v.breadth = v.prelim + m;
  11718. m += v.mod;
  11719. for (var c = v.firstChild; c; c = c.nextSibling) {
  11720. secondWalk(c, m, depth);
  11721. }
  11722. }
  11723. /** @private */
  11724. function apportion(v, a) {
  11725. var w = v.previousSibling;
  11726. if (w) {
  11727. var vip = v,
  11728. vop = v,
  11729. vim = w,
  11730. vom = v.parentNode.firstChild,
  11731. sip = vip.mod,
  11732. sop = vop.mod,
  11733. sim = vim.mod,
  11734. som = vom.mod,
  11735. nr = nextRight(vim),
  11736. nl = nextLeft(vip);
  11737. while (nr && nl) {
  11738. vim = nr;
  11739. vip = nl;
  11740. vom = nextLeft(vom);
  11741. vop = nextRight(vop);
  11742. vop.ancestor = v;
  11743. var shift = (vim.prelim + sim) - (vip.prelim + sip) + distance(vim.depth, false);
  11744. if (shift > 0) {
  11745. moveSubtree(ancestor(vim, v, a), v, shift);
  11746. sip += shift;
  11747. sop += shift;
  11748. }
  11749. sim += vim.mod;
  11750. sip += vip.mod;
  11751. som += vom.mod;
  11752. sop += vop.mod;
  11753. nr = nextRight(vim);
  11754. nl = nextLeft(vip);
  11755. }
  11756. if (nr && !nextRight(vop)) {
  11757. vop.thread = nr;
  11758. vop.mod += sim - sop;
  11759. }
  11760. if (nl && !nextLeft(vom)) {
  11761. vom.thread = nl;
  11762. vom.mod += sip - som;
  11763. a = v;
  11764. }
  11765. }
  11766. return a;
  11767. }
  11768. /** @private */
  11769. function nextLeft(v) {
  11770. return v.firstChild || v.thread;
  11771. }
  11772. /** @private */
  11773. function nextRight(v) {
  11774. return v.lastChild || v.thread;
  11775. }
  11776. /** @private */
  11777. function moveSubtree(wm, wp, shift) {
  11778. var subtrees = wp.number - wm.number;
  11779. wp.change -= shift / subtrees;
  11780. wp.shift += shift;
  11781. wm.change += shift / subtrees;
  11782. wp.prelim += shift;
  11783. wp.mod += shift;
  11784. }
  11785. /** @private */
  11786. function executeShifts(v) {
  11787. var shift = 0, change = 0;
  11788. for (var c = v.lastChild; c; c = c.previousSibling) {
  11789. c.prelim += shift;
  11790. c.mod += shift;
  11791. change += c.change;
  11792. shift += c.shift + change;
  11793. }
  11794. }
  11795. /** @private */
  11796. function ancestor(vim, v, a) {
  11797. return (vim.ancestor.parentNode == v.parentNode) ? vim.ancestor : a;
  11798. }
  11799. /** @private */
  11800. function distance(depth, siblings) {
  11801. return (siblings ? 1 : (group + 1)) / ((orient == "radial") ? depth : 1);
  11802. }
  11803. /* Initialize temporary layout variables. TODO: store separately. */
  11804. var root = nodes[0];
  11805. root.visitAfter(function(v, i) {
  11806. v.ancestor = v;
  11807. v.prelim = 0;
  11808. v.mod = 0;
  11809. v.change = 0;
  11810. v.shift = 0;
  11811. v.number = v.previousSibling ? (v.previousSibling.number + 1) : 0;
  11812. v.depth = i;
  11813. });
  11814. /* Compute the layout using Buchheim et al.'s algorithm. */
  11815. firstWalk(root);
  11816. secondWalk(root, -root.prelim, 0);
  11817. /** @private Returns the angle of the given node. */
  11818. function midAngle(n) {
  11819. return (orient == "radial") ? n.breadth / depth : 0;
  11820. }
  11821. /** @private */
  11822. function x(n) {
  11823. switch (orient) {
  11824. case "left": return n.depth;
  11825. case "right": return w - n.depth;
  11826. case "top":
  11827. case "bottom": return n.breadth + w / 2;
  11828. case "radial": return w / 2 + n.depth * Math.cos(midAngle(n));
  11829. }
  11830. }
  11831. /** @private */
  11832. function y(n) {
  11833. switch (orient) {
  11834. case "left":
  11835. case "right": return n.breadth + h / 2;
  11836. case "top": return n.depth;
  11837. case "bottom": return h - n.depth;
  11838. case "radial": return h / 2 + n.depth * Math.sin(midAngle(n));
  11839. }
  11840. }
  11841. /* Clear temporary layout variables; transform depth and breadth. */
  11842. root.visitAfter(function(v) {
  11843. v.breadth *= breadth;
  11844. v.depth *= depth;
  11845. v.midAngle = midAngle(v);
  11846. v.x = x(v);
  11847. v.y = y(v);
  11848. if (v.firstChild) v.midAngle += Math.PI;
  11849. delete v.breadth;
  11850. delete v.depth;
  11851. delete v.ancestor;
  11852. delete v.prelim;
  11853. delete v.mod;
  11854. delete v.change;
  11855. delete v.shift;
  11856. delete v.number;
  11857. delete v.thread;
  11858. });
  11859. };
  11860. /**
  11861. * The offset between siblings nodes; defaults to 15.
  11862. *
  11863. * @type number
  11864. * @name pv.Layout.Tree.prototype.breadth
  11865. */
  11866. /**
  11867. * The offset between parent and child nodes; defaults to 60.
  11868. *
  11869. * @type number
  11870. * @name pv.Layout.Tree.prototype.depth
  11871. */
  11872. /**
  11873. * The orientation. The default orientation is "top", which means that the root
  11874. * node is placed on the top edge, leaf nodes appear at the bottom, and internal
  11875. * nodes are in-between. The following orientations are supported:<ul>
  11876. *
  11877. * <li>left - left-to-right.
  11878. * <li>right - right-to-left.
  11879. * <li>top - top-to-bottom.
  11880. * <li>bottom - bottom-to-top.
  11881. * <li>radial - radially, with the root at the center.</ul>
  11882. *
  11883. * @type string
  11884. * @name pv.Layout.Tree.prototype.orient
  11885. */
  11886. /**
  11887. * The sibling grouping, i.e., whether differentiating space is placed between
  11888. * sibling groups. The default is 1 (or true), causing sibling leaves to be
  11889. * separated by one breadth offset. Setting this to false (or 0) causes
  11890. * non-siblings to be adjacent.
  11891. *
  11892. * @type number
  11893. * @name pv.Layout.Tree.prototype.group
  11894. */
  11895. /**
  11896. * Constructs a new, empty indent layout. Layouts are not typically constructed
  11897. * directly; instead, they are added to an existing panel via
  11898. * {@link pv.Mark#add}.
  11899. *
  11900. * @class Implements a hierarchical layout using the indent algorithm. This
  11901. * layout implements a node-link diagram where the nodes are presented in
  11902. * preorder traversal, and nodes are indented based on their depth from the
  11903. * root. This technique is used ubiquitously by operating systems to represent
  11904. * file directories; although it requires much vertical space, indented trees
  11905. * allow efficient <i>interactive</i> exploration of trees to find a specific
  11906. * node. In addition they allow rapid scanning of node labels, and multivariate
  11907. * data such as file sizes can be displayed adjacent to the hierarchy.
  11908. *
  11909. * <p>The indent layout can be configured using the <tt>depth</tt> and
  11910. * <tt>breadth</tt> properties, which control the increments in pixel space for
  11911. * each indent and row in the layout. This layout does not support multiple
  11912. * orientations; the root node is rendered in the top-left, while
  11913. * <tt>breadth</tt> is a vertical offset from the top, and <tt>depth</tt> is a
  11914. * horizontal offset from the left.
  11915. *
  11916. * <p>For more details on how to use this layout, see
  11917. * {@link pv.Layout.Hierarchy}.
  11918. *
  11919. * @extends pv.Layout.Hierarchy
  11920. */
  11921. pv.Layout.Indent = function() {
  11922. pv.Layout.Hierarchy.call(this);
  11923. this.link.interpolate("step-after");
  11924. };
  11925. pv.Layout.Indent.prototype = pv.extend(pv.Layout.Hierarchy)
  11926. .property("depth", Number)
  11927. .property("breadth", Number);
  11928. /**
  11929. * The horizontal offset between different levels of the tree; defaults to 15.
  11930. *
  11931. * @type number
  11932. * @name pv.Layout.Indent.prototype.depth
  11933. */
  11934. /**
  11935. * The vertical offset between nodes; defaults to 15.
  11936. *
  11937. * @type number
  11938. * @name pv.Layout.Indent.prototype.breadth
  11939. */
  11940. /**
  11941. * Default properties for indent layouts. By default the depth and breadth
  11942. * offsets are 15 pixels.
  11943. *
  11944. * @type pv.Layout.Indent
  11945. */
  11946. pv.Layout.Indent.prototype.defaults = new pv.Layout.Indent()
  11947. .extend(pv.Layout.Hierarchy.prototype.defaults)
  11948. .depth(15)
  11949. .breadth(15);
  11950. /** @private */
  11951. pv.Layout.Indent.prototype.buildImplied = function(s) {
  11952. if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) return;
  11953. var nodes = s.nodes,
  11954. bspace = s.breadth,
  11955. dspace = s.depth,
  11956. ax = 0,
  11957. ay = 0;
  11958. /** @private */
  11959. function position(n, breadth, depth) {
  11960. n.x = ax + depth++ * dspace;
  11961. n.y = ay + breadth++ * bspace;
  11962. n.midAngle = 0;
  11963. for (var c = n.firstChild; c; c = c.nextSibling) {
  11964. breadth = position(c, breadth, depth);
  11965. }
  11966. return breadth;
  11967. }
  11968. position(nodes[0], 1, 1);
  11969. };
  11970. /**
  11971. * Constructs a new, empty circle-packing layout. Layouts are not typically
  11972. * constructed directly; instead, they are added to an existing panel via
  11973. * {@link pv.Mark#add}.
  11974. *
  11975. * @class Implements a hierarchical layout using circle-packing. The meaning of
  11976. * the exported mark prototypes changes slightly in the space-filling
  11977. * implementation:<ul>
  11978. *
  11979. * <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Dot}.
  11980. *
  11981. * <p><li><tt>link</tt> - unsupported; undefined. Links are encoded implicitly
  11982. * in the arrangement of the space-filling nodes.
  11983. *
  11984. * <p><li><tt>label</tt> - for rendering node labels; typically a
  11985. * {@link pv.Label}.
  11986. *
  11987. * </ul>The pack layout support dynamic sizing for leaf nodes, if a
  11988. * {@link #size} psuedo-property is specified. The default size function returns
  11989. * 1, causing all leaf nodes to be sized equally, and all internal nodes to be
  11990. * sized by the number of leaf nodes they have as descendants.
  11991. *
  11992. * <p>The size function can be used in conjunction with the order property,
  11993. * which allows the nodes to the sorted by the computed size. Note: for sorting
  11994. * based on other data attributes, simply use the default <tt>null</tt> for the
  11995. * order property, and sort the nodes beforehand using the {@link pv.Dom}
  11996. * operator.
  11997. *
  11998. * <p>For more details on how to use this layout, see
  11999. * {@link pv.Layout.Hierarchy}.
  12000. *
  12001. * @extends pv.Layout.Hierarchy
  12002. * @see <a href="http://portal.acm.org/citation.cfm?id=1124772.1124851"
  12003. * >"Visualization of large hierarchical data by circle packing"</a> by W. Wang,
  12004. * H. Wang, G. Dai, and H. Wang, ACM CHI 2006.
  12005. */
  12006. pv.Layout.Pack = function() {
  12007. pv.Layout.Hierarchy.call(this);
  12008. this.node
  12009. .radius(function(n) { return n.radius; })
  12010. .strokeStyle("rgb(31, 119, 180)")
  12011. .fillStyle("rgba(31, 119, 180, .25)");
  12012. this.label
  12013. .textAlign("center");
  12014. /* Hide unsupported link. */
  12015. delete this.link;
  12016. };
  12017. pv.Layout.Pack.prototype = pv.extend(pv.Layout.Hierarchy)
  12018. .property("spacing", Number)
  12019. .property("order", String); // ascending, descending, reverse, null
  12020. /**
  12021. * Default properties for circle-packing layouts. The default spacing parameter
  12022. * is 1 and the default order is "ascending".
  12023. *
  12024. * @type pv.Layout.Pack
  12025. */
  12026. pv.Layout.Pack.prototype.defaults = new pv.Layout.Pack()
  12027. .extend(pv.Layout.Hierarchy.prototype.defaults)
  12028. .spacing(1)
  12029. .order("ascending");
  12030. /**
  12031. * The spacing parameter; defaults to 1, which provides a little bit of padding
  12032. * between sibling nodes and the enclosing circle. Larger values increase the
  12033. * spacing, by making the sibling nodes smaller; a value of zero makes the leaf
  12034. * nodes as large as possible, with no padding on enclosing circles.
  12035. *
  12036. * @type number
  12037. * @name pv.Layout.Pack.prototype.spacing
  12038. */
  12039. /**
  12040. * The sibling node order. The default order is <tt>null</tt>, which means to
  12041. * use the sibling order specified by the nodes property as-is. A value of
  12042. * "ascending" will sort siblings in ascending order of size, while "descending"
  12043. * will do the reverse. For sorting based on data attributes other than size,
  12044. * use the default <tt>null</tt> for the order property, and sort the nodes
  12045. * beforehand using the {@link pv.Dom} operator.
  12046. *
  12047. * @see pv.Dom.Node#sort
  12048. * @type string
  12049. * @name pv.Layout.Pack.prototype.order
  12050. */
  12051. /** @private The default size function. */
  12052. pv.Layout.Pack.prototype.$radius = function() { return 1; };
  12053. // TODO is it possible for spacing to operate in pixel space?
  12054. // Right now it appears to be multiples of the smallest radius.
  12055. /**
  12056. * Specifies the sizing function. By default, a sizing function is disabled and
  12057. * all nodes are given constant size. The sizing function is invoked for each
  12058. * leaf node in the tree (passed to the constructor).
  12059. *
  12060. * <p>For example, if the tree data structure represents a file system, with
  12061. * files as leaf nodes, and each file has a <tt>bytes</tt> attribute, you can
  12062. * specify a size function as:
  12063. *
  12064. * <pre> .size(function(d) d.bytes)</pre>
  12065. *
  12066. * As with other properties, a size function may specify additional arguments to
  12067. * access the data associated with the layout and any enclosing panels.
  12068. *
  12069. * @param {function} f the new sizing function.
  12070. * @returns {pv.Layout.Pack} this.
  12071. */
  12072. pv.Layout.Pack.prototype.size = function(f) {
  12073. this.$radius = typeof f == "function"
  12074. ? function() { return Math.sqrt(f.apply(this, arguments)); }
  12075. : (f = Math.sqrt(f), function() { return f; });
  12076. return this;
  12077. };
  12078. /** @private */
  12079. pv.Layout.Pack.prototype.buildImplied = function(s) {
  12080. if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) return;
  12081. var that = this,
  12082. nodes = s.nodes,
  12083. root = nodes[0];
  12084. /** @private Compute the radii of the leaf nodes. */
  12085. function radii(nodes) {
  12086. var stack = pv.Mark.stack;
  12087. stack.unshift(null);
  12088. for (var i = 0, n = nodes.length; i < n; i++) {
  12089. var c = nodes[i];
  12090. if (!c.firstChild) {
  12091. c.radius = that.$radius.apply(that, (stack[0] = c, stack));
  12092. }
  12093. }
  12094. stack.shift();
  12095. }
  12096. /** @private */
  12097. function packTree(n) {
  12098. var nodes = [];
  12099. for (var c = n.firstChild; c; c = c.nextSibling) {
  12100. if (c.firstChild) c.radius = packTree(c);
  12101. c.n = c.p = c;
  12102. nodes.push(c);
  12103. }
  12104. /* Sort. */
  12105. switch (s.order) {
  12106. case "ascending": {
  12107. nodes.sort(function(a, b) { return a.radius - b.radius; });
  12108. break;
  12109. }
  12110. case "descending": {
  12111. nodes.sort(function(a, b) { return b.radius - a.radius; });
  12112. break;
  12113. }
  12114. case "reverse": nodes.reverse(); break;
  12115. }
  12116. return packCircle(nodes);
  12117. }
  12118. /** @private */
  12119. function packCircle(nodes) {
  12120. var xMin = Infinity,
  12121. xMax = -Infinity,
  12122. yMin = Infinity,
  12123. yMax = -Infinity,
  12124. a, b, c, j, k;
  12125. /** @private */
  12126. function bound(n) {
  12127. xMin = Math.min(n.x - n.radius, xMin);
  12128. xMax = Math.max(n.x + n.radius, xMax);
  12129. yMin = Math.min(n.y - n.radius, yMin);
  12130. yMax = Math.max(n.y + n.radius, yMax);
  12131. }
  12132. /** @private */
  12133. function insert(a, b) {
  12134. var c = a.n;
  12135. a.n = b;
  12136. b.p = a;
  12137. b.n = c;
  12138. c.p = b;
  12139. }
  12140. /** @private */
  12141. function splice(a, b) {
  12142. a.n = b;
  12143. b.p = a;
  12144. }
  12145. /** @private */
  12146. function intersects(a, b) {
  12147. var dx = b.x - a.x,
  12148. dy = b.y - a.y,
  12149. dr = a.radius + b.radius;
  12150. return (dr * dr - dx * dx - dy * dy) > .001; // within epsilon
  12151. }
  12152. /* Create first node. */
  12153. a = nodes[0];
  12154. a.x = -a.radius;
  12155. a.y = 0;
  12156. bound(a);
  12157. /* Create second node. */
  12158. if (nodes.length > 1) {
  12159. b = nodes[1];
  12160. b.x = b.radius;
  12161. b.y = 0;
  12162. bound(b);
  12163. /* Create third node and build chain. */
  12164. if (nodes.length > 2) {
  12165. c = nodes[2];
  12166. place(a, b, c);
  12167. bound(c);
  12168. insert(a, c);
  12169. a.p = c;
  12170. insert(c, b);
  12171. b = a.n;
  12172. /* Now iterate through the rest. */
  12173. for (var i = 3; i < nodes.length; i++) {
  12174. place(a, b, c = nodes[i]);
  12175. /* Search for the closest intersection. */
  12176. var isect = 0, s1 = 1, s2 = 1;
  12177. for (j = b.n; j != b; j = j.n, s1++) {
  12178. if (intersects(j, c)) {
  12179. isect = 1;
  12180. break;
  12181. }
  12182. }
  12183. if (isect == 1) {
  12184. for (k = a.p; k != j.p; k = k.p, s2++) {
  12185. if (intersects(k, c)) {
  12186. if (s2 < s1) {
  12187. isect = -1;
  12188. j = k;
  12189. }
  12190. break;
  12191. }
  12192. }
  12193. }
  12194. /* Update node chain. */
  12195. if (isect == 0) {
  12196. insert(a, c);
  12197. b = c;
  12198. bound(c);
  12199. } else if (isect > 0) {
  12200. splice(a, j);
  12201. b = j;
  12202. i--;
  12203. } else if (isect < 0) {
  12204. splice(j, b);
  12205. a = j;
  12206. i--;
  12207. }
  12208. }
  12209. }
  12210. }
  12211. /* Re-center the circles and return the encompassing radius. */
  12212. var cx = (xMin + xMax) / 2,
  12213. cy = (yMin + yMax) / 2,
  12214. cr = 0;
  12215. for (var i = 0; i < nodes.length; i++) {
  12216. var n = nodes[i];
  12217. n.x -= cx;
  12218. n.y -= cy;
  12219. cr = Math.max(cr, n.radius + Math.sqrt(n.x * n.x + n.y * n.y));
  12220. }
  12221. return cr + s.spacing;
  12222. }
  12223. /** @private */
  12224. function place(a, b, c) {
  12225. var da = b.radius + c.radius,
  12226. db = a.radius + c.radius,
  12227. dx = b.x - a.x,
  12228. dy = b.y - a.y,
  12229. dc = Math.sqrt(dx * dx + dy * dy),
  12230. cos = (db * db + dc * dc - da * da) / (2 * db * dc),
  12231. theta = Math.acos(cos),
  12232. x = cos * db,
  12233. h = Math.sin(theta) * db;
  12234. dx /= dc;
  12235. dy /= dc;
  12236. c.x = a.x + x * dx + h * dy;
  12237. c.y = a.y + x * dy - h * dx;
  12238. }
  12239. /** @private */
  12240. function transform(n, x, y, k) {
  12241. for (var c = n.firstChild; c; c = c.nextSibling) {
  12242. c.x += n.x;
  12243. c.y += n.y;
  12244. transform(c, x, y, k);
  12245. }
  12246. n.x = x + k * n.x;
  12247. n.y = y + k * n.y;
  12248. n.radius *= k;
  12249. }
  12250. radii(nodes);
  12251. /* Recursively compute the layout. */
  12252. root.x = 0;
  12253. root.y = 0;
  12254. root.radius = packTree(root);
  12255. var w = this.width(),
  12256. h = this.height(),
  12257. k = 1 / Math.max(2 * root.radius / w, 2 * root.radius / h);
  12258. transform(root, w / 2, h / 2, k);
  12259. };
  12260. /**
  12261. * Constructs a new, empty force-directed layout. Layouts are not typically
  12262. * constructed directly; instead, they are added to an existing panel via
  12263. * {@link pv.Mark#add}.
  12264. *
  12265. * @class Implements force-directed network layout as a node-link diagram. This
  12266. * layout uses the Fruchterman-Reingold algorithm, which applies an attractive
  12267. * spring force between neighboring nodes, and a repulsive electrical charge
  12268. * force between all nodes. An additional drag force improves stability of the
  12269. * simulation. See {@link pv.Force.spring}, {@link pv.Force.drag} and {@link
  12270. * pv.Force.charge} for more details; note that the n-body charge force is
  12271. * approximated using the Barnes-Hut algorithm.
  12272. *
  12273. * <p>This layout is implemented on top of {@link pv.Simulation}, which can be
  12274. * used directly for more control over simulation parameters. The simulation
  12275. * uses Position Verlet integration, which does not compute velocities
  12276. * explicitly, but allows for easy geometric constraints, such as bounding the
  12277. * nodes within the layout panel. Many of the configuration properties supported
  12278. * by this layout are simply passed through to the underlying forces and
  12279. * constraints of the simulation.
  12280. *
  12281. * <p>Force layouts are typically interactive. The gradual movement of the nodes
  12282. * as they stabilize to a local stress minimum can help reveal the structure of
  12283. * the network, as can {@link pv.Behavior.drag}, which allows the user to pick
  12284. * up nodes and reposition them while the physics simulation continues. This
  12285. * layout can also be used with pan &amp; zoom behaviors for interaction.
  12286. *
  12287. * <p>To facilitate interaction, this layout by default automatically re-renders
  12288. * using a <tt>setInterval</tt> every 42 milliseconds. This can be disabled via
  12289. * the <tt>iterations</tt> property, which if non-null specifies the number of
  12290. * simulation iterations to run before the force-directed layout is finalized.
  12291. * Be careful not to use too high an iteration count, as this can lead to an
  12292. * annoying delay on page load.
  12293. *
  12294. * <p>As with other network layouts, the network data can be updated
  12295. * dynamically, provided the property cache is reset. See
  12296. * {@link pv.Layout.Network} for details. New nodes are initialized with random
  12297. * positions near the center. Alternatively, positions can be specified manually
  12298. * by setting the <tt>x</tt> and <tt>y</tt> attributes on nodes.
  12299. *
  12300. * @extends pv.Layout.Network
  12301. * @see <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.13.8444&rep=rep1&type=pdf"
  12302. * >"Graph Drawing by Force-directed Placement"</a> by T. Fruchterman &amp;
  12303. * E. Reingold, Software--Practice &amp; Experience, November 1991.
  12304. */
  12305. pv.Layout.Force = function() {
  12306. pv.Layout.Network.call(this);
  12307. /* Force-directed graphs can be messy, so reduce the link width. */
  12308. this.link.lineWidth(function(d, p) { return Math.sqrt(p.linkValue) * 1.5; });
  12309. this.label.textAlign("center");
  12310. };
  12311. pv.Layout.Force.prototype = pv.extend(pv.Layout.Network)
  12312. .property("bound", Boolean)
  12313. .property("iterations", Number)
  12314. .property("dragConstant", Number)
  12315. .property("chargeConstant", Number)
  12316. .property("chargeMinDistance", Number)
  12317. .property("chargeMaxDistance", Number)
  12318. .property("chargeTheta", Number)
  12319. .property("springConstant", Number)
  12320. .property("springDamping", Number)
  12321. .property("springLength", Number);
  12322. /**
  12323. * The bound parameter; true if nodes should be constrained within the layout
  12324. * panel. Bounding is disabled by default. Currently the layout does not observe
  12325. * the radius of the nodes; strictly speaking, only the center of the node is
  12326. * constrained to be within the panel, with an additional 6-pixel offset for
  12327. * padding. A future enhancement could extend the bound constraint to observe
  12328. * the node's radius, which would also support bounding for variable-size nodes.
  12329. *
  12330. * <p>Note that if this layout is used in conjunction with pan &amp; zoom
  12331. * behaviors, those behaviors should have their bound parameter set to the same
  12332. * value.
  12333. *
  12334. * @type boolean
  12335. * @name pv.Layout.Force.prototype.bound
  12336. */
  12337. /**
  12338. * The number of simulation iterations to run, or null if this layout is
  12339. * interactive. Force-directed layouts are interactive by default, using a
  12340. * <tt>setInterval</tt> to advance the physics simulation and re-render
  12341. * automatically.
  12342. *
  12343. * @type number
  12344. * @name pv.Layout.Force.prototype.iterations
  12345. */
  12346. /**
  12347. * The drag constant, in the range [0,1]. A value of 0 means no drag (a
  12348. * perfectly frictionless environment), while a value of 1 means friction
  12349. * immediately cancels all momentum. The default value is 0.1, which provides a
  12350. * minimum amount of drag that helps stabilize bouncy springs; lower values may
  12351. * result in excessive bounciness, while higher values cause the simulation to
  12352. * take longer to converge.
  12353. *
  12354. * @type number
  12355. * @name pv.Layout.Force.prototype.dragConstant
  12356. * @see pv.Force.drag#constant
  12357. */
  12358. /**
  12359. * The charge constant, which should be a negative number. The default value is
  12360. * -40; more negative values will result in a stronger repulsive force, which
  12361. * may lead to faster convergence at the risk of instability. Too strong
  12362. * repulsive charge forces can cause comparatively weak springs to be stretched
  12363. * well beyond their rest length, emphasizing global structure over local
  12364. * structure. A nonnegative value will break the Fruchterman-Reingold algorithm,
  12365. * and is for entertainment purposes only.
  12366. *
  12367. * @type number
  12368. * @name pv.Layout.Force.prototype.chargeConstant
  12369. * @see pv.Force.charge#constant
  12370. */
  12371. /**
  12372. * The minimum distance at which charge forces are applied. The default minimum
  12373. * distance of 2 avoids applying forces that are two strong; because the physics
  12374. * simulation is run at discrete time intervals, it is possible for two same-
  12375. * charged particles to become very close or even a singularity! Since the
  12376. * charge force is inversely proportional to the square of the distance, very
  12377. * small distances can break the simulation.
  12378. *
  12379. * <p>In rare cases, two particles can become stuck on top of each other, as a
  12380. * minimum distance threshold will prevent the charge force from repelling them.
  12381. * However, this occurs very rarely because other forces and momentum typically
  12382. * cause the particles to become separated again, at which point the repulsive
  12383. * charge force kicks in.
  12384. *
  12385. * @type number
  12386. * @name pv.Layout.Force.prototype.chargeMinDistance
  12387. * @see pv.Force.charge#domain
  12388. */
  12389. /**
  12390. * The maximum distance at which charge forces are applied. This improves
  12391. * performance by ignoring weak charge forces at great distances. Note that this
  12392. * parameter is partly redundant, as the Barnes-Hut algorithm for n-body forces
  12393. * already improves performance for far-away particles through approximation.
  12394. *
  12395. * @type number
  12396. * @name pv.Layout.Force.prototype.chargeMaxDistance
  12397. * @see pv.Force.charge#domain
  12398. */
  12399. /**
  12400. * The Barnes-Hut approximation factor. The Barnes-Hut approximation criterion
  12401. * is the ratio of the size of the quadtree node to the distance from the point
  12402. * to the node's center of mass is beneath some threshold. The default value is
  12403. * 0.9.
  12404. *
  12405. * @type number
  12406. * @name pv.Layout.Force.prototype.chargeTheta
  12407. * @see pv.Force.charge#theta
  12408. */
  12409. /**
  12410. * The spring constant, which should be a positive number. The default value is
  12411. * 0.1; greater values will result in a stronger attractive force, which may
  12412. * lead to faster convergence at the risk of instability. Too strong spring
  12413. * forces can cause comparatively weak charge forces to be ignored, emphasizing
  12414. * local structure over global structure. A nonpositive value will break the
  12415. * Fruchterman-Reingold algorithm, and is for entertainment purposes only.
  12416. *
  12417. * <p>The spring tension is automatically normalized using the inverse square
  12418. * root of the maximum link degree of attached nodes.
  12419. *
  12420. * @type number
  12421. * @name pv.Layout.Force.prototype.springConstant
  12422. * @see pv.Force.spring#constant
  12423. */
  12424. /**
  12425. * The spring damping factor, in the range [0,1]. Damping functions identically
  12426. * to drag forces, damping spring bounciness by applying a force in the opposite
  12427. * direction of attached nodes' velocities. The default value is 0.3.
  12428. *
  12429. * <p>The spring damping is automatically normalized using the inverse square
  12430. * root of the maximum link degree of attached nodes.
  12431. *
  12432. * @type number
  12433. * @name pv.Layout.Force.prototype.springDamping
  12434. * @see pv.Force.spring#damping
  12435. */
  12436. /**
  12437. * The spring rest length. The default value is 20 pixels. Larger values may be
  12438. * appropriate if the layout panel is larger, or if the nodes are rendered
  12439. * larger than the default dot size of 20.
  12440. *
  12441. * @type number
  12442. * @name pv.Layout.Force.prototype.springLength
  12443. * @see pv.Force.spring#length
  12444. */
  12445. /**
  12446. * Default properties for force-directed layouts. The default drag constant is
  12447. * 0.1, the default charge constant is -40 (with a domain of [2, 500] and theta
  12448. * of 0.9), and the default spring constant is 0.1 (with a damping of 0.3 and a
  12449. * rest length of 20).
  12450. *
  12451. * @type pv.Layout.Force
  12452. */
  12453. pv.Layout.Force.prototype.defaults = new pv.Layout.Force()
  12454. .extend(pv.Layout.Network.prototype.defaults)
  12455. .dragConstant(.1)
  12456. .chargeConstant(-40)
  12457. .chargeMinDistance(2)
  12458. .chargeMaxDistance(500)
  12459. .chargeTheta(.9)
  12460. .springConstant(.1)
  12461. .springDamping(.3)
  12462. .springLength(20);
  12463. /** @private Initialize the physics simulation. */
  12464. pv.Layout.Force.prototype.buildImplied = function(s) {
  12465. /* Any cached interactive layouts need to be rebound for the timer. */
  12466. if (pv.Layout.Network.prototype.buildImplied.call(this, s)) {
  12467. var f = s.$force;
  12468. if (f) {
  12469. f.next = this.binds.$force;
  12470. this.binds.$force = f;
  12471. }
  12472. return;
  12473. }
  12474. var that = this,
  12475. nodes = s.nodes,
  12476. links = s.links,
  12477. k = s.iterations,
  12478. w = s.width,
  12479. h = s.height;
  12480. /* Initialize positions randomly near the center. */
  12481. for (var i = 0, n; i < nodes.length; i++) {
  12482. n = nodes[i];
  12483. if (isNaN(n.x)) n.x = w / 2 + 40 * Math.random() - 20;
  12484. if (isNaN(n.y)) n.y = h / 2 + 40 * Math.random() - 20;
  12485. }
  12486. /* Initialize the simulation. */
  12487. var sim = pv.simulation(nodes);
  12488. /* Drag force. */
  12489. sim.force(pv.Force.drag(s.dragConstant));
  12490. /* Charge (repelling) force. */
  12491. sim.force(pv.Force.charge(s.chargeConstant)
  12492. .domain(s.chargeMinDistance, s.chargeMaxDistance)
  12493. .theta(s.chargeTheta));
  12494. /* Spring (attracting) force. */
  12495. sim.force(pv.Force.spring(s.springConstant)
  12496. .damping(s.springDamping)
  12497. .length(s.springLength)
  12498. .links(links));
  12499. /* Position constraint (for interactive dragging). */
  12500. sim.constraint(pv.Constraint.position());
  12501. /* Optionally add bound constraint. TODO: better padding. */
  12502. if (s.bound) {
  12503. sim.constraint(pv.Constraint.bound().x(6, w - 6).y(6, h - 6));
  12504. }
  12505. /** @private Returns the speed of the given node, to determine cooling. */
  12506. function speed(n) {
  12507. return n.fix ? 1 : n.vx * n.vx + n.vy * n.vy;
  12508. }
  12509. /*
  12510. * If the iterations property is null (the default), the layout is
  12511. * interactive. The simulation is run until the fastest particle drops below
  12512. * an arbitrary minimum speed. Although the timer keeps firing, this speed
  12513. * calculation is fast so there is minimal CPU overhead. Note: if a particle
  12514. * is fixed for interactivity, treat this as a high speed and resume
  12515. * simulation.
  12516. */
  12517. if (k == null) {
  12518. sim.step(); // compute initial previous velocities
  12519. sim.step(); // compute initial velocities
  12520. /* Add the simulation state to the bound list. */
  12521. var force = s.$force = this.binds.$force = {
  12522. next: this.binds.$force,
  12523. nodes: nodes,
  12524. min: 1e-4 * (links.length + 1),
  12525. sim: sim
  12526. };
  12527. /* Start the timer, if not already started. */
  12528. if (!this.$timer) this.$timer = setInterval(function() {
  12529. var render = false;
  12530. for (var f = that.binds.$force; f; f = f.next) {
  12531. if (pv.max(f.nodes, speed) > f.min) {
  12532. f.sim.step();
  12533. render = true;
  12534. }
  12535. }
  12536. if (render) that.render();
  12537. }, 42);
  12538. } else for (var i = 0; i < k; i++) {
  12539. sim.step();
  12540. }
  12541. };
  12542. /**
  12543. * Constructs a new, empty cluster layout. Layouts are not typically
  12544. * constructed directly; instead, they are added to an existing panel via
  12545. * {@link pv.Mark#add}.
  12546. *
  12547. * @class Implements a hierarchical layout using the cluster (or dendrogram)
  12548. * algorithm. This layout provides both node-link and space-filling
  12549. * implementations of cluster diagrams. In many ways it is similar to
  12550. * {@link pv.Layout.Partition}, except that leaf nodes are positioned at maximum
  12551. * depth, and the depth of internal nodes is based on their distance from their
  12552. * deepest descendant, rather than their distance from the root.
  12553. *
  12554. * <p>The cluster layout supports a "group" property, which if true causes
  12555. * siblings to be positioned closer together than unrelated nodes at the same
  12556. * depth. Unlike the partition layout, this layout does not support dynamic
  12557. * sizing for leaf nodes; all leaf nodes are the same size.
  12558. *
  12559. * <p>For more details on how to use this layout, see
  12560. * {@link pv.Layout.Hierarchy}.
  12561. *
  12562. * @see pv.Layout.Cluster.Fill
  12563. * @extends pv.Layout.Hierarchy
  12564. */
  12565. pv.Layout.Cluster = function() {
  12566. pv.Layout.Hierarchy.call(this);
  12567. var interpolate, // cached interpolate
  12568. buildImplied = this.buildImplied;
  12569. /** @private Cache layout state to optimize properties. */
  12570. this.buildImplied = function(s) {
  12571. buildImplied.call(this, s);
  12572. interpolate
  12573. = /^(top|bottom)$/.test(s.orient) ? "step-before"
  12574. : /^(left|right)$/.test(s.orient) ? "step-after"
  12575. : "linear";
  12576. };
  12577. this.link.interpolate(function() { return interpolate; });
  12578. };
  12579. pv.Layout.Cluster.prototype = pv.extend(pv.Layout.Hierarchy)
  12580. .property("group", Number)
  12581. .property("orient", String)
  12582. .property("innerRadius", Number)
  12583. .property("outerRadius", Number);
  12584. /**
  12585. * The group parameter; defaults to 0, disabling grouping of siblings. If this
  12586. * parameter is set to a positive number (or true, which is equivalent to 1),
  12587. * then additional space will be allotted between sibling groups. In other
  12588. * words, siblings (nodes that share the same parent) will be positioned more
  12589. * closely than nodes at the same depth that do not share a parent.
  12590. *
  12591. * @type number
  12592. * @name pv.Layout.Cluster.prototype.group
  12593. */
  12594. /**
  12595. * The orientation. The default orientation is "top", which means that the root
  12596. * node is placed on the top edge, leaf nodes appear on the bottom edge, and
  12597. * internal nodes are in-between. The following orientations are supported:<ul>
  12598. *
  12599. * <li>left - left-to-right.
  12600. * <li>right - right-to-left.
  12601. * <li>top - top-to-bottom.
  12602. * <li>bottom - bottom-to-top.
  12603. * <li>radial - radially, with the root at the center.</ul>
  12604. *
  12605. * @type string
  12606. * @name pv.Layout.Cluster.prototype.orient
  12607. */
  12608. /**
  12609. * The inner radius; defaults to 0. This property applies only to radial
  12610. * orientations, and can be used to compress the layout radially. Note that for
  12611. * the node-link implementation, the root node is always at the center,
  12612. * regardless of the value of this property; this property only affects internal
  12613. * and leaf nodes. For the space-filling implementation, a non-zero value of
  12614. * this property will result in the root node represented as a ring rather than
  12615. * a circle.
  12616. *
  12617. * @type number
  12618. * @name pv.Layout.Cluster.prototype.innerRadius
  12619. */
  12620. /**
  12621. * The outer radius; defaults to fill the containing panel, based on the height
  12622. * and width of the layout. If the layout has no height and width specified, it
  12623. * will extend to fill the enclosing panel.
  12624. *
  12625. * @type number
  12626. * @name pv.Layout.Cluster.prototype.outerRadius
  12627. */
  12628. /**
  12629. * Defaults for cluster layouts. The default group parameter is 0 and the
  12630. * default orientation is "top".
  12631. *
  12632. * @type pv.Layout.Cluster
  12633. */
  12634. pv.Layout.Cluster.prototype.defaults = new pv.Layout.Cluster()
  12635. .extend(pv.Layout.Hierarchy.prototype.defaults)
  12636. .group(0)
  12637. .orient("top");
  12638. /** @private */
  12639. pv.Layout.Cluster.prototype.buildImplied = function(s) {
  12640. if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) return;
  12641. var root = s.nodes[0],
  12642. group = s.group,
  12643. breadth,
  12644. depth,
  12645. leafCount = 0,
  12646. leafIndex = .5 - group / 2;
  12647. /* Count the leaf nodes and compute the depth of descendants. */
  12648. var p = undefined;
  12649. root.visitAfter(function(n) {
  12650. if (n.firstChild) {
  12651. n.depth = 1 + pv.max(n.childNodes, function(n) { return n.depth; });
  12652. } else {
  12653. if (group && (p != n.parentNode)) {
  12654. p = n.parentNode;
  12655. leafCount += group;
  12656. }
  12657. leafCount++;
  12658. n.depth = 0;
  12659. }
  12660. });
  12661. breadth = 1 / leafCount;
  12662. depth = 1 / root.depth;
  12663. /* Compute the unit breadth and depth of each node. */
  12664. var p = undefined;
  12665. root.visitAfter(function(n) {
  12666. if (n.firstChild) {
  12667. n.breadth = pv.mean(n.childNodes, function(n) { return n.breadth; });
  12668. } else {
  12669. if (group && (p != n.parentNode)) {
  12670. p = n.parentNode;
  12671. leafIndex += group;
  12672. }
  12673. n.breadth = breadth * leafIndex++;
  12674. }
  12675. n.depth = 1 - n.depth * depth;
  12676. });
  12677. /* Compute breadth and depth ranges for space-filling layouts. */
  12678. root.visitAfter(function(n) {
  12679. n.minBreadth = n.firstChild
  12680. ? n.firstChild.minBreadth
  12681. : (n.breadth - breadth / 2);
  12682. n.maxBreadth = n.firstChild
  12683. ? n.lastChild.maxBreadth
  12684. : (n.breadth + breadth / 2);
  12685. });
  12686. root.visitBefore(function(n) {
  12687. n.minDepth = n.parentNode
  12688. ? n.parentNode.maxDepth
  12689. : 0;
  12690. n.maxDepth = n.parentNode
  12691. ? (n.depth + root.depth)
  12692. : (n.minDepth + 2 * root.depth);
  12693. });
  12694. root.minDepth = -depth;
  12695. pv.Layout.Hierarchy.NodeLink.buildImplied.call(this, s);
  12696. };
  12697. /**
  12698. * Constructs a new, empty space-filling cluster layout. Layouts are not
  12699. * typically constructed directly; instead, they are added to an existing panel
  12700. * via {@link pv.Mark#add}.
  12701. *
  12702. * @class A variant of cluster layout that is space-filling. The meaning of the
  12703. * exported mark prototypes changes slightly in the space-filling
  12704. * implementation:<ul>
  12705. *
  12706. * <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Bar} for
  12707. * non-radial orientations, and a {@link pv.Wedge} for radial orientations.
  12708. *
  12709. * <p><li><tt>link</tt> - unsupported; undefined. Links are encoded implicitly
  12710. * in the arrangement of the space-filling nodes.
  12711. *
  12712. * <p><li><tt>label</tt> - for rendering node labels; typically a
  12713. * {@link pv.Label}.
  12714. *
  12715. * </ul>For more details on how to use this layout, see
  12716. * {@link pv.Layout.Cluster}.
  12717. *
  12718. * @extends pv.Layout.Cluster
  12719. */
  12720. pv.Layout.Cluster.Fill = function() {
  12721. pv.Layout.Cluster.call(this);
  12722. pv.Layout.Hierarchy.Fill.constructor.call(this);
  12723. };
  12724. pv.Layout.Cluster.Fill.prototype = pv.extend(pv.Layout.Cluster);
  12725. /** @private */
  12726. pv.Layout.Cluster.Fill.prototype.buildImplied = function(s) {
  12727. if (pv.Layout.Cluster.prototype.buildImplied.call(this, s)) return;
  12728. pv.Layout.Hierarchy.Fill.buildImplied.call(this, s);
  12729. };
  12730. /**
  12731. * Constructs a new, empty partition layout. Layouts are not typically
  12732. * constructed directly; instead, they are added to an existing panel via
  12733. * {@link pv.Mark#add}.
  12734. *
  12735. * @class Implemeents a hierarchical layout using the partition (or sunburst,
  12736. * icicle) algorithm. This layout provides both node-link and space-filling
  12737. * implementations of partition diagrams. In many ways it is similar to
  12738. * {@link pv.Layout.Cluster}, except that leaf nodes are positioned based on
  12739. * their distance from the root.
  12740. *
  12741. * <p>The partition layout support dynamic sizing for leaf nodes, if a
  12742. * {@link #size} psuedo-property is specified. The default size function returns
  12743. * 1, causing all leaf nodes to be sized equally, and all internal nodes to be
  12744. * sized by the number of leaf nodes they have as descendants.
  12745. *
  12746. * <p>The size function can be used in conjunction with the order property,
  12747. * which allows the nodes to the sorted by the computed size. Note: for sorting
  12748. * based on other data attributes, simply use the default <tt>null</tt> for the
  12749. * order property, and sort the nodes beforehand using the {@link pv.Dom}
  12750. * operator.
  12751. *
  12752. * <p>For more details on how to use this layout, see
  12753. * {@link pv.Layout.Hierarchy}.
  12754. *
  12755. * @see pv.Layout.Partition.Fill
  12756. * @extends pv.Layout.Hierarchy
  12757. */
  12758. pv.Layout.Partition = function() {
  12759. pv.Layout.Hierarchy.call(this);
  12760. };
  12761. pv.Layout.Partition.prototype = pv.extend(pv.Layout.Hierarchy)
  12762. .property("order", String) // null, ascending, descending?
  12763. .property("orient", String) // top, left, right, bottom, radial
  12764. .property("innerRadius", Number)
  12765. .property("outerRadius", Number);
  12766. /**
  12767. * The sibling node order. The default order is <tt>null</tt>, which means to
  12768. * use the sibling order specified by the nodes property as-is. A value of
  12769. * "ascending" will sort siblings in ascending order of size, while "descending"
  12770. * will do the reverse. For sorting based on data attributes other than size,
  12771. * use the default <tt>null</tt> for the order property, and sort the nodes
  12772. * beforehand using the {@link pv.Dom} operator.
  12773. *
  12774. * @see pv.Dom.Node#sort
  12775. * @type string
  12776. * @name pv.Layout.Partition.prototype.order
  12777. */
  12778. /**
  12779. * The orientation. The default orientation is "top", which means that the root
  12780. * node is placed on the top edge, leaf nodes appear at the bottom, and internal
  12781. * nodes are in-between. The following orientations are supported:<ul>
  12782. *
  12783. * <li>left - left-to-right.
  12784. * <li>right - right-to-left.
  12785. * <li>top - top-to-bottom.
  12786. * <li>bottom - bottom-to-top.
  12787. * <li>radial - radially, with the root at the center.</ul>
  12788. *
  12789. * @type string
  12790. * @name pv.Layout.Partition.prototype.orient
  12791. */
  12792. /**
  12793. * The inner radius; defaults to 0. This property applies only to radial
  12794. * orientations, and can be used to compress the layout radially. Note that for
  12795. * the node-link implementation, the root node is always at the center,
  12796. * regardless of the value of this property; this property only affects internal
  12797. * and leaf nodes. For the space-filling implementation, a non-zero value of
  12798. * this property will result in the root node represented as a ring rather than
  12799. * a circle.
  12800. *
  12801. * @type number
  12802. * @name pv.Layout.Partition.prototype.innerRadius
  12803. */
  12804. /**
  12805. * The outer radius; defaults to fill the containing panel, based on the height
  12806. * and width of the layout. If the layout has no height and width specified, it
  12807. * will extend to fill the enclosing panel.
  12808. *
  12809. * @type number
  12810. * @name pv.Layout.Partition.prototype.outerRadius
  12811. */
  12812. /**
  12813. * Default properties for partition layouts. The default orientation is "top".
  12814. *
  12815. * @type pv.Layout.Partition
  12816. */
  12817. pv.Layout.Partition.prototype.defaults = new pv.Layout.Partition()
  12818. .extend(pv.Layout.Hierarchy.prototype.defaults)
  12819. .orient("top");
  12820. /** @private */
  12821. pv.Layout.Partition.prototype.$size = function() { return 1; };
  12822. /**
  12823. * Specifies the sizing function. By default, a sizing function is disabled and
  12824. * all nodes are given constant size. The sizing function is invoked for each
  12825. * leaf node in the tree (passed to the constructor).
  12826. *
  12827. * <p>For example, if the tree data structure represents a file system, with
  12828. * files as leaf nodes, and each file has a <tt>bytes</tt> attribute, you can
  12829. * specify a size function as:
  12830. *
  12831. * <pre> .size(function(d) d.bytes)</pre>
  12832. *
  12833. * As with other properties, a size function may specify additional arguments to
  12834. * access the data associated with the layout and any enclosing panels.
  12835. *
  12836. * @param {function} f the new sizing function.
  12837. * @returns {pv.Layout.Partition} this.
  12838. */
  12839. pv.Layout.Partition.prototype.size = function(f) {
  12840. this.$size = f;
  12841. return this;
  12842. };
  12843. /** @private */
  12844. pv.Layout.Partition.prototype.buildImplied = function(s) {
  12845. if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) return;
  12846. var that = this,
  12847. root = s.nodes[0],
  12848. stack = pv.Mark.stack,
  12849. maxDepth = 0;
  12850. /* Recursively compute the tree depth and node size. */
  12851. stack.unshift(null);
  12852. root.visitAfter(function(n, i) {
  12853. if (i > maxDepth) maxDepth = i;
  12854. n.size = n.firstChild
  12855. ? pv.sum(n.childNodes, function(n) { return n.size; })
  12856. : that.$size.apply(that, (stack[0] = n, stack));
  12857. });
  12858. stack.shift();
  12859. /* Order */
  12860. switch (s.order) {
  12861. case "ascending": root.sort(function(a, b) { return a.size - b.size; }); break;
  12862. case "descending": root.sort(function(b, a) { return a.size - b.size; }); break;
  12863. }
  12864. /* Compute the unit breadth and depth of each node. */
  12865. var ds = 1 / maxDepth;
  12866. root.minBreadth = 0;
  12867. root.breadth = .5;
  12868. root.maxBreadth = 1;
  12869. root.visitBefore(function(n) {
  12870. var b = n.minBreadth, s = n.maxBreadth - b;
  12871. for (var c = n.firstChild; c; c = c.nextSibling) {
  12872. c.minBreadth = b;
  12873. c.maxBreadth = b += (c.size / n.size) * s;
  12874. c.breadth = (b + c.minBreadth) / 2;
  12875. }
  12876. });
  12877. root.visitAfter(function(n, i) {
  12878. n.minDepth = (i - 1) * ds;
  12879. n.maxDepth = n.depth = i * ds;
  12880. });
  12881. pv.Layout.Hierarchy.NodeLink.buildImplied.call(this, s);
  12882. };
  12883. /**
  12884. * Constructs a new, empty space-filling partition layout. Layouts are not
  12885. * typically constructed directly; instead, they are added to an existing panel
  12886. * via {@link pv.Mark#add}.
  12887. *
  12888. * @class A variant of partition layout that is space-filling. The meaning of
  12889. * the exported mark prototypes changes slightly in the space-filling
  12890. * implementation:<ul>
  12891. *
  12892. * <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Bar} for
  12893. * non-radial orientations, and a {@link pv.Wedge} for radial orientations.
  12894. *
  12895. * <p><li><tt>link</tt> - unsupported; undefined. Links are encoded implicitly
  12896. * in the arrangement of the space-filling nodes.
  12897. *
  12898. * <p><li><tt>label</tt> - for rendering node labels; typically a
  12899. * {@link pv.Label}.
  12900. *
  12901. * </ul>For more details on how to use this layout, see
  12902. * {@link pv.Layout.Partition}.
  12903. *
  12904. * @extends pv.Layout.Partition
  12905. */
  12906. pv.Layout.Partition.Fill = function() {
  12907. pv.Layout.Partition.call(this);
  12908. pv.Layout.Hierarchy.Fill.constructor.call(this);
  12909. };
  12910. pv.Layout.Partition.Fill.prototype = pv.extend(pv.Layout.Partition);
  12911. /** @private */
  12912. pv.Layout.Partition.Fill.prototype.buildImplied = function(s) {
  12913. if (pv.Layout.Partition.prototype.buildImplied.call(this, s)) return;
  12914. pv.Layout.Hierarchy.Fill.buildImplied.call(this, s);
  12915. };
  12916. /**
  12917. * Constructs a new, empty arc layout. Layouts are not typically constructed
  12918. * directly; instead, they are added to an existing panel via
  12919. * {@link pv.Mark#add}.
  12920. *
  12921. * @class Implements a layout for arc diagrams. An arc diagram is a network
  12922. * visualization with a one-dimensional layout of nodes, using circular arcs to
  12923. * render links between nodes. For undirected networks, arcs are rendering on a
  12924. * single side; this makes arc diagrams useful as annotations to other
  12925. * two-dimensional network layouts, such as rollup, matrix or table layouts. For
  12926. * directed networks, links in opposite directions can be rendered on opposite
  12927. * sides using <tt>directed(true)</tt>.
  12928. *
  12929. * <p>Arc layouts are particularly sensitive to node ordering; for best results,
  12930. * order the nodes such that related nodes are close to each other. A poor
  12931. * (e.g., random) order may result in large arcs with crossovers that impede
  12932. * visual processing. A future improvement to this layout may include automatic
  12933. * reordering using, e.g., spectral graph layout or simulated annealing.
  12934. *
  12935. * <p>This visualization technique is related to that developed by
  12936. * M. Wattenberg, <a
  12937. * href="http://www.research.ibm.com/visual/papers/arc-diagrams.pdf">"Arc
  12938. * Diagrams: Visualizing Structure in Strings"</a> in <i>IEEE InfoVis</i>, 2002.
  12939. * However, this implementation is limited to simple node-link networks, as
  12940. * opposed to structures with hierarchical self-similarity (such as strings).
  12941. *
  12942. * <p>As with other network layouts, three mark prototypes are provided:<ul>
  12943. *
  12944. * <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Dot}.
  12945. * <li><tt>link</tt> - for rendering links; typically a {@link pv.Line}.
  12946. * <li><tt>label</tt> - for rendering node labels; typically a {@link pv.Label}.
  12947. *
  12948. * </ul>For more details on how this layout is structured and can be customized,
  12949. * see {@link pv.Layout.Network}.
  12950. *
  12951. * @extends pv.Layout.Network
  12952. **/
  12953. pv.Layout.Arc = function() {
  12954. pv.Layout.Network.call(this);
  12955. var interpolate, // cached interpolate
  12956. directed, // cached directed
  12957. reverse, // cached reverse
  12958. buildImplied = this.buildImplied;
  12959. /** @private Cache layout state to optimize properties. */
  12960. this.buildImplied = function(s) {
  12961. buildImplied.call(this, s);
  12962. directed = s.directed;
  12963. interpolate = s.orient == "radial" ? "linear" : "polar";
  12964. reverse = s.orient == "right" || s.orient == "top";
  12965. };
  12966. /* Override link properties to handle directedness and orientation. */
  12967. this.link
  12968. .data(function(p) {
  12969. var s = p.sourceNode, t = p.targetNode;
  12970. return reverse != (directed || (s.breadth < t.breadth)) ? [s, t] : [t, s];
  12971. })
  12972. .interpolate(function() { return interpolate; });
  12973. };
  12974. pv.Layout.Arc.prototype = pv.extend(pv.Layout.Network)
  12975. .property("orient", String)
  12976. .property("directed", Boolean);
  12977. /**
  12978. * Default properties for arc layouts. By default, the orientation is "bottom".
  12979. *
  12980. * @type pv.Layout.Arc
  12981. */
  12982. pv.Layout.Arc.prototype.defaults = new pv.Layout.Arc()
  12983. .extend(pv.Layout.Network.prototype.defaults)
  12984. .orient("bottom");
  12985. /**
  12986. * Specifies an optional sort function. The sort function follows the same
  12987. * comparator contract required by {@link pv.Dom.Node#sort}. Specifying a sort
  12988. * function provides an alternative to sort the nodes as they are specified by
  12989. * the <tt>nodes</tt> property; the main advantage of doing this is that the
  12990. * comparator function can access implicit fields populated by the network
  12991. * layout, such as the <tt>linkDegree</tt>.
  12992. *
  12993. * <p>Note that arc diagrams are particularly sensitive to order. This is
  12994. * referred to as the seriation problem, and many different techniques exist to
  12995. * find good node orders that emphasize clusters, such as spectral layout and
  12996. * simulated annealing.
  12997. *
  12998. * @param {function} f comparator function for nodes.
  12999. * @returns {pv.Layout.Arc} this.
  13000. */
  13001. pv.Layout.Arc.prototype.sort = function(f) {
  13002. this.$sort = f;
  13003. return this;
  13004. };
  13005. /** @private Populates the x, y and angle attributes on the nodes. */
  13006. pv.Layout.Arc.prototype.buildImplied = function(s) {
  13007. if (pv.Layout.Network.prototype.buildImplied.call(this, s)) return;
  13008. var nodes = s.nodes,
  13009. orient = s.orient,
  13010. sort = this.$sort,
  13011. index = pv.range(nodes.length),
  13012. w = s.width,
  13013. h = s.height,
  13014. r = Math.min(w, h) / 2;
  13015. /* Sort the nodes. */
  13016. if (sort) index.sort(function(a, b) { return sort(nodes[a], nodes[b]); });
  13017. /** @private Returns the mid-angle, given the breadth. */
  13018. function midAngle(b) {
  13019. switch (orient) {
  13020. case "top": return -Math.PI / 2;
  13021. case "bottom": return Math.PI / 2;
  13022. case "left": return Math.PI;
  13023. case "right": return 0;
  13024. case "radial": return (b - .25) * 2 * Math.PI;
  13025. }
  13026. }
  13027. /** @private Returns the x-position, given the breadth. */
  13028. function x(b) {
  13029. switch (orient) {
  13030. case "top":
  13031. case "bottom": return b * w;
  13032. case "left": return 0;
  13033. case "right": return w;
  13034. case "radial": return w / 2 + r * Math.cos(midAngle(b));
  13035. }
  13036. }
  13037. /** @private Returns the y-position, given the breadth. */
  13038. function y(b) {
  13039. switch (orient) {
  13040. case "top": return 0;
  13041. case "bottom": return h;
  13042. case "left":
  13043. case "right": return b * h;
  13044. case "radial": return h / 2 + r * Math.sin(midAngle(b));
  13045. }
  13046. }
  13047. /* Populate the x, y and mid-angle attributes. */
  13048. for (var i = 0; i < nodes.length; i++) {
  13049. var n = nodes[index[i]], b = n.breadth = (i + .5) / nodes.length;
  13050. n.x = x(b);
  13051. n.y = y(b);
  13052. n.midAngle = midAngle(b);
  13053. }
  13054. };
  13055. /**
  13056. * The orientation. The default orientation is "left", which means that nodes
  13057. * will be positioned from left-to-right in the order they are specified in the
  13058. * <tt>nodes</tt> property. The following orientations are supported:<ul>
  13059. *
  13060. * <li>left - left-to-right.
  13061. * <li>right - right-to-left.
  13062. * <li>top - top-to-bottom.
  13063. * <li>bottom - bottom-to-top.
  13064. * <li>radial - radially, starting at 12 o'clock and proceeding clockwise.</ul>
  13065. *
  13066. * @type string
  13067. * @name pv.Layout.Arc.prototype.orient
  13068. */
  13069. /**
  13070. * Whether this arc digram is directed (bidirectional); only applies to
  13071. * non-radial orientations. By default, arc digrams are undirected, such that
  13072. * all arcs appear on one side. If the arc digram is directed, then forward
  13073. * links are drawn on the conventional side (the same as as undirected
  13074. * links--right, left, bottom and top for left, right, top and bottom,
  13075. * respectively), while reverse links are drawn on the opposite side.
  13076. *
  13077. * @type boolean
  13078. * @name pv.Layout.Arc.prototype.directed
  13079. */
  13080. /**
  13081. * Constructs a new, empty horizon layout. Layouts are not typically constructed
  13082. * directly; instead, they are added to an existing panel via
  13083. * {@link pv.Mark#add}.
  13084. *
  13085. * @class Implements a horizon layout, which is a variation of a single-series
  13086. * area chart where the area is folded into multiple bands. Color is used to
  13087. * encode band, allowing the size of the chart to be reduced significantly
  13088. * without impeding readability. This layout algorithm is based on the work of
  13089. * J. Heer, N. Kong and M. Agrawala in <a
  13090. * href="http://hci.stanford.edu/publications/2009/heer-horizon-chi09.pdf">"Sizing
  13091. * the Horizon: The Effects of Chart Size and Layering on the Graphical
  13092. * Perception of Time Series Visualizations"</a>, CHI 2009.
  13093. *
  13094. * <p>This layout exports a single <tt>band</tt> mark prototype, which is
  13095. * intended to be used with an area mark. The band mark is contained in a panel
  13096. * which is replicated per band (and for negative/positive bands). For example,
  13097. * to create a simple horizon graph given an array of numbers:
  13098. *
  13099. * <pre>vis.add(pv.Layout.Horizon)
  13100. * .bands(n)
  13101. * .band.add(pv.Area)
  13102. * .data(data)
  13103. * .left(function() this.index * 35)
  13104. * .height(function(d) d * 40);</pre>
  13105. *
  13106. * The layout can be further customized by changing the number of bands, and
  13107. * toggling whether the negative bands are mirrored or offset. (See the
  13108. * above-referenced paper for guidance.)
  13109. *
  13110. * <p>The <tt>fillStyle</tt> of the area can be overridden, though typically it
  13111. * is easier to customize the layout's behavior through the custom
  13112. * <tt>backgroundStyle</tt>, <tt>positiveStyle</tt> and <tt>negativeStyle</tt>
  13113. * properties. By default, the background is white, positive bands are blue, and
  13114. * negative bands are red. For the most accurate presentation, use fully-opaque
  13115. * colors of equal intensity for the negative and positive bands.
  13116. *
  13117. * @extends pv.Layout
  13118. */
  13119. pv.Layout.Horizon = function() {
  13120. pv.Layout.call(this);
  13121. var that = this,
  13122. bands, // cached bands
  13123. mode, // cached mode
  13124. size, // cached height
  13125. fill, // cached background style
  13126. red, // cached negative color (ramp)
  13127. blue, // cached positive color (ramp)
  13128. buildImplied = this.buildImplied;
  13129. /** @private Cache the layout state to optimize properties. */
  13130. this.buildImplied = function(s) {
  13131. buildImplied.call(this, s);
  13132. bands = s.bands;
  13133. mode = s.mode;
  13134. size = Math.round((mode == "color" ? .5 : 1) * s.height);
  13135. fill = s.backgroundStyle;
  13136. red = pv.ramp(fill, s.negativeStyle).domain(0, bands);
  13137. blue = pv.ramp(fill, s.positiveStyle).domain(0, bands);
  13138. };
  13139. var bands = new pv.Panel()
  13140. .data(function() { return pv.range(bands * 2); })
  13141. .overflow("hidden")
  13142. .height(function() { return size; })
  13143. .top(function(i) { return mode == "color" ? (i & 1) * size : 0; })
  13144. .fillStyle(function(i) { return i ? null : fill; });
  13145. /**
  13146. * The band prototype. This prototype is intended to be used with an Area
  13147. * mark to render the horizon bands.
  13148. *
  13149. * @type pv.Mark
  13150. * @name pv.Layout.Horizon.prototype.band
  13151. */
  13152. this.band = new pv.Mark()
  13153. .top(function(d, i) {
  13154. return mode == "mirror" && i & 1
  13155. ? (i + 1 >> 1) * size
  13156. : null;
  13157. })
  13158. .bottom(function(d, i) {
  13159. return mode == "mirror"
  13160. ? (i & 1 ? null : (i + 1 >> 1) * -size)
  13161. : ((i & 1 || -1) * (i + 1 >> 1) * size);
  13162. })
  13163. .fillStyle(function(d, i) {
  13164. return (i & 1 ? red : blue)((i >> 1) + 1);
  13165. });
  13166. this.band.add = function(type) {
  13167. return that.add(pv.Panel).extend(bands).add(type).extend(this);
  13168. };
  13169. };
  13170. pv.Layout.Horizon.prototype = pv.extend(pv.Layout)
  13171. .property("bands", Number)
  13172. .property("mode", String)
  13173. .property("backgroundStyle", pv.color)
  13174. .property("positiveStyle", pv.color)
  13175. .property("negativeStyle", pv.color);
  13176. /**
  13177. * Default properties for horizon layouts. By default, there are two bands, the
  13178. * mode is "offset", the background style is "white", the positive style is
  13179. * blue, negative style is red.
  13180. *
  13181. * @type pv.Layout.Horizon
  13182. */
  13183. pv.Layout.Horizon.prototype.defaults = new pv.Layout.Horizon()
  13184. .extend(pv.Layout.prototype.defaults)
  13185. .bands(2)
  13186. .mode("offset")
  13187. .backgroundStyle("white")
  13188. .positiveStyle("#1f77b4")
  13189. .negativeStyle("#d62728");
  13190. /**
  13191. * The horizon mode: offset, mirror, or color. The default is "offset".
  13192. *
  13193. * @type string
  13194. * @name pv.Layout.Horizon.prototype.mode
  13195. */
  13196. /**
  13197. * The number of bands. Must be at least one. The default value is two.
  13198. *
  13199. * @type number
  13200. * @name pv.Layout.Horizon.prototype.bands
  13201. */
  13202. /**
  13203. * The positive band color; if non-null, the interior of positive bands are
  13204. * filled with the specified color. The default value of this property is blue.
  13205. * For accurate blending, this color should be fully opaque.
  13206. *
  13207. * @type pv.Color
  13208. * @name pv.Layout.Horizon.prototype.positiveStyle
  13209. */
  13210. /**
  13211. * The negative band color; if non-null, the interior of negative bands are
  13212. * filled with the specified color. The default value of this property is red.
  13213. * For accurate blending, this color should be fully opaque.
  13214. *
  13215. * @type pv.Color
  13216. * @name pv.Layout.Horizon.prototype.negativeStyle
  13217. */
  13218. /**
  13219. * The background color. The panel background is filled with the specified
  13220. * color, and the negative and positive bands are filled with an interpolated
  13221. * color between this color and the respective band color. The default value of
  13222. * this property is white. For accurate blending, this color should be fully
  13223. * opaque.
  13224. *
  13225. * @type pv.Color
  13226. * @name pv.Layout.Horizon.prototype.backgroundStyle
  13227. */
  13228. /**
  13229. * Constructs a new, empty rollup network layout. Layouts are not typically
  13230. * constructed directly; instead, they are added to an existing panel via
  13231. * {@link pv.Mark#add}.
  13232. *
  13233. * @class Implements a network visualization using a node-link diagram where
  13234. * nodes are rolled up along two dimensions. This implementation is based on the
  13235. * "PivotGraph" designed by Martin Wattenberg:
  13236. *
  13237. * <blockquote>The method is designed for graphs that are "multivariate", i.e.,
  13238. * where each node is associated with several attributes. Unlike visualizations
  13239. * which emphasize global graph topology, PivotGraph uses a simple grid-based
  13240. * approach to focus on the relationship between node attributes &amp;
  13241. * connections.</blockquote>
  13242. *
  13243. * This layout requires two psuedo-properties to be specified, which assign node
  13244. * positions along the two dimensions {@link #x} and {@link #y}, corresponding
  13245. * to the left and top properties, respectively. Typically, these functions are
  13246. * specified using an {@link pv.Scale.ordinal}. Nodes that share the same
  13247. * position in <i>x</i> and <i>y</i> are "rolled up" into a meta-node, and
  13248. * similarly links are aggregated between meta-nodes. For example, to construct
  13249. * a rollup to analyze links by gender and affiliation, first define two ordinal
  13250. * scales:
  13251. *
  13252. * <pre>var x = pv.Scale.ordinal(nodes, function(d) d.gender).split(0, w),
  13253. * y = pv.Scale.ordinal(nodes, function(d) d.aff).split(0, h);</pre>
  13254. *
  13255. * Next, define the position psuedo-properties:
  13256. *
  13257. * <pre> .x(function(d) x(d.gender))
  13258. * .y(function(d) y(d.aff))</pre>
  13259. *
  13260. * Linear and other quantitative scales can alternatively be used to position
  13261. * the nodes along either dimension. Note, however, that the rollup requires
  13262. * that the positions match exactly, and thus ordinal scales are recommended to
  13263. * avoid precision errors.
  13264. *
  13265. * <p>Note that because this layout provides a visualization of the rolled up
  13266. * graph, the data properties for the mark prototypes (<tt>node</tt>,
  13267. * <tt>link</tt> and <tt>label</tt>) are different from most other network
  13268. * layouts: they reference the rolled-up nodes and links, rather than the nodes
  13269. * and links of the full network. The underlying nodes and links for each
  13270. * rolled-up node and link can be accessed via the <tt>nodes</tt> and
  13271. * <tt>links</tt> attributes, respectively. The aggregated link values for
  13272. * rolled-up links can similarly be accessed via the <tt>linkValue</tt>
  13273. * attribute.
  13274. *
  13275. * <p>For undirected networks, links are duplicated in both directions. For
  13276. * directed networks, use <tt>directed(true)</tt>. The graph is assumed to be
  13277. * undirected by default.
  13278. *
  13279. * @extends pv.Layout.Network
  13280. * @see <a href="http://www.research.ibm.com/visual/papers/pivotgraph.pdf"
  13281. * >"Visual Exploration of Multivariate Graphs"</a> by M. Wattenberg, CHI 2006.
  13282. */
  13283. pv.Layout.Rollup = function() {
  13284. pv.Layout.Network.call(this);
  13285. var that = this,
  13286. nodes, // cached rollup nodes
  13287. links, // cached rollup links
  13288. buildImplied = that.buildImplied;
  13289. /** @private Cache layout state to optimize properties. */
  13290. this.buildImplied = function(s) {
  13291. buildImplied.call(this, s);
  13292. nodes = s.$rollup.nodes;
  13293. links = s.$rollup.links;
  13294. };
  13295. /* Render rollup nodes. */
  13296. this.node
  13297. .data(function() { return nodes; })
  13298. .size(function(d) { return d.nodes.length * 20; });
  13299. /* Render rollup links. */
  13300. this.link
  13301. .interpolate("polar")
  13302. .eccentricity(.8);
  13303. this.link.add = function(type) {
  13304. return that.add(pv.Panel)
  13305. .data(function() { return links; })
  13306. .add(type)
  13307. .extend(this);
  13308. };
  13309. };
  13310. pv.Layout.Rollup.prototype = pv.extend(pv.Layout.Network)
  13311. .property("directed", Boolean);
  13312. /**
  13313. * Whether the underlying network is directed. By default, the graph is assumed
  13314. * to be undirected, and links are rendered in both directions. If the network
  13315. * is directed, then forward links are drawn above the diagonal, while reverse
  13316. * links are drawn below.
  13317. *
  13318. * @type boolean
  13319. * @name pv.Layout.Rollup.prototype.directed
  13320. */
  13321. /**
  13322. * Specifies the <i>x</i>-position function used to rollup nodes. The rolled up
  13323. * nodes are positioned horizontally using the return values from the given
  13324. * function. Typically the function is specified as an ordinal scale. For
  13325. * single-dimension rollups, a constant value can be specified.
  13326. *
  13327. * @param {function} f the <i>x</i>-position function.
  13328. * @returns {pv.Layout.Rollup} this.
  13329. * @see pv.Scale.ordinal
  13330. */
  13331. pv.Layout.Rollup.prototype.x = function(f) {
  13332. this.$x = pv.functor(f);
  13333. return this;
  13334. };
  13335. /**
  13336. * Specifies the <i>y</i>-position function used to rollup nodes. The rolled up
  13337. * nodes are positioned vertically using the return values from the given
  13338. * function. Typically the function is specified as an ordinal scale. For
  13339. * single-dimension rollups, a constant value can be specified.
  13340. *
  13341. * @param {function} f the <i>y</i>-position function.
  13342. * @returns {pv.Layout.Rollup} this.
  13343. * @see pv.Scale.ordinal
  13344. */
  13345. pv.Layout.Rollup.prototype.y = function(f) {
  13346. this.$y = pv.functor(f);
  13347. return this;
  13348. };
  13349. /** @private */
  13350. pv.Layout.Rollup.prototype.buildImplied = function(s) {
  13351. if (pv.Layout.Network.prototype.buildImplied.call(this, s)) return;
  13352. var nodes = s.nodes,
  13353. links = s.links,
  13354. directed = s.directed,
  13355. n = nodes.length,
  13356. x = [],
  13357. y = [],
  13358. rnindex = 0,
  13359. rnodes = {},
  13360. rlinks = {};
  13361. /** @private */
  13362. function id(i) {
  13363. return x[i] + "," + y[i];
  13364. }
  13365. /* Iterate over the data, evaluating the x and y functions. */
  13366. var stack = pv.Mark.stack, o = {parent: this};
  13367. stack.unshift(null);
  13368. for (var i = 0; i < n; i++) {
  13369. o.index = i;
  13370. stack[0] = nodes[i];
  13371. x[i] = this.$x.apply(o, stack);
  13372. y[i] = this.$y.apply(o, stack);
  13373. }
  13374. stack.shift();
  13375. /* Compute rollup nodes. */
  13376. for (var i = 0; i < nodes.length; i++) {
  13377. var nodeId = id(i),
  13378. rn = rnodes[nodeId];
  13379. if (!rn) {
  13380. rn = rnodes[nodeId] = pv.extend(nodes[i]);
  13381. rn.index = rnindex++;
  13382. rn.x = x[i];
  13383. rn.y = y[i];
  13384. rn.nodes = [];
  13385. }
  13386. rn.nodes.push(nodes[i]);
  13387. }
  13388. /* Compute rollup links. */
  13389. for (var i = 0; i < links.length; i++) {
  13390. var source = links[i].sourceNode,
  13391. target = links[i].targetNode,
  13392. rsource = rnodes[id(source.index)],
  13393. rtarget = rnodes[id(target.index)],
  13394. reverse = !directed && rsource.index > rtarget.index,
  13395. linkId = reverse
  13396. ? rtarget.index + "," + rsource.index
  13397. : rsource.index + "," + rtarget.index,
  13398. rl = rlinks[linkId];
  13399. if (!rl) {
  13400. rl = rlinks[linkId] = {
  13401. sourceNode: rsource,
  13402. targetNode: rtarget,
  13403. linkValue: 0,
  13404. links: []
  13405. };
  13406. }
  13407. rl.links.push(links[i]);
  13408. rl.linkValue += links[i].linkValue;
  13409. }
  13410. /* Export the rolled up nodes and links to the scene. */
  13411. s.$rollup = {
  13412. nodes: pv.values(rnodes),
  13413. links: pv.values(rlinks)
  13414. };
  13415. };
  13416. /**
  13417. * Constructs a new, empty matrix network layout. Layouts are not typically
  13418. * constructed directly; instead, they are added to an existing panel via
  13419. * {@link pv.Mark#add}.
  13420. *
  13421. * @class Implements a network visualization using a matrix view. This is, in
  13422. * effect, a visualization of the graph's <i>adjacency matrix</i>: the cell at
  13423. * row <i>i</i>, column <i>j</i>, corresponds to the link from node <i>i</i> to
  13424. * node <i>j</i>. The fill color of each cell is binary by default, and
  13425. * corresponds to whether a link exists between the two nodes. If the underlying
  13426. * graph has links with variable values, the <tt>fillStyle</tt> property can be
  13427. * substited to use an appropriate color function, such as {@link pv.ramp}.
  13428. *
  13429. * <p>For undirected networks, the matrix is symmetric around the diagonal. For
  13430. * directed networks, links in opposite directions can be rendered on opposite
  13431. * sides of the diagonal using <tt>directed(true)</tt>. The graph is assumed to
  13432. * be undirected by default.
  13433. *
  13434. * <p>The mark prototypes for this network layout are slightly different than
  13435. * other implementations:<ul>
  13436. *
  13437. * <li><tt>node</tt> - unsupported; undefined. No mark is needed to visualize
  13438. * nodes directly, as the nodes are implicit in the location (rows and columns)
  13439. * of the links.
  13440. *
  13441. * <p><li><tt>link</tt> - for rendering links; typically a {@link pv.Bar}. The
  13442. * link mark is added directly to the layout, with the data property defined as
  13443. * all possible pairs of nodes. Each pair is represented as a
  13444. * {@link pv.Network.Layout.Link}, though the <tt>linkValue</tt> attribute may
  13445. * be 0 if no link exists in the graph.
  13446. *
  13447. * <p><li><tt>label</tt> - for rendering node labels; typically a
  13448. * {@link pv.Label}. The label mark is added directly to the layout, with the
  13449. * data property defined via the layout's <tt>nodes</tt> property; note,
  13450. * however, that the nodes are duplicated so as to provide a label across the
  13451. * top and down the side. Properties such as <tt>strokeStyle</tt> and
  13452. * <tt>fillStyle</tt> can be overridden to compute properties from node data
  13453. * dynamically.
  13454. *
  13455. * </ul>For more details on how to use this layout, see
  13456. * {@link pv.Layout.Network}.
  13457. *
  13458. * @extends pv.Layout.Network
  13459. */
  13460. pv.Layout.Matrix = function() {
  13461. pv.Layout.Network.call(this);
  13462. var that = this,
  13463. n, // cached matrix size
  13464. dx, // cached cell width
  13465. dy, // cached cell height
  13466. labels, // cached labels (array of strings)
  13467. pairs, // cached pairs (array of links)
  13468. buildImplied = that.buildImplied;
  13469. /** @private Cache layout state to optimize properties. */
  13470. this.buildImplied = function(s) {
  13471. buildImplied.call(this, s);
  13472. n = s.nodes.length;
  13473. dx = s.width / n;
  13474. dy = s.height / n;
  13475. labels = s.$matrix.labels;
  13476. pairs = s.$matrix.pairs;
  13477. };
  13478. /* Links are all pairs of nodes. */
  13479. this.link
  13480. .data(function() { return pairs; })
  13481. .left(function() { return dx * (this.index % n); })
  13482. .top(function() { return dy * Math.floor(this.index / n); })
  13483. .width(function() { return dx; })
  13484. .height(function() { return dy; })
  13485. .lineWidth(1.5)
  13486. .strokeStyle("#fff")
  13487. .fillStyle(function(l) { return l.linkValue ? "#555" : "#eee"; })
  13488. .parent = this;
  13489. /* No special add for links! */
  13490. delete this.link.add;
  13491. /* Labels are duplicated for top & left. */
  13492. this.label
  13493. .data(function() { return labels; })
  13494. .left(function() { return this.index & 1 ? dx * ((this.index >> 1) + .5) : null; })
  13495. .top(function() { return this.index & 1 ? null : dy * ((this.index >> 1) + .5); })
  13496. .textMargin(4)
  13497. .textAlign(function() { return this.index & 1 ? "left" : "right"; })
  13498. .textAngle(function() { return this.index & 1 ? -Math.PI / 2 : 0; });
  13499. /* The node mark is unused. */
  13500. delete this.node;
  13501. };
  13502. pv.Layout.Matrix.prototype = pv.extend(pv.Layout.Network)
  13503. .property("directed", Boolean);
  13504. /**
  13505. * Whether this matrix visualization is directed (bidirectional). By default,
  13506. * the graph is assumed to be undirected, such that the visualization is
  13507. * symmetric across the matrix diagonal. If the network is directed, then
  13508. * forward links are drawn above the diagonal, while reverse links are drawn
  13509. * below.
  13510. *
  13511. * @type boolean
  13512. * @name pv.Layout.Matrix.prototype.directed
  13513. */
  13514. /**
  13515. * Specifies an optional sort function. The sort function follows the same
  13516. * comparator contract required by {@link pv.Dom.Node#sort}. Specifying a sort
  13517. * function provides an alternative to sort the nodes as they are specified by
  13518. * the <tt>nodes</tt> property; the main advantage of doing this is that the
  13519. * comparator function can access implicit fields populated by the network
  13520. * layout, such as the <tt>linkDegree</tt>.
  13521. *
  13522. * <p>Note that matrix visualizations are particularly sensitive to order. This
  13523. * is referred to as the seriation problem, and many different techniques exist
  13524. * to find good node orders that emphasize clusters, such as spectral layout and
  13525. * simulated annealing.
  13526. *
  13527. * @param {function} f comparator function for nodes.
  13528. * @returns {pv.Layout.Matrix} this.
  13529. */
  13530. pv.Layout.Matrix.prototype.sort = function(f) {
  13531. this.$sort = f;
  13532. return this;
  13533. };
  13534. /** @private */
  13535. pv.Layout.Matrix.prototype.buildImplied = function(s) {
  13536. if (pv.Layout.Network.prototype.buildImplied.call(this, s)) return;
  13537. var nodes = s.nodes,
  13538. links = s.links,
  13539. sort = this.$sort,
  13540. n = nodes.length,
  13541. index = pv.range(n),
  13542. labels = [],
  13543. pairs = [],
  13544. map = {};
  13545. s.$matrix = {labels: labels, pairs: pairs};
  13546. /* Sort the nodes. */
  13547. if (sort) index.sort(function(a, b) { return sort(nodes[a], nodes[b]); });
  13548. /* Create pairs. */
  13549. for (var i = 0; i < n; i++) {
  13550. for (var j = 0; j < n; j++) {
  13551. var a = index[i],
  13552. b = index[j],
  13553. p = {
  13554. row: i,
  13555. col: j,
  13556. sourceNode: nodes[a],
  13557. targetNode: nodes[b],
  13558. linkValue: 0
  13559. };
  13560. pairs.push(map[a + "." + b] = p);
  13561. }
  13562. }
  13563. /* Create labels. */
  13564. for (var i = 0; i < n; i++) {
  13565. var a = index[i];
  13566. labels.push(nodes[a], nodes[a]);
  13567. }
  13568. /* Accumulate link values. */
  13569. for (var i = 0; i < links.length; i++) {
  13570. var l = links[i],
  13571. source = l.sourceNode.index,
  13572. target = l.targetNode.index,
  13573. value = l.linkValue;
  13574. map[source + "." + target].linkValue += value;
  13575. if (!s.directed) map[target + "." + source].linkValue += value;
  13576. }
  13577. };
  13578. // ranges (bad, satisfactory, good)
  13579. // measures (actual, forecast)
  13580. // markers (previous, goal)
  13581. /*
  13582. * Chart design based on the recommendations of Stephen Few. Implementation
  13583. * based on the work of Clint Ivy, Jamie Love, and Jason Davies.
  13584. * http://projects.instantcognition.com/protovis/bulletchart/
  13585. */
  13586. pv.Layout.Bullet = function() {
  13587. pv.Layout.call(this);
  13588. var that = this,
  13589. buildImplied = that.buildImplied,
  13590. scale = that.x = pv.Scale.linear(),
  13591. orient,
  13592. horizontal,
  13593. rangeColor,
  13594. measureColor,
  13595. x;
  13596. /** @private Cache layout state to optimize properties. */
  13597. this.buildImplied = function(s) {
  13598. buildImplied.call(this, x = s);
  13599. orient = s.orient;
  13600. horizontal = /^left|right$/.test(orient);
  13601. rangeColor = pv.ramp("#bbb", "#eee")
  13602. .domain(0, Math.max(1, x.ranges.length - 1));
  13603. measureColor = pv.ramp("steelblue", "lightsteelblue")
  13604. .domain(0, Math.max(1, x.measures.length - 1));
  13605. };
  13606. (this.range = new pv.Mark())
  13607. .data(function() { return x.ranges; })
  13608. .reverse(true)
  13609. .left(function() { return orient == "left" ? 0 : null; })
  13610. .top(function() { return orient == "top" ? 0 : null; })
  13611. .right(function() { return orient == "right" ? 0 : null; })
  13612. .bottom(function() { return orient == "bottom" ? 0 : null; })
  13613. .width(function(d) { return horizontal ? scale(d) : null; })
  13614. .height(function(d) { return horizontal ? null : scale(d); })
  13615. .fillStyle(function() { return rangeColor(this.index); })
  13616. .antialias(false)
  13617. .parent = that;
  13618. (this.measure = new pv.Mark())
  13619. .extend(this.range)
  13620. .data(function() { return x.measures; })
  13621. .left(function() { return orient == "left" ? 0 : horizontal ? null : this.parent.width() / 3.25; })
  13622. .top(function() { return orient == "top" ? 0 : horizontal ? this.parent.height() / 3.25 : null; })
  13623. .right(function() { return orient == "right" ? 0 : horizontal ? null : this.parent.width() / 3.25; })
  13624. .bottom(function() { return orient == "bottom" ? 0 : horizontal ? this.parent.height() / 3.25 : null; })
  13625. .fillStyle(function() { return measureColor(this.index); })
  13626. .parent = that;
  13627. (this.marker = new pv.Mark())
  13628. .data(function() { return x.markers; })
  13629. .left(function(d) { return orient == "left" ? scale(d) : horizontal ? null : this.parent.width() / 2; })
  13630. .top(function(d) { return orient == "top" ? scale(d) : horizontal ? this.parent.height() / 2 : null; })
  13631. .right(function(d) { return orient == "right" ? scale(d) : null; })
  13632. .bottom(function(d) { return orient == "bottom" ? scale(d) : null; })
  13633. .strokeStyle("black")
  13634. .shape("bar")
  13635. .angle(function() { return horizontal ? 0 : Math.PI / 2; })
  13636. .parent = that;
  13637. (this.tick = new pv.Mark())
  13638. .data(function() { return scale.ticks(7); })
  13639. .left(function(d) { return orient == "left" ? scale(d) : null; })
  13640. .top(function(d) { return orient == "top" ? scale(d) : null; })
  13641. .right(function(d) { return orient == "right" ? scale(d) : horizontal ? null : -6; })
  13642. .bottom(function(d) { return orient == "bottom" ? scale(d) : horizontal ? -8 : null; })
  13643. .height(function() { return horizontal ? 6 : null; })
  13644. .width(function() { return horizontal ? null : 6; })
  13645. .parent = that;
  13646. };
  13647. pv.Layout.Bullet.prototype = pv.extend(pv.Layout)
  13648. .property("orient", String) // left, right, top, bottom
  13649. .property("ranges")
  13650. .property("markers")
  13651. .property("measures")
  13652. .property("maximum", Number);
  13653. pv.Layout.Bullet.prototype.defaults = new pv.Layout.Bullet()
  13654. .extend(pv.Layout.prototype.defaults)
  13655. .orient("left")
  13656. .ranges([])
  13657. .markers([])
  13658. .measures([]);
  13659. /** @private */
  13660. pv.Layout.Bullet.prototype.buildImplied = function(s) {
  13661. pv.Layout.prototype.buildImplied.call(this, s);
  13662. var size = this.parent[/^left|right$/.test(s.orient) ? "width" : "height"]();
  13663. s.maximum = s.maximum || pv.max([].concat(s.ranges, s.markers, s.measures));
  13664. this.x.domain(0, s.maximum).range(0, size);
  13665. };
  13666. /**
  13667. * Abstract; see an implementing class for details.
  13668. *
  13669. * @class Represents a reusable interaction; applies an interactive behavior to
  13670. * a given mark. Behaviors are themselves functions designed to be used as event
  13671. * handlers. For example, to add pan and zoom support to any panel, say:
  13672. *
  13673. * <pre> .event("mousedown", pv.Behavior.pan())
  13674. * .event("mousewheel", pv.Behavior.zoom())</pre>
  13675. *
  13676. * The behavior should be registered on the event that triggers the start of the
  13677. * behavior. Typically, the behavior will take care of registering for any
  13678. * additional events that are necessary. For example, dragging starts on
  13679. * mousedown, while the drag behavior automatically listens for mousemove and
  13680. * mouseup events on the window. By listening to the window, the behavior can
  13681. * continue to receive mouse events even if the mouse briefly leaves the mark
  13682. * being dragged, or even the root panel.
  13683. *
  13684. * <p>Each behavior implementation has specific requirements as to which events
  13685. * it supports, and how it should be used. For example, the drag behavior
  13686. * requires that the data associated with the mark be an object with <tt>x</tt>
  13687. * and <tt>y</tt> attributes, such as a {@link pv.Vector}, storing the mark's
  13688. * position. See an implementing class for details.
  13689. *
  13690. * @see pv.Behavior.drag
  13691. * @see pv.Behavior.pan
  13692. * @see pv.Behavior.point
  13693. * @see pv.Behavior.select
  13694. * @see pv.Behavior.zoom
  13695. * @extends function
  13696. */
  13697. pv.Behavior = {};
  13698. /**
  13699. * Returns a new drag behavior to be registered on mousedown events.
  13700. *
  13701. * @class Implements interactive dragging starting with mousedown events.
  13702. * Register this behavior on marks that should be draggable by the user, such as
  13703. * the selected region for brushing and linking. This behavior can be used in
  13704. * tandom with {@link pv.Behavior.select} to allow the selected region to be
  13705. * dragged interactively.
  13706. *
  13707. * <p>After the initial mousedown event is triggered, this behavior listens for
  13708. * mousemove and mouseup events on the window. This allows dragging to continue
  13709. * even if the mouse temporarily leaves the mark that is being dragged, or even
  13710. * the root panel.
  13711. *
  13712. * <p>This behavior requires that the data associated with the mark being
  13713. * dragged have <tt>x</tt> and <tt>y</tt> attributes that correspond to the
  13714. * mark's location in pixels. The mark's positional properties are not set
  13715. * directly by this behavior; instead, the positional properties should be
  13716. * defined as:
  13717. *
  13718. * <pre> .left(function(d) d.x)
  13719. * .top(function(d) d.y)</pre>
  13720. *
  13721. * Thus, the behavior does not move the mark directly, but instead updates the
  13722. * mark position by updating the underlying data. Note that if the positional
  13723. * properties are defined with bottom and right (rather than top and left), the
  13724. * drag behavior will be inverted, which will confuse users!
  13725. *
  13726. * <p>The drag behavior is bounded by the parent panel; the <tt>x</tt> and
  13727. * <tt>y</tt> attributes are clamped such that the mark being dragged does not
  13728. * extend outside the enclosing panel's bounds. To facilitate this, the drag
  13729. * behavior also queries for <tt>dx</tt> and <tt>dy</tt> attributes on the
  13730. * underlying data, to determine the dimensions of the bar being dragged. For
  13731. * non-rectangular marks, the drag behavior simply treats the mark as a point,
  13732. * which means that only the mark's center is bounded.
  13733. *
  13734. * <p>The mark being dragged is automatically re-rendered for each mouse event
  13735. * as part of the drag operation. In addition, a <tt>fix</tt> attribute is
  13736. * populated on the mark, which allows visual feedback for dragging. For
  13737. * example, to change the mark fill color while dragging:
  13738. *
  13739. * <pre> .fillStyle(function(d) d.fix ? "#ff7f0e" : "#aec7e8")</pre>
  13740. *
  13741. * In some cases, such as with network layouts, dragging the mark may cause
  13742. * related marks to change, in which case additional marks may also need to be
  13743. * rendered. This can be accomplished by listening for the drag
  13744. * psuedo-events:<ul>
  13745. *
  13746. * <li>dragstart (on mousedown)
  13747. * <li>drag (on mousemove)
  13748. * <li>dragend (on mouseup)
  13749. *
  13750. * </ul>For example, to render the parent panel while dragging, thus
  13751. * re-rendering all sibling marks:
  13752. *
  13753. * <pre> .event("mousedown", pv.Behavior.drag())
  13754. * .event("drag", function() this.parent)</pre>
  13755. *
  13756. * This behavior may be enhanced in the future to allow more flexible
  13757. * configuration of drag behavior.
  13758. *
  13759. * @extends pv.Behavior
  13760. * @see pv.Behavior
  13761. * @see pv.Behavior.select
  13762. * @see pv.Layout.force
  13763. */
  13764. pv.Behavior.drag = function() {
  13765. var scene, // scene context
  13766. index, // scene context
  13767. p, // particle being dragged
  13768. v1, // initial mouse-particle offset
  13769. max;
  13770. /** @private */
  13771. function mousedown(d) {
  13772. index = this.index;
  13773. scene = this.scene;
  13774. var m = this.mouse();
  13775. v1 = ((p = d).fix = pv.vector(d.x, d.y)).minus(m);
  13776. max = {
  13777. x: this.parent.width() - (d.dx || 0),
  13778. y: this.parent.height() - (d.dy || 0)
  13779. };
  13780. scene.mark.context(scene, index, function() { this.render(); });
  13781. pv.Mark.dispatch("dragstart", scene, index);
  13782. }
  13783. /** @private */
  13784. function mousemove() {
  13785. if (!scene) return;
  13786. scene.mark.context(scene, index, function() {
  13787. var m = this.mouse();
  13788. p.x = p.fix.x = Math.max(0, Math.min(v1.x + m.x, max.x));
  13789. p.y = p.fix.y = Math.max(0, Math.min(v1.y + m.y, max.y));
  13790. this.render();
  13791. });
  13792. pv.Mark.dispatch("drag", scene, index);
  13793. }
  13794. /** @private */
  13795. function mouseup() {
  13796. if (!scene) return;
  13797. p.fix = null;
  13798. scene.mark.context(scene, index, function() { this.render(); });
  13799. pv.Mark.dispatch("dragend", scene, index);
  13800. scene = null;
  13801. }
  13802. pv.listen(window, "mousemove", mousemove);
  13803. pv.listen(window, "mouseup", mouseup);
  13804. return mousedown;
  13805. };
  13806. /**
  13807. * Returns a new point behavior to be registered on mousemove events.
  13808. *
  13809. * @class Implements interactive fuzzy pointing, identifying marks that are in
  13810. * close proximity to the mouse cursor. This behavior is an alternative to the
  13811. * native mouseover and mouseout events, improving usability. Rather than
  13812. * requiring the user to mouseover a mark exactly, the mouse simply needs to
  13813. * move near the given mark and a "point" event is triggered. In addition, if
  13814. * multiple marks overlap, the point behavior can be used to identify the mark
  13815. * instance closest to the cursor, as opposed to the one that is rendered on
  13816. * top.
  13817. *
  13818. * <p>The point behavior can also identify the closest mark instance for marks
  13819. * that produce a continuous graphic primitive. The point behavior can thus be
  13820. * used to provide details-on-demand for both discrete marks (such as dots and
  13821. * bars), as well as continuous marks (such as lines and areas).
  13822. *
  13823. * <p>This behavior is implemented by finding the closest mark instance to the
  13824. * mouse cursor on every mousemove event. If this closest mark is within the
  13825. * given radius threshold, which defaults to 30 pixels, a "point" psuedo-event
  13826. * is dispatched to the given mark instance. If any mark were previously
  13827. * pointed, it would receive a corresponding "unpoint" event. These two
  13828. * psuedo-event types correspond to the native "mouseover" and "mouseout"
  13829. * events, respectively. To increase the radius at which the point behavior can
  13830. * be applied, specify an appropriate threshold to the constructor, up to
  13831. * <tt>Infinity</tt>.
  13832. *
  13833. * <p>By default, the standard Cartesian distance is computed. However, with
  13834. * some visualizations it is desirable to consider only a single dimension, such
  13835. * as the <i>x</i>-dimension for an independent variable. In this case, the
  13836. * collapse parameter can be set to collapse the <i>y</i> dimension:
  13837. *
  13838. * <pre> .event("mousemove", pv.Behavior.point(Infinity).collapse("y"))</pre>
  13839. *
  13840. * <p>This behavior only listens to mousemove events on the assigned panel,
  13841. * which is typically the root panel. The behavior will search recursively for
  13842. * descendant marks to point. If the mouse leaves the assigned panel, the
  13843. * behavior no longer receives mousemove events; an unpoint psuedo-event is
  13844. * automatically dispatched to unpoint any pointed mark. Marks may be re-pointed
  13845. * when the mouse reenters the panel.
  13846. *
  13847. * <p>Panels have transparent fill styles by default; this means that panels may
  13848. * not receive the initial mousemove event to start pointing. To fix this
  13849. * problem, either given the panel a visible fill style (such as "white"), or
  13850. * set the <tt>events</tt> property to "all" such that the panel receives events
  13851. * despite its transparent fill.
  13852. *
  13853. * <p>Note: this behavior does not currently wedge marks.
  13854. *
  13855. * @extends pv.Behavior
  13856. *
  13857. * @param {number} [r] the fuzzy radius threshold in pixels
  13858. * @see <a href="http://www.tovigrossman.com/papers/chi2005bubblecursor.pdf"
  13859. * >"The Bubble Cursor: Enhancing Target Acquisition by Dynamic Resizing of the
  13860. * Cursor's Activation Area"</a> by T. Grossman &amp; R. Balakrishnan, CHI 2005.
  13861. */
  13862. pv.Behavior.point = function(r) {
  13863. var unpoint, // the current pointer target
  13864. collapse = null, // dimensions to collapse
  13865. kx = 1, // x-dimension cost scale
  13866. ky = 1, // y-dimension cost scale
  13867. r2 = arguments.length ? r * r : 900; // fuzzy radius
  13868. /** @private Search for the mark closest to the mouse. */
  13869. function search(scene, index) {
  13870. var s = scene[index],
  13871. point = {cost: Infinity};
  13872. for (var i = 0, n = s.visible && s.children.length; i < n; i++) {
  13873. var child = s.children[i], mark = child.mark, p;
  13874. if (mark.type == "panel") {
  13875. mark.scene = child;
  13876. for (var j = 0, m = child.length; j < m; j++) {
  13877. mark.index = j;
  13878. p = search(child, j);
  13879. if (p.cost < point.cost) point = p;
  13880. }
  13881. delete mark.scene;
  13882. delete mark.index;
  13883. } else if (mark.$handlers.point) {
  13884. var v = mark.mouse();
  13885. for (var j = 0, m = child.length; j < m; j++) {
  13886. var c = child[j],
  13887. dx = v.x - c.left - (c.width || 0) / 2,
  13888. dy = v.y - c.top - (c.height || 0) / 2,
  13889. dd = kx * dx * dx + ky * dy * dy;
  13890. if (dd < point.cost) {
  13891. point.distance = dx * dx + dy * dy;
  13892. point.cost = dd;
  13893. point.scene = child;
  13894. point.index = j;
  13895. }
  13896. }
  13897. }
  13898. }
  13899. return point;
  13900. }
  13901. /** @private */
  13902. function mousemove() {
  13903. /* If the closest mark is far away, clear the current target. */
  13904. var point = search(this.scene, this.index);
  13905. if ((point.cost == Infinity) || (point.distance > r2)) point = null;
  13906. /* Unpoint the old target, if it's not the new target. */
  13907. if (unpoint) {
  13908. if (point
  13909. && (unpoint.scene == point.scene)
  13910. && (unpoint.index == point.index)) return;
  13911. pv.Mark.dispatch("unpoint", unpoint.scene, unpoint.index);
  13912. }
  13913. /* Point the new target, if there is one. */
  13914. if (unpoint = point) {
  13915. pv.Mark.dispatch("point", point.scene, point.index);
  13916. /* Unpoint when the mouse leaves the root panel. */
  13917. pv.listen(this.root.canvas(), "mouseout", mouseout);
  13918. }
  13919. }
  13920. /** @private */
  13921. function mouseout(e) {
  13922. if (unpoint && !pv.ancestor(this, e.relatedTarget)) {
  13923. pv.Mark.dispatch("unpoint", unpoint.scene, unpoint.index);
  13924. unpoint = null;
  13925. }
  13926. }
  13927. /**
  13928. * Sets or gets the collapse parameter. By default, the standard Cartesian
  13929. * distance is computed. However, with some visualizations it is desirable to
  13930. * consider only a single dimension, such as the <i>x</i>-dimension for an
  13931. * independent variable. In this case, the collapse parameter can be set to
  13932. * collapse the <i>y</i> dimension:
  13933. *
  13934. * <pre> .event("mousemove", pv.Behavior.point(Infinity).collapse("y"))</pre>
  13935. *
  13936. * @function
  13937. * @returns {pv.Behavior.point} this, or the current collapse parameter.
  13938. * @name pv.Behavior.point.prototype.collapse
  13939. * @param {string} [x] the new collapse parameter
  13940. */
  13941. mousemove.collapse = function(x) {
  13942. if (arguments.length) {
  13943. collapse = String(x);
  13944. switch (collapse) {
  13945. case "y": kx = 1; ky = 0; break;
  13946. case "x": kx = 0; ky = 1; break;
  13947. default: kx = 1; ky = 1; break;
  13948. }
  13949. return mousemove;
  13950. }
  13951. return collapse;
  13952. };
  13953. return mousemove;
  13954. };
  13955. /**
  13956. * Returns a new select behavior to be registered on mousedown events.
  13957. *
  13958. * @class Implements interactive selecting starting with mousedown events.
  13959. * Register this behavior on panels that should be selectable by the user, such
  13960. * for brushing and linking. This behavior can be used in tandom with
  13961. * {@link pv.Behavior.drag} to allow the selected region to be dragged
  13962. * interactively.
  13963. *
  13964. * <p>After the initial mousedown event is triggered, this behavior listens for
  13965. * mousemove and mouseup events on the window. This allows selecting to continue
  13966. * even if the mouse temporarily leaves the assigned panel, or even the root
  13967. * panel.
  13968. *
  13969. * <p>This behavior requires that the data associated with the mark being
  13970. * dragged have <tt>x</tt>, <tt>y</tt>, <tt>dx</tt> and <tt>dy</tt> attributes
  13971. * that correspond to the mark's location and dimensions in pixels. The mark's
  13972. * positional properties are not set directly by this behavior; instead, the
  13973. * positional properties should be defined as:
  13974. *
  13975. * <pre> .left(function(d) d.x)
  13976. * .top(function(d) d.y)
  13977. * .width(function(d) d.dx)
  13978. * .height(function(d) d.dy)</pre>
  13979. *
  13980. * Thus, the behavior does not resize the mark directly, but instead updates the
  13981. * selection by updating the assigned panel's underlying data. Note that if the
  13982. * positional properties are defined with bottom and right (rather than top and
  13983. * left), the drag behavior will be inverted, which will confuse users!
  13984. *
  13985. * <p>The select behavior is bounded by the assigned panel; the positional
  13986. * attributes are clamped such that the selection does not extend outside the
  13987. * panel's bounds.
  13988. *
  13989. * <p>The panel being selected is automatically re-rendered for each mouse event
  13990. * as part of the drag operation. This behavior may be enhanced in the future to
  13991. * allow more flexible configuration of select behavior. In some cases, such as
  13992. * with parallel coordinates, making a selection may cause related marks to
  13993. * change, in which case additional marks may also need to be rendered. This can
  13994. * be accomplished by listening for the select psuedo-events:<ul>
  13995. *
  13996. * <li>selectstart (on mousedown)
  13997. * <li>select (on mousemove)
  13998. * <li>selectend (on mouseup)
  13999. *
  14000. * </ul>For example, to render the parent panel while selecting, thus
  14001. * re-rendering all sibling marks:
  14002. *
  14003. * <pre> .event("mousedown", pv.Behavior.drag())
  14004. * .event("select", function() this.parent)</pre>
  14005. *
  14006. * This behavior may be enhanced in the future to allow more flexible
  14007. * configuration of the selection behavior.
  14008. *
  14009. * @extends pv.Behavior
  14010. * @see pv.Behavior.drag
  14011. */
  14012. pv.Behavior.select = function() {
  14013. var scene, // scene context
  14014. index, // scene context
  14015. r, // region being selected
  14016. m1; // initial mouse position
  14017. /** @private */
  14018. function mousedown(d) {
  14019. index = this.index;
  14020. scene = this.scene;
  14021. m1 = this.mouse();
  14022. r = d;
  14023. r.x = m1.x;
  14024. r.y = m1.y;
  14025. r.dx = r.dy = 0;
  14026. pv.Mark.dispatch("selectstart", scene, index);
  14027. }
  14028. /** @private */
  14029. function mousemove() {
  14030. if (!scene) return;
  14031. scene.mark.context(scene, index, function() {
  14032. var m2 = this.mouse();
  14033. r.x = Math.max(0, Math.min(m1.x, m2.x));
  14034. r.y = Math.max(0, Math.min(m1.y, m2.y));
  14035. r.dx = Math.min(this.width(), Math.max(m2.x, m1.x)) - r.x;
  14036. r.dy = Math.min(this.height(), Math.max(m2.y, m1.y)) - r.y;
  14037. this.render();
  14038. });
  14039. pv.Mark.dispatch("select", scene, index);
  14040. }
  14041. /** @private */
  14042. function mouseup() {
  14043. if (!scene) return;
  14044. pv.Mark.dispatch("selectend", scene, index);
  14045. scene = null;
  14046. }
  14047. pv.listen(window, "mousemove", mousemove);
  14048. pv.listen(window, "mouseup", mouseup);
  14049. return mousedown;
  14050. };
  14051. /**
  14052. * Returns a new resize behavior to be registered on mousedown events.
  14053. *
  14054. * @class Implements interactive resizing of a selection starting with mousedown
  14055. * events. Register this behavior on selection handles that should be resizeable
  14056. * by the user, such for brushing and linking. This behavior can be used in
  14057. * tandom with {@link pv.Behavior.select} and {@link pv.Behavior.drag} to allow
  14058. * the selected region to be selected and dragged interactively.
  14059. *
  14060. * <p>After the initial mousedown event is triggered, this behavior listens for
  14061. * mousemove and mouseup events on the window. This allows resizing to continue
  14062. * even if the mouse temporarily leaves the assigned panel, or even the root
  14063. * panel.
  14064. *
  14065. * <p>This behavior requires that the data associated with the mark being
  14066. * resized have <tt>x</tt>, <tt>y</tt>, <tt>dx</tt> and <tt>dy</tt> attributes
  14067. * that correspond to the mark's location and dimensions in pixels. The mark's
  14068. * positional properties are not set directly by this behavior; instead, the
  14069. * positional properties should be defined as:
  14070. *
  14071. * <pre> .left(function(d) d.x)
  14072. * .top(function(d) d.y)
  14073. * .width(function(d) d.dx)
  14074. * .height(function(d) d.dy)</pre>
  14075. *
  14076. * Thus, the behavior does not resize the mark directly, but instead updates the
  14077. * size by updating the assigned panel's underlying data. Note that if the
  14078. * positional properties are defined with bottom and right (rather than top and
  14079. * left), the resize behavior will be inverted, which will confuse users!
  14080. *
  14081. * <p>The resize behavior is bounded by the assigned mark's enclosing panel; the
  14082. * positional attributes are clamped such that the selection does not extend
  14083. * outside the panel's bounds.
  14084. *
  14085. * <p>The mark being resized is automatically re-rendered for each mouse event
  14086. * as part of the resize operation. This behavior may be enhanced in the future
  14087. * to allow more flexible configuration. In some cases, such as with parallel
  14088. * coordinates, resizing the selection may cause related marks to change, in
  14089. * which case additional marks may also need to be rendered. This can be
  14090. * accomplished by listening for the select psuedo-events:<ul>
  14091. *
  14092. * <li>resizestart (on mousedown)
  14093. * <li>resize (on mousemove)
  14094. * <li>resizeend (on mouseup)
  14095. *
  14096. * </ul>For example, to render the parent panel while resizing, thus
  14097. * re-rendering all sibling marks:
  14098. *
  14099. * <pre> .event("mousedown", pv.Behavior.resize("left"))
  14100. * .event("resize", function() this.parent)</pre>
  14101. *
  14102. * This behavior may be enhanced in the future to allow more flexible
  14103. * configuration of the selection behavior.
  14104. *
  14105. * @extends pv.Behavior
  14106. * @see pv.Behavior.select
  14107. * @see pv.Behavior.drag
  14108. */
  14109. pv.Behavior.resize = function(side) {
  14110. var scene, // scene context
  14111. index, // scene context
  14112. r, // region being selected
  14113. m1; // initial mouse position
  14114. /** @private */
  14115. function mousedown(d) {
  14116. index = this.index;
  14117. scene = this.scene;
  14118. m1 = this.mouse();
  14119. r = d;
  14120. switch (side) {
  14121. case "left": m1.x = r.x + r.dx; break;
  14122. case "right": m1.x = r.x; break;
  14123. case "top": m1.y = r.y + r.dy; break;
  14124. case "bottom": m1.y = r.y; break;
  14125. }
  14126. pv.Mark.dispatch("resizestart", scene, index);
  14127. }
  14128. /** @private */
  14129. function mousemove() {
  14130. if (!scene) return;
  14131. scene.mark.context(scene, index, function() {
  14132. var m2 = this.mouse();
  14133. r.x = Math.max(0, Math.min(m1.x, m2.x));
  14134. r.y = Math.max(0, Math.min(m1.y, m2.y));
  14135. r.dx = Math.min(this.parent.width(), Math.max(m2.x, m1.x)) - r.x;
  14136. r.dy = Math.min(this.parent.height(), Math.max(m2.y, m1.y)) - r.y;
  14137. this.render();
  14138. });
  14139. pv.Mark.dispatch("resize", scene, index);
  14140. }
  14141. /** @private */
  14142. function mouseup() {
  14143. if (!scene) return;
  14144. pv.Mark.dispatch("resizeend", scene, index);
  14145. scene = null;
  14146. }
  14147. pv.listen(window, "mousemove", mousemove);
  14148. pv.listen(window, "mouseup", mouseup);
  14149. return mousedown;
  14150. };
  14151. /**
  14152. * Returns a new pan behavior to be registered on mousedown events.
  14153. *
  14154. * @class Implements interactive panning starting with mousedown events.
  14155. * Register this behavior on panels to allow panning. This behavior can be used
  14156. * in tandem with {@link pv.Behavior.zoom} to allow both panning and zooming:
  14157. *
  14158. * <pre> .event("mousedown", pv.Behavior.pan())
  14159. * .event("mousewheel", pv.Behavior.zoom())</pre>
  14160. *
  14161. * The pan behavior currently supports only mouse events; support for keyboard
  14162. * shortcuts to improve accessibility may be added in the future.
  14163. *
  14164. * <p>After the initial mousedown event is triggered, this behavior listens for
  14165. * mousemove and mouseup events on the window. This allows panning to continue
  14166. * even if the mouse temporarily leaves the panel that is being panned, or even
  14167. * the root panel.
  14168. *
  14169. * <p>The implementation of this behavior relies on the panel's
  14170. * <tt>transform</tt> property, which specifies a matrix transformation that is
  14171. * applied to child marks. Note that the transform property only affects the
  14172. * panel's children, but not the panel itself; therefore the panel's fill and
  14173. * stroke will not change when the contents are panned.
  14174. *
  14175. * <p>Panels have transparent fill styles by default; this means that panels may
  14176. * not receive the initial mousedown event to start panning. To fix this
  14177. * problem, either given the panel a visible fill style (such as "white"), or
  14178. * set the <tt>events</tt> property to "all" such that the panel receives events
  14179. * despite its transparent fill.
  14180. *
  14181. * <p>The pan behavior has optional support for bounding. If enabled, the user
  14182. * will not be able to pan the panel outside of the initial bounds. This feature
  14183. * is designed to work in conjunction with the zoom behavior; otherwise,
  14184. * bounding the panel effectively disables all panning.
  14185. *
  14186. * @extends pv.Behavior
  14187. * @see pv.Behavior.zoom
  14188. * @see pv.Panel#transform
  14189. */
  14190. pv.Behavior.pan = function() {
  14191. var scene, // scene context
  14192. index, // scene context
  14193. m1, // transformation matrix at the start of panning
  14194. v1, // mouse location at the start of panning
  14195. k, // inverse scale
  14196. bound; // whether to bound to the panel
  14197. /** @private */
  14198. function mousedown() {
  14199. index = this.index;
  14200. scene = this.scene;
  14201. v1 = pv.vector(pv.event.pageX, pv.event.pageY);
  14202. m1 = this.transform();
  14203. k = 1 / (m1.k * this.scale);
  14204. if (bound) {
  14205. bound = {
  14206. x: (1 - m1.k) * this.width(),
  14207. y: (1 - m1.k) * this.height()
  14208. };
  14209. }
  14210. }
  14211. /** @private */
  14212. function mousemove() {
  14213. if (!scene) return;
  14214. scene.mark.context(scene, index, function() {
  14215. var x = (pv.event.pageX - v1.x) * k,
  14216. y = (pv.event.pageY - v1.y) * k,
  14217. m = m1.translate(x, y);
  14218. if (bound) {
  14219. m.x = Math.max(bound.x, Math.min(0, m.x));
  14220. m.y = Math.max(bound.y, Math.min(0, m.y));
  14221. }
  14222. this.transform(m).render();
  14223. });
  14224. pv.Mark.dispatch("pan", scene, index);
  14225. }
  14226. /** @private */
  14227. function mouseup() {
  14228. scene = null;
  14229. }
  14230. /**
  14231. * Sets or gets the bound parameter. If bounding is enabled, the user will not
  14232. * be able to pan outside the initial panel bounds; this typically applies
  14233. * only when the pan behavior is used in tandem with the zoom behavior.
  14234. * Bounding is not enabled by default.
  14235. *
  14236. * <p>Note: enabling bounding after panning has already occurred will not
  14237. * immediately reset the transform. Bounding should be enabled before the
  14238. * panning behavior is applied.
  14239. *
  14240. * @function
  14241. * @returns {pv.Behavior.pan} this, or the current bound parameter.
  14242. * @name pv.Behavior.pan.prototype.bound
  14243. * @param {boolean} [x] the new bound parameter.
  14244. */
  14245. mousedown.bound = function(x) {
  14246. if (arguments.length) {
  14247. bound = Boolean(x);
  14248. return this;
  14249. }
  14250. return Boolean(bound);
  14251. };
  14252. pv.listen(window, "mousemove", mousemove);
  14253. pv.listen(window, "mouseup", mouseup);
  14254. return mousedown;
  14255. };
  14256. /**
  14257. * Returns a new zoom behavior to be registered on mousewheel events.
  14258. *
  14259. * @class Implements interactive zooming using mousewheel events. Register this
  14260. * behavior on panels to allow zooming. This behavior can be used in tandem with
  14261. * {@link pv.Behavior.pan} to allow both panning and zooming:
  14262. *
  14263. * <pre> .event("mousedown", pv.Behavior.pan())
  14264. * .event("mousewheel", pv.Behavior.zoom())</pre>
  14265. *
  14266. * The zoom behavior currently supports only mousewheel events; support for
  14267. * keyboard shortcuts and gesture events to improve accessibility may be added
  14268. * in the future.
  14269. *
  14270. * <p>The implementation of this behavior relies on the panel's
  14271. * <tt>transform</tt> property, which specifies a matrix transformation that is
  14272. * applied to child marks. Note that the transform property only affects the
  14273. * panel's children, but not the panel itself; therefore the panel's fill and
  14274. * stroke will not change when the contents are zoomed. The built-in support for
  14275. * transforms only supports uniform scaling and translates, which is sufficient
  14276. * for panning and zooming. Note that this is not a strict geometric
  14277. * transformation, as the <tt>lineWidth</tt> property is scale-aware: strokes
  14278. * are drawn at constant size independent of scale.
  14279. *
  14280. * <p>Panels have transparent fill styles by default; this means that panels may
  14281. * not receive mousewheel events to zoom. To fix this problem, either given the
  14282. * panel a visible fill style (such as "white"), or set the <tt>events</tt>
  14283. * property to "all" such that the panel receives events despite its transparent
  14284. * fill.
  14285. *
  14286. * <p>The zoom behavior has optional support for bounding. If enabled, the user
  14287. * will not be able to zoom out farther than the initial bounds. This feature is
  14288. * designed to work in conjunction with the pan behavior.
  14289. *
  14290. * @extends pv.Behavior
  14291. * @see pv.Panel#transform
  14292. * @see pv.Mark#scale
  14293. * @param {number} speed
  14294. */
  14295. pv.Behavior.zoom = function(speed) {
  14296. var bound; // whether to bound to the panel
  14297. if (!arguments.length) speed = 1 / 48;
  14298. /** @private */
  14299. function mousewheel() {
  14300. var v = this.mouse(),
  14301. k = pv.event.wheel * speed,
  14302. m = this.transform().translate(v.x, v.y)
  14303. .scale((k < 0) ? (1e3 / (1e3 - k)) : ((1e3 + k) / 1e3))
  14304. .translate(-v.x, -v.y);
  14305. if (bound) {
  14306. m.k = Math.max(1, m.k);
  14307. m.x = Math.max((1 - m.k) * this.width(), Math.min(0, m.x));
  14308. m.y = Math.max((1 - m.k) * this.height(), Math.min(0, m.y));
  14309. }
  14310. this.transform(m).render();
  14311. pv.Mark.dispatch("zoom", this.scene, this.index);
  14312. }
  14313. /**
  14314. * Sets or gets the bound parameter. If bounding is enabled, the user will not
  14315. * be able to zoom out farther than the initial panel bounds. Bounding is not
  14316. * enabled by default. If this behavior is used in tandem with the pan
  14317. * behavior, both should use the same bound parameter.
  14318. *
  14319. * <p>Note: enabling bounding after zooming has already occurred will not
  14320. * immediately reset the transform. Bounding should be enabled before the zoom
  14321. * behavior is applied.
  14322. *
  14323. * @function
  14324. * @returns {pv.Behavior.zoom} this, or the current bound parameter.
  14325. * @name pv.Behavior.zoom.prototype.bound
  14326. * @param {boolean} [x] the new bound parameter.
  14327. */
  14328. mousewheel.bound = function(x) {
  14329. if (arguments.length) {
  14330. bound = Boolean(x);
  14331. return this;
  14332. }
  14333. return Boolean(bound);
  14334. };
  14335. return mousewheel;
  14336. };
  14337. /**
  14338. * @ignore
  14339. * @namespace
  14340. */
  14341. pv.Geo = function() {};
  14342. /**
  14343. * Abstract; not implemented. There is no explicit constructor; this class
  14344. * merely serves to document the representation used by {@link pv.Geo.scale}.
  14345. *
  14346. * @class Represents a pair of geographic coordinates.
  14347. *
  14348. * @name pv.Geo.LatLng
  14349. * @see pv.Geo.scale
  14350. */
  14351. /**
  14352. * The <i>latitude</i> coordinate in degrees; positive is North.
  14353. *
  14354. * @type number
  14355. * @name pv.Geo.LatLng.prototype.lat
  14356. */
  14357. /**
  14358. * The <i>longitude</i> coordinate in degrees; positive is East.
  14359. *
  14360. * @type number
  14361. * @name pv.Geo.LatLng.prototype.lng
  14362. */
  14363. /**
  14364. * Abstract; not implemented. There is no explicit constructor; this class
  14365. * merely serves to document the representation used by {@link pv.Geo.scale}.
  14366. *
  14367. * @class Represents a geographic projection. This class provides the core
  14368. * implementation for {@link pv.Geo.scale}s, mapping between geographic
  14369. * coordinates (latitude and longitude) and normalized screen space in the range
  14370. * [-1,1]. The remaining mapping between normalized screen space and actual
  14371. * pixels is performed by <tt>pv.Geo.scale</tt>.
  14372. *
  14373. * <p>Many geographic projections have a point around which the projection is
  14374. * centered. Rather than have each implementation add support for a
  14375. * user-specified center point, the <tt>pv.Geo.scale</tt> translates the
  14376. * geographic coordinates relative to the center point for both the forward and
  14377. * inverse projection.
  14378. *
  14379. * <p>In general, this class should not be used directly, unless the desire is
  14380. * to implement a new geographic projection. Instead, use <tt>pv.Geo.scale</tt>.
  14381. * Implementations are not required to implement inverse projections, but are
  14382. * needed for some forms of interactivity. Also note that some inverse
  14383. * projections are ambiguous, such as the connecting points in Dymaxian maps.
  14384. *
  14385. * @name pv.Geo.Projection
  14386. * @see pv.Geo.scale
  14387. */
  14388. /**
  14389. * The <i>forward</i> projection.
  14390. *
  14391. * @function
  14392. * @name pv.Geo.Projection.prototype.project
  14393. * @param {pv.Geo.LatLng} latlng the latitude and longitude to project.
  14394. * @returns {pv.Vector} the xy-coordinates of the given point.
  14395. */
  14396. /**
  14397. * The <i>inverse</i> projection; optional.
  14398. *
  14399. * @function
  14400. * @name pv.Geo.Projection.prototype.invert
  14401. * @param {pv.Vector} xy the x- and y-coordinates to invert.
  14402. * @returns {pv.Geo.LatLng} the latitude and longitude of the given point.
  14403. */
  14404. /**
  14405. * The built-in projections.
  14406. *
  14407. * @see pv.Geo.Projection
  14408. * @namespace
  14409. */
  14410. pv.Geo.projections = {
  14411. /** @see http://en.wikipedia.org/wiki/Mercator_projection */
  14412. mercator: {
  14413. project: function(latlng) {
  14414. return {
  14415. x: latlng.lng / 180,
  14416. y: latlng.lat > 85 ? 1 : latlng.lat < -85 ? -1
  14417. : Math.log(Math.tan(Math.PI / 4
  14418. + pv.radians(latlng.lat) / 2)) / Math.PI
  14419. };
  14420. },
  14421. invert: function(xy) {
  14422. return {
  14423. lng: xy.x * 180,
  14424. lat: pv.degrees(2 * Math.atan(Math.exp(xy.y * Math.PI)) - Math.PI / 2)
  14425. };
  14426. }
  14427. },
  14428. /** @see http://en.wikipedia.org/wiki/Gall-Peters_projection */
  14429. "gall-peters": {
  14430. project: function(latlng) {
  14431. return {
  14432. x: latlng.lng / 180,
  14433. y: Math.sin(pv.radians(latlng.lat))
  14434. };
  14435. },
  14436. invert: function(xy) {
  14437. return {
  14438. lng: xy.x * 180,
  14439. lat: pv.degrees(Math.asin(xy.y))
  14440. };
  14441. }
  14442. },
  14443. /** @see http://en.wikipedia.org/wiki/Sinusoidal_projection */
  14444. sinusoidal: {
  14445. project: function(latlng) {
  14446. return {
  14447. x: pv.radians(latlng.lng) * Math.cos(pv.radians(latlng.lat)) / Math.PI,
  14448. y: latlng.lat / 90
  14449. };
  14450. },
  14451. invert: function(xy) {
  14452. return {
  14453. lng: pv.degrees((xy.x * Math.PI) / Math.cos(xy.y * Math.PI / 2)),
  14454. lat: xy.y * 90
  14455. };
  14456. }
  14457. },
  14458. /** @see http://en.wikipedia.org/wiki/Aitoff_projection */
  14459. aitoff: {
  14460. project: function(latlng) {
  14461. var l = pv.radians(latlng.lng),
  14462. f = pv.radians(latlng.lat),
  14463. a = Math.acos(Math.cos(f) * Math.cos(l / 2));
  14464. return {
  14465. x: 2 * (a ? (Math.cos(f) * Math.sin(l / 2) * a / Math.sin(a)) : 0) / Math.PI,
  14466. y: 2 * (a ? (Math.sin(f) * a / Math.sin(a)) : 0) / Math.PI
  14467. };
  14468. },
  14469. invert: function(xy) {
  14470. var x = xy.x * Math.PI / 2,
  14471. y = xy.y * Math.PI / 2;
  14472. return {
  14473. lng: pv.degrees(x / Math.cos(y)),
  14474. lat: pv.degrees(y)
  14475. };
  14476. }
  14477. },
  14478. /** @see http://en.wikipedia.org/wiki/Hammer_projection */
  14479. hammer: {
  14480. project: function(latlng) {
  14481. var l = pv.radians(latlng.lng),
  14482. f = pv.radians(latlng.lat),
  14483. c = Math.sqrt(1 + Math.cos(f) * Math.cos(l / 2));
  14484. return {
  14485. x: 2 * Math.SQRT2 * Math.cos(f) * Math.sin(l / 2) / c / 3,
  14486. y: Math.SQRT2 * Math.sin(f) / c / 1.5
  14487. };
  14488. },
  14489. invert: function(xy) {
  14490. var x = xy.x * 3,
  14491. y = xy.y * 1.5,
  14492. z = Math.sqrt(1 - x * x / 16 - y * y / 4);
  14493. return {
  14494. lng: pv.degrees(2 * Math.atan2(z * x, 2 * (2 * z * z - 1))),
  14495. lat: pv.degrees(Math.asin(z * y))
  14496. };
  14497. }
  14498. },
  14499. /** The identity or "none" projection. */
  14500. identity: {
  14501. project: function(latlng) {
  14502. return {
  14503. x: latlng.lng / 180,
  14504. y: latlng.lat / 90
  14505. };
  14506. },
  14507. invert: function(xy) {
  14508. return {
  14509. lng: xy.x * 180,
  14510. lat: xy.y * 90
  14511. };
  14512. }
  14513. }
  14514. };
  14515. /**
  14516. * Returns a geographic scale. The arguments to this constructor are optional,
  14517. * and equivalent to calling {@link #projection}.
  14518. *
  14519. * @class Represents a geographic scale; a mapping between latitude-longitude
  14520. * coordinates and screen pixel coordinates. By default, the domain is inferred
  14521. * from the geographic coordinates, so that the domain fills the output range.
  14522. *
  14523. * <p>Note that geographic scales are two-dimensional transformations, rather
  14524. * than the one-dimensional bidrectional mapping typical of other scales.
  14525. * Rather than mapping (for example) between a numeric domain and a numeric
  14526. * range, geographic scales map between two coordinate objects: {@link
  14527. * pv.Geo.LatLng} and {@link pv.Vector}.
  14528. *
  14529. * @param {pv.Geo.Projection} [p] optional projection.
  14530. * @see pv.Geo.scale#ticks
  14531. */
  14532. pv.Geo.scale = function(p) {
  14533. var rmin = {x: 0, y: 0}, // default range minimum
  14534. rmax = {x: 1, y: 1}, // default range maximum
  14535. d = [], // default domain
  14536. j = pv.Geo.projections.identity, // domain <-> normalized range
  14537. x = pv.Scale.linear(-1, 1).range(0, 1), // normalized <-> range
  14538. y = pv.Scale.linear(-1, 1).range(1, 0), // normalized <-> range
  14539. c = {lng: 0, lat: 0}, // Center Point
  14540. lastLatLng, // cached latlng
  14541. lastPoint; // cached point
  14542. /** @private */
  14543. function scale(latlng) {
  14544. if (!lastLatLng
  14545. || (latlng.lng != lastLatLng.lng)
  14546. || (latlng.lat != lastLatLng.lat)) {
  14547. lastLatLng = latlng;
  14548. var p = project(latlng);
  14549. lastPoint = {x: x(p.x), y: y(p.y)};
  14550. }
  14551. return lastPoint;
  14552. }
  14553. /** @private */
  14554. function project(latlng) {
  14555. var offset = {lng: latlng.lng - c.lng, lat: latlng.lat};
  14556. return j.project(offset);
  14557. }
  14558. /** @private */
  14559. function invert(xy) {
  14560. var latlng = j.invert(xy);
  14561. latlng.lng += c.lng;
  14562. return latlng;
  14563. }
  14564. /** Returns the projected x-coordinate. */
  14565. scale.x = function(latlng) {
  14566. return scale(latlng).x;
  14567. };
  14568. /** Returns the projected y-coordinate. */
  14569. scale.y = function(latlng) {
  14570. return scale(latlng).y;
  14571. };
  14572. /**
  14573. * Abstract; this is a local namespace on a given geographic scale.
  14574. *
  14575. * @namespace Tick functions for geographic scales. Because geographic scales
  14576. * represent two-dimensional transformations (as opposed to one-dimensional
  14577. * transformations typical of other scales), the tick values are similarly
  14578. * represented as two-dimensional coordinates in the input domain, i.e.,
  14579. * {@link pv.Geo.LatLng} objects.
  14580. *
  14581. * <p>Also, note that non-rectilinear projections, such as sinsuoidal and
  14582. * aitoff, may not produce straight lines for constant longitude or constant
  14583. * latitude. Therefore the returned array of ticks is a two-dimensional array,
  14584. * sampling various latitudes as constant longitude, and vice versa.
  14585. *
  14586. * <p>The tick lines can therefore be approximated as polylines, either with
  14587. * "linear" or "cardinal" interpolation. This is not as accurate as drawing
  14588. * the true curve through the projection space, but is usually sufficient.
  14589. *
  14590. * @name pv.Geo.scale.prototype.ticks
  14591. * @see pv.Geo.scale
  14592. * @see pv.Geo.LatLng
  14593. * @see pv.Line#interpolate
  14594. */
  14595. scale.ticks = {
  14596. /**
  14597. * Returns longitude ticks.
  14598. *
  14599. * @function
  14600. * @param {number} [m] the desired number of ticks.
  14601. * @returns {array} a nested array of <tt>pv.Geo.LatLng</tt> ticks.
  14602. * @name pv.Geo.scale.prototype.ticks.prototype.lng
  14603. */
  14604. lng: function(m) {
  14605. var lat, lng;
  14606. if (d.length > 1) {
  14607. var s = pv.Scale.linear();
  14608. if (m == undefined) m = 10;
  14609. lat = s.domain(d, function(d) { return d.lat; }).ticks(m);
  14610. lng = s.domain(d, function(d) { return d.lng; }).ticks(m);
  14611. } else {
  14612. lat = pv.range(-80, 81, 10);
  14613. lng = pv.range(-180, 181, 10);
  14614. }
  14615. return lng.map(function(lng) {
  14616. return lat.map(function(lat) {
  14617. return {lat: lat, lng: lng};
  14618. });
  14619. });
  14620. },
  14621. /**
  14622. * Returns latitude ticks.
  14623. *
  14624. * @function
  14625. * @param {number} [m] the desired number of ticks.
  14626. * @returns {array} a nested array of <tt>pv.Geo.LatLng</tt> ticks.
  14627. * @name pv.Geo.scale.prototype.ticks.prototype.lat
  14628. */
  14629. lat: function(m) {
  14630. return pv.transpose(scale.ticks.lng(m));
  14631. }
  14632. };
  14633. /**
  14634. * Inverts the specified value in the output range, returning the
  14635. * corresponding value in the input domain. This is frequently used to convert
  14636. * the mouse location (see {@link pv.Mark#mouse}) to a value in the input
  14637. * domain. Inversion is only supported for numeric ranges, and not colors.
  14638. *
  14639. * <p>Note that this method does not do any rounding or bounds checking. If
  14640. * the input domain is discrete (e.g., an array index), the returned value
  14641. * should be rounded. If the specified <tt>y</tt> value is outside the range,
  14642. * the returned value may be equivalently outside the input domain.
  14643. *
  14644. * @function
  14645. * @name pv.Geo.scale.prototype.invert
  14646. * @param {number} y a value in the output range (a pixel location).
  14647. * @returns {number} a value in the input domain.
  14648. */
  14649. scale.invert = function(p) {
  14650. return invert({x: x.invert(p.x), y: y.invert(p.y)});
  14651. };
  14652. /**
  14653. * Sets or gets the input domain. Note that unlike quantitative scales, the
  14654. * domain cannot be reduced to a simple rectangle (i.e., minimum and maximum
  14655. * values for latitude and longitude). Instead, the domain values must be
  14656. * projected to normalized space, effectively finding the domain in normalized
  14657. * space rather than in terms of latitude and longitude. Thus, changing the
  14658. * projection requires recomputing the normalized domain.
  14659. *
  14660. * <p>This method can be invoked several ways:
  14661. *
  14662. * <p>1. <tt>domain(values...)</tt>
  14663. *
  14664. * <p>Specifying the domain as a series of {@link pv.Geo.LatLng}s is the most
  14665. * explicit and recommended approach. However, if the domain values are
  14666. * derived from data, you may find the second method more appropriate.
  14667. *
  14668. * <p>2. <tt>domain(array, f)</tt>
  14669. *
  14670. * <p>Rather than enumerating the domain explicitly, you can specify a single
  14671. * argument of an array. In addition, you can specify an optional accessor
  14672. * function to extract the domain values (as {@link pv.Geo.LatLng}s) from the
  14673. * array. If the specified array has fewer than two elements, this scale will
  14674. * default to the full normalized domain.
  14675. *
  14676. * <p>2. <tt>domain()</tt>
  14677. *
  14678. * <p>Invoking the <tt>domain</tt> method with no arguments returns the
  14679. * current domain as an array.
  14680. *
  14681. * @function
  14682. * @name pv.Geo.scale.prototype.domain
  14683. * @param {...} domain... domain values.
  14684. * @returns {pv.Geo.scale} <tt>this</tt>, or the current domain.
  14685. */
  14686. scale.domain = function(array, f) {
  14687. if (arguments.length) {
  14688. d = (array instanceof Array)
  14689. ? ((arguments.length > 1) ? pv.map(array, f) : array)
  14690. : Array.prototype.slice.call(arguments);
  14691. if (d.length > 1) {
  14692. var lngs = d.map(function(c) { return c.lng; });
  14693. var lats = d.map(function(c) { return c.lat; });
  14694. c = {
  14695. lng: (pv.max(lngs) + pv.min(lngs)) / 2,
  14696. lat: (pv.max(lats) + pv.min(lats)) / 2
  14697. };
  14698. var n = d.map(project); // normalized domain
  14699. x.domain(n, function(p) { return p.x; });
  14700. y.domain(n, function(p) { return p.y; });
  14701. } else {
  14702. c = {lng: 0, lat: 0};
  14703. x.domain(-1, 1);
  14704. y.domain(-1, 1);
  14705. }
  14706. lastLatLng = null; // invalidate the cache
  14707. return this;
  14708. }
  14709. return d;
  14710. };
  14711. /**
  14712. * Sets or gets the output range. This method can be invoked several ways:
  14713. *
  14714. * <p>1. <tt>range(min, max)</tt>
  14715. *
  14716. * <p>If two objects are specified, the arguments should be {@link pv.Vector}s
  14717. * which specify the minimum and maximum values of the x- and y-coordinates
  14718. * explicitly.
  14719. *
  14720. * <p>2. <tt>range(width, height)</tt>
  14721. *
  14722. * <p>If two numbers are specified, the arguments specify the maximum values
  14723. * of the x- and y-coordinates explicitly; the minimum values are implicitly
  14724. * zero.
  14725. *
  14726. * <p>3. <tt>range()</tt>
  14727. *
  14728. * <p>Invoking the <tt>range</tt> method with no arguments returns the current
  14729. * range as an array of two {@link pv.Vector}s: the minimum (top-left) and
  14730. * maximum (bottom-right) values.
  14731. *
  14732. * @function
  14733. * @name pv.Geo.scale.prototype.range
  14734. * @param {...} range... range values.
  14735. * @returns {pv.Geo.scale} <tt>this</tt>, or the current range.
  14736. */
  14737. scale.range = function(min, max) {
  14738. if (arguments.length) {
  14739. if (typeof min == "object") {
  14740. rmin = {x: Number(min.x), y: Number(min.y)};
  14741. rmax = {x: Number(max.x), y: Number(max.y)};
  14742. } else {
  14743. rmin = {x: 0, y: 0};
  14744. rmax = {x: Number(min), y: Number(max)};
  14745. }
  14746. x.range(rmin.x, rmax.x);
  14747. y.range(rmax.y, rmin.y); // XXX flipped?
  14748. lastLatLng = null; // invalidate the cache
  14749. return this;
  14750. }
  14751. return [rmin, rmax];
  14752. };
  14753. /**
  14754. * Sets or gets the projection. This method can be invoked several ways:
  14755. *
  14756. * <p>1. <tt>projection(string)</tt>
  14757. *
  14758. * <p>Specifying a string sets the projection to the given named projection in
  14759. * {@link pv.Geo.projections}. If no such projection is found, the identity
  14760. * projection is used.
  14761. *
  14762. * <p>2. <tt>projection(object)</tt>
  14763. *
  14764. * <p>Specifying an object sets the projection to the given custom projection,
  14765. * which must implement the <i>forward</i> and <i>inverse</i> methods per the
  14766. * {@link pv.Geo.Projection} interface.
  14767. *
  14768. * <p>3. <tt>projection()</tt>
  14769. *
  14770. * <p>Invoking the <tt>projection</tt> method with no arguments returns the
  14771. * current object that defined the projection.
  14772. *
  14773. * @function
  14774. * @name pv.Scale.geo.prototype.projection
  14775. * @param {...} range... range values.
  14776. * @returns {pv.Scale.geo} <tt>this</tt>, or the current range.
  14777. */
  14778. scale.projection = function(p) {
  14779. if (arguments.length) {
  14780. j = typeof p == "string"
  14781. ? pv.Geo.projections[p] || pv.Geo.projections.identity
  14782. : p;
  14783. return this.domain(d); // recompute normalized domain
  14784. }
  14785. return p;
  14786. };
  14787. /**
  14788. * Returns a view of this scale by the specified accessor function <tt>f</tt>.
  14789. * Given a scale <tt>g</tt>, <tt>g.by(function(d) d.foo)</tt> is equivalent to
  14790. * <tt>function(d) g(d.foo)</tt>. This method should be used judiciously; it
  14791. * is typically more clear to invoke the scale directly, passing in the value
  14792. * to be scaled.
  14793. *
  14794. * @function
  14795. * @name pv.Geo.scale.prototype.by
  14796. * @param {function} f an accessor function.
  14797. * @returns {pv.Geo.scale} a view of this scale by the specified accessor
  14798. * function.
  14799. */
  14800. scale.by = function(f) {
  14801. function by() { return scale(f.apply(this, arguments)); }
  14802. for (var method in scale) by[method] = scale[method];
  14803. return by;
  14804. };
  14805. if (arguments.length) scale.projection(p);
  14806. return scale;
  14807. };