protovis-d3.2.js 515 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900
  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. x -= n.offsetLeft;
  7402. y -= n.offsetTop;
  7403. } while (n = n.offsetParent);
  7404. /* Compute the inverse transform of all enclosing panels. */
  7405. var t = pv.Transform.identity,
  7406. p = this.properties.transform ? this : this.parent,
  7407. pz = [];
  7408. do { pz.push(p); } while (p = p.parent);
  7409. while (p = pz.pop()) t = t.translate(p.left(), p.top()).times(p.transform());
  7410. t = t.invert();
  7411. return pv.vector(x * t.k + t.x, y * t.k + t.y);
  7412. };
  7413. /**
  7414. * Registers an event handler for the specified event type with this mark. When
  7415. * an event of the specified type is triggered, the specified handler will be
  7416. * invoked. The handler is invoked in a similar method to property functions:
  7417. * the context is <tt>this</tt> mark instance, and the arguments are the full
  7418. * data stack. Event handlers can use property methods to manipulate the display
  7419. * properties of the mark:
  7420. *
  7421. * <pre>m.event("click", function() this.fillStyle("red"));</pre>
  7422. *
  7423. * Alternatively, the external data can be manipulated and the visualization
  7424. * redrawn:
  7425. *
  7426. * <pre>m.event("click", function(d) {
  7427. * data = all.filter(function(k) k.name == d);
  7428. * vis.render();
  7429. * });</pre>
  7430. *
  7431. * The return value of the event handler determines which mark gets re-rendered.
  7432. * Use defs ({@link #def}) to set temporary state from event handlers.
  7433. *
  7434. * <p>The complete set of event types is defined by SVG; see the reference
  7435. * below. The set of supported event types is:<ul>
  7436. *
  7437. * <li>click
  7438. * <li>mousedown
  7439. * <li>mouseup
  7440. * <li>mouseover
  7441. * <li>mousemove
  7442. * <li>mouseout
  7443. *
  7444. * </ul>Since Protovis does not specify any concept of focus, it does not
  7445. * support key events; these should be handled outside the visualization using
  7446. * standard JavaScript. In the future, support for interaction may be extended
  7447. * to support additional event types, particularly those most relevant to
  7448. * interactive visualization, such as selection.
  7449. *
  7450. * <p>TODO In the current implementation, event handlers are not inherited from
  7451. * prototype marks. They must be defined explicitly on each interactive mark. In
  7452. * addition, only one event handler for a given event type can be defined; when
  7453. * specifying multiple event handlers for the same type, only the last one will
  7454. * be used.
  7455. *
  7456. * @see <a href="http://www.w3.org/TR/SVGTiny12/interact.html#SVGEvents">SVG events</a>
  7457. * @param {string} type the event type.
  7458. * @param {function} handler the event handler.
  7459. * @returns {pv.Mark} this.
  7460. */
  7461. pv.Mark.prototype.event = function(type, handler) {
  7462. this.$handlers[type] = pv.functor(handler);
  7463. return this;
  7464. };
  7465. /** @private Evaluates the function <i>f</i> with the specified context. */
  7466. pv.Mark.prototype.context = function(scene, index, f) {
  7467. var proto = pv.Mark.prototype,
  7468. stack = pv.Mark.stack,
  7469. oscene = pv.Mark.scene,
  7470. oindex = proto.index;
  7471. /** @private Sets the context. */
  7472. function apply(scene, index) {
  7473. pv.Mark.scene = scene;
  7474. proto.index = index;
  7475. if (!scene) return;
  7476. var that = scene.mark,
  7477. mark = that,
  7478. ancestors = [];
  7479. /* Set ancestors' scene and index; populate data stack. */
  7480. do {
  7481. ancestors.push(mark);
  7482. stack.push(scene[index].data);
  7483. mark.index = index;
  7484. mark.scene = scene;
  7485. index = scene.parentIndex;
  7486. scene = scene.parent;
  7487. } while (mark = mark.parent);
  7488. /* Set ancestors' scale; requires top-down. */
  7489. for (var i = ancestors.length - 1, k = 1; i > 0; i--) {
  7490. mark = ancestors[i];
  7491. mark.scale = k;
  7492. k *= mark.scene[mark.index].transform.k;
  7493. }
  7494. /* Set children's scene and scale. */
  7495. if (that.children) for (var i = 0, n = that.children.length; i < n; i++) {
  7496. mark = that.children[i];
  7497. mark.scene = that.scene[that.index].children[i];
  7498. mark.scale = k;
  7499. }
  7500. }
  7501. /** @private Clears the context. */
  7502. function clear(scene, index) {
  7503. if (!scene) return;
  7504. var that = scene.mark,
  7505. mark;
  7506. /* Reset children. */
  7507. if (that.children) for (var i = 0, n = that.children.length; i < n; i++) {
  7508. mark = that.children[i];
  7509. delete mark.scene;
  7510. delete mark.scale;
  7511. }
  7512. /* Reset ancestors. */
  7513. mark = that;
  7514. do {
  7515. stack.pop();
  7516. if (mark.parent) {
  7517. delete mark.scene;
  7518. delete mark.scale;
  7519. }
  7520. delete mark.index;
  7521. } while (mark = mark.parent);
  7522. }
  7523. /* Context switch, invoke the function, then switch back. */
  7524. try {
  7525. f.apply(this, stack);
  7526. } finally {
  7527. clear(scene, index);
  7528. apply(oscene, oindex);
  7529. }
  7530. };
  7531. /** @private Execute the event listener, then re-render. */
  7532. pv.Mark.dispatch = function(type, scene, index) {
  7533. var m = scene.mark, p = scene.parent, l = m.$handlers[type];
  7534. if (!l) return p && pv.Mark.dispatch(type, p, scene.parentIndex);
  7535. m.context(scene, index, function() {
  7536. m = l.apply(m, pv.Mark.stack);
  7537. if (m && m.render) m.render();
  7538. });
  7539. return true;
  7540. };
  7541. /**
  7542. * Constructs a new mark anchor with default properties.
  7543. *
  7544. * @class Represents an anchor on a given mark. An anchor is itself a mark, but
  7545. * without a visual representation. It serves only to provide useful default
  7546. * properties that can be inherited by other marks. Each type of mark can define
  7547. * any number of named anchors for convenience. If the concrete mark type does
  7548. * not define an anchor implementation specifically, one will be inherited from
  7549. * the mark's parent class.
  7550. *
  7551. * <p>For example, the bar mark provides anchors for its four sides: left,
  7552. * right, top and bottom. Adding a label to the top anchor of a bar,
  7553. *
  7554. * <pre>bar.anchor("top").add(pv.Label);</pre>
  7555. *
  7556. * will render a text label on the top edge of the bar; the top anchor defines
  7557. * the appropriate position properties (top and left), as well as text-rendering
  7558. * properties for convenience (textAlign and textBaseline).
  7559. *
  7560. * <p>Note that anchors do not <i>inherit</i> from their targets; the positional
  7561. * properties are copied from the scene graph, which guarantees that the anchors
  7562. * are positioned correctly, even if the positional properties are not defined
  7563. * deterministically. (In addition, it also improves performance by avoiding
  7564. * re-evaluating expensive properties.) If you want the anchor to inherit from
  7565. * the target, use {@link pv.Mark#extend} before adding. For example:
  7566. *
  7567. * <pre>bar.anchor("top").extend(bar).add(pv.Label);</pre>
  7568. *
  7569. * The anchor defines it's own positional properties, but other properties (such
  7570. * as the title property, say) can be inherited using the above idiom. Also note
  7571. * that you can override positional properties in the anchor for custom
  7572. * behavior.
  7573. *
  7574. * @extends pv.Mark
  7575. * @param {pv.Mark} target the anchor target.
  7576. */
  7577. pv.Anchor = function(target) {
  7578. pv.Mark.call(this);
  7579. this.target = target;
  7580. this.parent = target.parent;
  7581. };
  7582. pv.Anchor.prototype = pv.extend(pv.Mark)
  7583. .property("name", String);
  7584. /**
  7585. * The anchor name. The set of supported anchor names is dependent on the
  7586. * concrete mark type; see the mark type for details. For example, bars support
  7587. * left, right, top and bottom anchors.
  7588. *
  7589. * <p>While anchor names are typically constants, the anchor name is a true
  7590. * property, which means you can specify a function to compute the anchor name
  7591. * dynamically. For instance, if you wanted to alternate top and bottom anchors,
  7592. * saying
  7593. *
  7594. * <pre>m.anchor(function() (this.index % 2) ? "top" : "bottom").add(pv.Dot);</pre>
  7595. *
  7596. * would have the desired effect.
  7597. *
  7598. * @type string
  7599. * @name pv.Anchor.prototype.name
  7600. */
  7601. /**
  7602. * Returns the anchor target of this mark, if it is derived from an anchor;
  7603. * otherwise returns null. For example, if a label is derived from a bar anchor,
  7604. *
  7605. * <pre>bar.anchor("top").add(pv.Label);</pre>
  7606. *
  7607. * then property functions on the label can refer to the bar via the
  7608. * <tt>anchorTarget</tt> method. This method is also useful for mark types
  7609. * defining properties on custom anchors.
  7610. *
  7611. * @returns {pv.Mark} the anchor target of this mark; possibly null.
  7612. */
  7613. pv.Anchor.prototype.anchorTarget = function() {
  7614. return this.target;
  7615. };
  7616. /**
  7617. * Constructs a new area mark with default properties. Areas are not typically
  7618. * constructed directly, but by adding to a panel or an existing mark via
  7619. * {@link pv.Mark#add}.
  7620. *
  7621. * @class Represents an area mark: the solid area between two series of
  7622. * connected line segments. Unsurprisingly, areas are used most frequently for
  7623. * area charts.
  7624. *
  7625. * <p>Just as a line represents a polyline, the <tt>Area</tt> mark type
  7626. * represents a <i>polygon</i>. However, an area is not an arbitrary polygon;
  7627. * vertices are paired either horizontally or vertically into parallel
  7628. * <i>spans</i>, and each span corresponds to an associated datum. Either the
  7629. * width or the height must be specified, but not both; this determines whether
  7630. * the area is horizontally-oriented or vertically-oriented. Like lines, areas
  7631. * can be stroked and filled with arbitrary colors.
  7632. *
  7633. * <p>See also the <a href="../../api/Area.html">Area guide</a>.
  7634. *
  7635. * @extends pv.Mark
  7636. */
  7637. pv.Area = function() {
  7638. pv.Mark.call(this);
  7639. };
  7640. pv.Area.prototype = pv.extend(pv.Mark)
  7641. .property("width", Number)
  7642. .property("height", Number)
  7643. .property("lineWidth", Number)
  7644. .property("strokeStyle", pv.color)
  7645. .property("fillStyle", pv.color)
  7646. .property("segmented", Boolean)
  7647. .property("interpolate", String)
  7648. .property("tension", Number);
  7649. pv.Area.prototype.type = "area";
  7650. /**
  7651. * The width of a given span, in pixels; used for horizontal spans. If the width
  7652. * is specified, the height property should be 0 (the default). Either the top
  7653. * or bottom property should be used to space the spans vertically, typically as
  7654. * a multiple of the index.
  7655. *
  7656. * @type number
  7657. * @name pv.Area.prototype.width
  7658. */
  7659. /**
  7660. * The height of a given span, in pixels; used for vertical spans. If the height
  7661. * is specified, the width property should be 0 (the default). Either the left
  7662. * or right property should be used to space the spans horizontally, typically
  7663. * as a multiple of the index.
  7664. *
  7665. * @type number
  7666. * @name pv.Area.prototype.height
  7667. */
  7668. /**
  7669. * The width of stroked lines, in pixels; used in conjunction with
  7670. * <tt>strokeStyle</tt> to stroke the perimeter of the area. Unlike the
  7671. * {@link Line} mark type, the entire perimeter is stroked, rather than just one
  7672. * edge. The default value of this property is 1.5, but since the default stroke
  7673. * style is null, area marks are not stroked by default.
  7674. *
  7675. * <p>This property is <i>fixed</i> for non-segmented areas. See
  7676. * {@link pv.Mark}.
  7677. *
  7678. * @type number
  7679. * @name pv.Area.prototype.lineWidth
  7680. */
  7681. /**
  7682. * The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
  7683. * stroke the perimeter of the area. Unlike the {@link Line} mark type, the
  7684. * entire perimeter is stroked, rather than just one edge. The default value of
  7685. * this property is null, meaning areas are not stroked by default.
  7686. *
  7687. * <p>This property is <i>fixed</i> for non-segmented areas. See
  7688. * {@link pv.Mark}.
  7689. *
  7690. * @type string
  7691. * @name pv.Area.prototype.strokeStyle
  7692. * @see pv.color
  7693. */
  7694. /**
  7695. * The area fill style; if non-null, the interior of the polygon forming the
  7696. * area is filled with the specified color. The default value of this property
  7697. * is a categorical color.
  7698. *
  7699. * <p>This property is <i>fixed</i> for non-segmented areas. See
  7700. * {@link pv.Mark}.
  7701. *
  7702. * @type string
  7703. * @name pv.Area.prototype.fillStyle
  7704. * @see pv.color
  7705. */
  7706. /**
  7707. * Whether the area is segmented; whether variations in fill style, stroke
  7708. * style, and the other properties are treated as fixed. Rendering segmented
  7709. * areas is noticeably slower than non-segmented areas.
  7710. *
  7711. * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
  7712. *
  7713. * @type boolean
  7714. * @name pv.Area.prototype.segmented
  7715. */
  7716. /**
  7717. * How to interpolate between values. Linear interpolation ("linear") is the
  7718. * default, producing a straight line between points. For piecewise constant
  7719. * functions (i.e., step functions), either "step-before" or "step-after" can be
  7720. * specified. To draw open uniform b-splines, specify "basis". To draw cardinal
  7721. * splines, specify "cardinal"; see also {@link #tension}.
  7722. *
  7723. * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
  7724. *
  7725. * @type string
  7726. * @name pv.Area.prototype.interpolate
  7727. */
  7728. /**
  7729. * The tension of cardinal splines; used in conjunction with
  7730. * interpolate("cardinal"). A value between 0 and 1 draws cardinal splines with
  7731. * the given tension. In some sense, the tension can be interpreted as the
  7732. * "length" of the tangent; a tension of 1 will yield all zero tangents (i.e.,
  7733. * linear interpolation), and a tension of 0 yields a Catmull-Rom spline. The
  7734. * default value is 0.7.
  7735. *
  7736. * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
  7737. *
  7738. * @type number
  7739. * @name pv.Area.prototype.tension
  7740. */
  7741. /**
  7742. * Default properties for areas. By default, there is no stroke and the fill
  7743. * style is a categorical color.
  7744. *
  7745. * @type pv.Area
  7746. */
  7747. pv.Area.prototype.defaults = new pv.Area()
  7748. .extend(pv.Mark.prototype.defaults)
  7749. .lineWidth(1.5)
  7750. .fillStyle(pv.Colors.category20().by(pv.parent))
  7751. .interpolate("linear")
  7752. .tension(.7);
  7753. /** @private Sets width and height to zero if null. */
  7754. pv.Area.prototype.buildImplied = function(s) {
  7755. if (s.height == null) s.height = 0;
  7756. if (s.width == null) s.width = 0;
  7757. pv.Mark.prototype.buildImplied.call(this, s);
  7758. };
  7759. /** @private Records which properties may be fixed. */
  7760. pv.Area.fixed = {
  7761. lineWidth: 1,
  7762. lineJoin: 1,
  7763. strokeStyle: 1,
  7764. fillStyle: 1,
  7765. segmented: 1,
  7766. interpolate: 1,
  7767. tension: 1
  7768. };
  7769. /**
  7770. * @private Make segmented required, such that this fixed property is always
  7771. * evaluated, even if the first segment is not visible. Also cache which
  7772. * properties are normally fixed.
  7773. */
  7774. pv.Area.prototype.bind = function() {
  7775. pv.Mark.prototype.bind.call(this);
  7776. var binds = this.binds,
  7777. required = binds.required,
  7778. optional = binds.optional;
  7779. for (var i = 0, n = optional.length; i < n; i++) {
  7780. var p = optional[i];
  7781. p.fixed = p.name in pv.Area.fixed;
  7782. if (p.name == "segmented") {
  7783. required.push(p);
  7784. optional.splice(i, 1);
  7785. i--;
  7786. n--;
  7787. }
  7788. }
  7789. /* Cache the original arrays so they can be restored on build. */
  7790. this.binds.$required = required;
  7791. this.binds.$optional = optional;
  7792. };
  7793. /**
  7794. * @private Override the default build behavior such that fixed properties are
  7795. * determined dynamically, based on the value of the (always) fixed segmented
  7796. * property. Any fixed properties are only evaluated on the first instance,
  7797. * although their values are propagated to subsequent instances, so that they
  7798. * are available for property chaining and the like.
  7799. */
  7800. pv.Area.prototype.buildInstance = function(s) {
  7801. var binds = this.binds;
  7802. /* Handle fixed properties on secondary instances. */
  7803. if (this.index) {
  7804. var fixed = binds.fixed;
  7805. /* Determine which properties are fixed. */
  7806. if (!fixed) {
  7807. fixed = binds.fixed = [];
  7808. function f(p) { return !p.fixed || (fixed.push(p), false); }
  7809. binds.required = binds.required.filter(f);
  7810. if (!this.scene[0].segmented) binds.optional = binds.optional.filter(f);
  7811. }
  7812. /* Copy fixed property values from the first instance. */
  7813. for (var i = 0, n = fixed.length; i < n; i++) {
  7814. var p = fixed[i].name;
  7815. s[p] = this.scene[0][p];
  7816. }
  7817. }
  7818. /* Evaluate all properties on the first instance. */
  7819. else {
  7820. binds.required = binds.$required;
  7821. binds.optional = binds.$optional;
  7822. binds.fixed = null;
  7823. }
  7824. pv.Mark.prototype.buildInstance.call(this, s);
  7825. };
  7826. /**
  7827. * Constructs a new area anchor with default properties. Areas support five
  7828. * different anchors:<ul>
  7829. *
  7830. * <li>top
  7831. * <li>left
  7832. * <li>center
  7833. * <li>bottom
  7834. * <li>right
  7835. *
  7836. * </ul>In addition to positioning properties (left, right, top bottom), the
  7837. * anchors support text rendering properties (text-align, text-baseline). Text
  7838. * is rendered to appear inside the area. The area anchor also propagates the
  7839. * interpolate, eccentricity, and tension properties such that an anchored area
  7840. * or line will match positions between control points.
  7841. *
  7842. * <p>For consistency with the other mark types, the anchor positions are
  7843. * defined in terms of their opposite edge. For example, the top anchor defines
  7844. * the bottom property, such that an area added to the top anchor grows upward.
  7845. *
  7846. * @param {string} name the anchor name; either a string or a property function.
  7847. * @returns {pv.Anchor}
  7848. */
  7849. pv.Area.prototype.anchor = function(name) {
  7850. var scene;
  7851. return pv.Mark.prototype.anchor.call(this, name)
  7852. .def("$area.anchor", function() {
  7853. scene = this.scene.target;
  7854. })
  7855. .interpolate(function() {
  7856. return scene[this.index].interpolate;
  7857. })
  7858. .eccentricity(function() {
  7859. return scene[this.index].eccentricity;
  7860. })
  7861. .tension(function() {
  7862. return scene[this.index].tension;
  7863. });
  7864. };
  7865. /**
  7866. * Constructs a new bar mark with default properties. Bars are not typically
  7867. * constructed directly, but by adding to a panel or an existing mark via
  7868. * {@link pv.Mark#add}.
  7869. *
  7870. * @class Represents a bar: an axis-aligned rectangle that can be stroked and
  7871. * filled. Bars are used for many chart types, including bar charts, histograms
  7872. * and Gantt charts. Bars can also be used as decorations, for example to draw a
  7873. * frame border around a panel; in fact, a panel is a special type (a subclass)
  7874. * of bar.
  7875. *
  7876. * <p>Bars can be positioned in several ways. Most commonly, one of the four
  7877. * corners is fixed using two margins, and then the width and height properties
  7878. * determine the extent of the bar relative to this fixed location. For example,
  7879. * using the bottom and left properties fixes the bottom-left corner; the width
  7880. * then extends to the right, while the height extends to the top. As an
  7881. * alternative to the four corners, a bar can be positioned exclusively using
  7882. * margins; this is convenient as an inset from the containing panel, for
  7883. * example. See {@link pv.Mark} for details on the prioritization of redundant
  7884. * positioning properties.
  7885. *
  7886. * <p>See also the <a href="../../api/Bar.html">Bar guide</a>.
  7887. *
  7888. * @extends pv.Mark
  7889. */
  7890. pv.Bar = function() {
  7891. pv.Mark.call(this);
  7892. };
  7893. pv.Bar.prototype = pv.extend(pv.Mark)
  7894. .property("width", Number)
  7895. .property("height", Number)
  7896. .property("lineWidth", Number)
  7897. .property("strokeStyle", pv.color)
  7898. .property("fillStyle", pv.color);
  7899. pv.Bar.prototype.type = "bar";
  7900. /**
  7901. * The width of the bar, in pixels. If the left position is specified, the bar
  7902. * extends rightward from the left edge; if the right position is specified, the
  7903. * bar extends leftward from the right edge.
  7904. *
  7905. * @type number
  7906. * @name pv.Bar.prototype.width
  7907. */
  7908. /**
  7909. * The height of the bar, in pixels. If the bottom position is specified, the
  7910. * bar extends upward from the bottom edge; if the top position is specified,
  7911. * the bar extends downward from the top edge.
  7912. *
  7913. * @type number
  7914. * @name pv.Bar.prototype.height
  7915. */
  7916. /**
  7917. * The width of stroked lines, in pixels; used in conjunction with
  7918. * <tt>strokeStyle</tt> to stroke the bar's border.
  7919. *
  7920. * @type number
  7921. * @name pv.Bar.prototype.lineWidth
  7922. */
  7923. /**
  7924. * The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
  7925. * stroke the bar's border. The default value of this property is null, meaning
  7926. * bars are not stroked by default.
  7927. *
  7928. * @type string
  7929. * @name pv.Bar.prototype.strokeStyle
  7930. * @see pv.color
  7931. */
  7932. /**
  7933. * The bar fill style; if non-null, the interior of the bar is filled with the
  7934. * specified color. The default value of this property is a categorical color.
  7935. *
  7936. * @type string
  7937. * @name pv.Bar.prototype.fillStyle
  7938. * @see pv.color
  7939. */
  7940. /**
  7941. * Default properties for bars. By default, there is no stroke and the fill
  7942. * style is a categorical color.
  7943. *
  7944. * @type pv.Bar
  7945. */
  7946. pv.Bar.prototype.defaults = new pv.Bar()
  7947. .extend(pv.Mark.prototype.defaults)
  7948. .lineWidth(1.5)
  7949. .fillStyle(pv.Colors.category20().by(pv.parent));
  7950. /**
  7951. * Constructs a new dot mark with default properties. Dots are not typically
  7952. * constructed directly, but by adding to a panel or an existing mark via
  7953. * {@link pv.Mark#add}.
  7954. *
  7955. * @class Represents a dot; a dot is simply a sized glyph centered at a given
  7956. * point that can also be stroked and filled. The <tt>size</tt> property is
  7957. * proportional to the area of the rendered glyph to encourage meaningful visual
  7958. * encodings. Dots can visually encode up to eight dimensions of data, though
  7959. * this may be unwise due to integrality. See {@link pv.Mark} for details on the
  7960. * prioritization of redundant positioning properties.
  7961. *
  7962. * <p>See also the <a href="../../api/Dot.html">Dot guide</a>.
  7963. *
  7964. * @extends pv.Mark
  7965. */
  7966. pv.Dot = function() {
  7967. pv.Mark.call(this);
  7968. };
  7969. pv.Dot.prototype = pv.extend(pv.Mark)
  7970. .property("size", Number)
  7971. .property("radius", Number)
  7972. .property("shape", String)
  7973. .property("angle", Number)
  7974. .property("lineWidth", Number)
  7975. .property("strokeStyle", pv.color)
  7976. .property("fillStyle", pv.color);
  7977. pv.Dot.prototype.type = "dot";
  7978. /**
  7979. * The size of the dot, in square pixels. Square pixels are used such that the
  7980. * area of the dot is linearly proportional to the value of the size property,
  7981. * facilitating representative encodings.
  7982. *
  7983. * @see #radius
  7984. * @type number
  7985. * @name pv.Dot.prototype.size
  7986. */
  7987. /**
  7988. * The radius of the dot, in pixels. This is an alternative to using
  7989. * {@link #size}.
  7990. *
  7991. * @see #size
  7992. * @type number
  7993. * @name pv.Dot.prototype.radius
  7994. */
  7995. /**
  7996. * The shape name. Several shapes are supported:<ul>
  7997. *
  7998. * <li>cross
  7999. * <li>triangle
  8000. * <li>diamond
  8001. * <li>square
  8002. * <li>circle
  8003. * <li>tick
  8004. * <li>bar
  8005. *
  8006. * </ul>These shapes can be further changed using the {@link #angle} property;
  8007. * for instance, a cross can be turned into a plus by rotating. Similarly, the
  8008. * tick, which is vertical by default, can be rotated horizontally. Note that
  8009. * some shapes (cross and tick) do not have interior areas, and thus do not
  8010. * support fill style meaningfully.
  8011. *
  8012. * <p>Note: it may be more natural to use the {@link pv.Rule} mark for
  8013. * horizontal and vertical ticks. The tick shape is only necessary if angled
  8014. * ticks are needed.
  8015. *
  8016. * @type string
  8017. * @name pv.Dot.prototype.shape
  8018. */
  8019. /**
  8020. * The rotation angle, in radians. Used to rotate shapes, such as to turn a
  8021. * cross into a plus.
  8022. *
  8023. * @type number
  8024. * @name pv.Dot.prototype.angle
  8025. */
  8026. /**
  8027. * The width of stroked lines, in pixels; used in conjunction with
  8028. * <tt>strokeStyle</tt> to stroke the dot's shape.
  8029. *
  8030. * @type number
  8031. * @name pv.Dot.prototype.lineWidth
  8032. */
  8033. /**
  8034. * The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
  8035. * stroke the dot's shape. The default value of this property is a categorical
  8036. * color.
  8037. *
  8038. * @type string
  8039. * @name pv.Dot.prototype.strokeStyle
  8040. * @see pv.color
  8041. */
  8042. /**
  8043. * The fill style; if non-null, the interior of the dot is filled with the
  8044. * specified color. The default value of this property is null, meaning dots are
  8045. * not filled by default.
  8046. *
  8047. * @type string
  8048. * @name pv.Dot.prototype.fillStyle
  8049. * @see pv.color
  8050. */
  8051. /**
  8052. * Default properties for dots. By default, there is no fill and the stroke
  8053. * style is a categorical color. The default shape is "circle" with size 20.
  8054. *
  8055. * @type pv.Dot
  8056. */
  8057. pv.Dot.prototype.defaults = new pv.Dot()
  8058. .extend(pv.Mark.prototype.defaults)
  8059. .size(20)
  8060. .shape("circle")
  8061. .lineWidth(1.5)
  8062. .strokeStyle(pv.Colors.category10().by(pv.parent));
  8063. /**
  8064. * Constructs a new dot anchor with default properties. Dots support five
  8065. * different anchors:<ul>
  8066. *
  8067. * <li>top
  8068. * <li>left
  8069. * <li>center
  8070. * <li>bottom
  8071. * <li>right
  8072. *
  8073. * </ul>In addition to positioning properties (left, right, top bottom), the
  8074. * anchors support text rendering properties (text-align, text-baseline). Text is
  8075. * rendered to appear outside the dot. Note that this behavior is different from
  8076. * other mark anchors, which default to rendering text <i>inside</i> the mark.
  8077. *
  8078. * <p>For consistency with the other mark types, the anchor positions are
  8079. * defined in terms of their opposite edge. For example, the top anchor defines
  8080. * the bottom property, such that a bar added to the top anchor grows upward.
  8081. *
  8082. * @param {string} name the anchor name; either a string or a property function.
  8083. * @returns {pv.Anchor}
  8084. */
  8085. pv.Dot.prototype.anchor = function(name) {
  8086. var scene;
  8087. return pv.Mark.prototype.anchor.call(this, name)
  8088. .def("$wedge.anchor", function() {
  8089. scene = this.scene.target;
  8090. })
  8091. .left(function() {
  8092. var s = scene[this.index];
  8093. switch (this.name()) {
  8094. case "bottom":
  8095. case "top":
  8096. case "center": return s.left;
  8097. case "left": return null;
  8098. }
  8099. return s.left + s.radius;
  8100. })
  8101. .right(function() {
  8102. var s = scene[this.index];
  8103. return this.name() == "left" ? s.right + s.radius : null;
  8104. })
  8105. .top(function() {
  8106. var s = scene[this.index];
  8107. switch (this.name()) {
  8108. case "left":
  8109. case "right":
  8110. case "center": return s.top;
  8111. case "top": return null;
  8112. }
  8113. return s.top + s.radius;
  8114. })
  8115. .bottom(function() {
  8116. var s = scene[this.index];
  8117. return this.name() == "top" ? s.bottom + s.radius : null;
  8118. })
  8119. .textAlign(function() {
  8120. switch (this.name()) {
  8121. case "left": return "right";
  8122. case "bottom":
  8123. case "top":
  8124. case "center": return "center";
  8125. }
  8126. return "left";
  8127. })
  8128. .textBaseline(function() {
  8129. switch (this.name()) {
  8130. case "right":
  8131. case "left":
  8132. case "center": return "middle";
  8133. case "bottom": return "top";
  8134. }
  8135. return "bottom";
  8136. });
  8137. };
  8138. /** @private Sets radius based on size or vice versa. */
  8139. pv.Dot.prototype.buildImplied = function(s) {
  8140. if (s.radius == null) s.radius = Math.sqrt(s.size);
  8141. else if (s.size == null) s.size = s.radius * s.radius;
  8142. pv.Mark.prototype.buildImplied.call(this, s);
  8143. };
  8144. /**
  8145. * Constructs a new label mark with default properties. Labels are not typically
  8146. * constructed directly, but by adding to a panel or an existing mark via
  8147. * {@link pv.Mark#add}.
  8148. *
  8149. * @class Represents a text label, allowing textual annotation of other marks or
  8150. * arbitrary text within the visualization. The character data must be plain
  8151. * text (unicode), though the text can be styled using the {@link #font}
  8152. * property. If rich text is needed, external HTML elements can be overlaid on
  8153. * the canvas by hand.
  8154. *
  8155. * <p>Labels are positioned using the box model, similarly to {@link Dot}. Thus,
  8156. * a label has no width or height, but merely a text anchor location. The text
  8157. * is positioned relative to this anchor location based on the
  8158. * {@link #textAlign}, {@link #textBaseline} and {@link #textMargin} properties.
  8159. * Furthermore, the text may be rotated using {@link #textAngle}.
  8160. *
  8161. * <p>Labels ignore events, so as to not interfere with event handlers on
  8162. * underlying marks, such as bars. In the future, we may support event handlers
  8163. * on labels.
  8164. *
  8165. * <p>See also the <a href="../../api/Label.html">Label guide</a>.
  8166. *
  8167. * @extends pv.Mark
  8168. */
  8169. pv.Label = function() {
  8170. pv.Mark.call(this);
  8171. };
  8172. pv.Label.prototype = pv.extend(pv.Mark)
  8173. .property("text", String)
  8174. .property("font", String)
  8175. .property("textAngle", Number)
  8176. .property("textStyle", pv.color)
  8177. .property("textAlign", String)
  8178. .property("textBaseline", String)
  8179. .property("textMargin", Number)
  8180. .property("textDecoration", String)
  8181. .property("textShadow", String);
  8182. pv.Label.prototype.type = "label";
  8183. /**
  8184. * The character data to render; a string. The default value of the text
  8185. * property is the identity function, meaning the label's associated datum will
  8186. * be rendered using its <tt>toString</tt>.
  8187. *
  8188. * @type string
  8189. * @name pv.Label.prototype.text
  8190. */
  8191. /**
  8192. * The font format, per the CSS Level 2 specification. The default font is "10px
  8193. * sans-serif", for consistency with the HTML 5 canvas element specification.
  8194. * Note that since text is not wrapped, any line-height property will be
  8195. * ignored. The other font-style, font-variant, font-weight, font-size and
  8196. * font-family properties are supported.
  8197. *
  8198. * @see <a href="http://www.w3.org/TR/CSS2/fonts.html#font-shorthand">CSS2 fonts</a>
  8199. * @type string
  8200. * @name pv.Label.prototype.font
  8201. */
  8202. /**
  8203. * The rotation angle, in radians. Text is rotated clockwise relative to the
  8204. * anchor location. For example, with the default left alignment, an angle of
  8205. * Math.PI / 2 causes text to proceed downwards. The default angle is zero.
  8206. *
  8207. * @type number
  8208. * @name pv.Label.prototype.textAngle
  8209. */
  8210. /**
  8211. * The text color. The name "textStyle" is used for consistency with "fillStyle"
  8212. * and "strokeStyle", although it might be better to rename this property (and
  8213. * perhaps use the same name as "strokeStyle"). The default color is black.
  8214. *
  8215. * @type string
  8216. * @name pv.Label.prototype.textStyle
  8217. * @see pv.color
  8218. */
  8219. /**
  8220. * The horizontal text alignment. One of:<ul>
  8221. *
  8222. * <li>left
  8223. * <li>center
  8224. * <li>right
  8225. *
  8226. * </ul>The default horizontal alignment is left.
  8227. *
  8228. * @type string
  8229. * @name pv.Label.prototype.textAlign
  8230. */
  8231. /**
  8232. * The vertical text alignment. One of:<ul>
  8233. *
  8234. * <li>top
  8235. * <li>middle
  8236. * <li>bottom
  8237. *
  8238. * </ul>The default vertical alignment is bottom.
  8239. *
  8240. * @type string
  8241. * @name pv.Label.prototype.textBaseline
  8242. */
  8243. /**
  8244. * The text margin; may be specified in pixels, or in font-dependent units (such
  8245. * as ".1ex"). The margin can be used to pad text away from its anchor location,
  8246. * in a direction dependent on the horizontal and vertical alignment
  8247. * properties. For example, if the text is left- and middle-aligned, the margin
  8248. * shifts the text to the right. The default margin is 3 pixels.
  8249. *
  8250. * @type number
  8251. * @name pv.Label.prototype.textMargin
  8252. */
  8253. /**
  8254. * A list of shadow effects to be applied to text, per the CSS Text Level 3
  8255. * text-shadow property. An example specification is "0.1em 0.1em 0.1em
  8256. * rgba(0,0,0,.5)"; the first length is the horizontal offset, the second the
  8257. * vertical offset, and the third the blur radius.
  8258. *
  8259. * @see <a href="http://www.w3.org/TR/css3-text/#text-shadow">CSS3 text</a>
  8260. * @type string
  8261. * @name pv.Label.prototype.textShadow
  8262. */
  8263. /**
  8264. * A list of decoration to be applied to text, per the CSS Text Level 3
  8265. * text-decoration property. An example specification is "underline".
  8266. *
  8267. * @see <a href="http://www.w3.org/TR/css3-text/#text-decoration">CSS3 text</a>
  8268. * @type string
  8269. * @name pv.Label.prototype.textDecoration
  8270. */
  8271. /**
  8272. * Default properties for labels. See the individual properties for the default
  8273. * values.
  8274. *
  8275. * @type pv.Label
  8276. */
  8277. pv.Label.prototype.defaults = new pv.Label()
  8278. .extend(pv.Mark.prototype.defaults)
  8279. .events("none")
  8280. .text(pv.identity)
  8281. .font("10px sans-serif")
  8282. .textAngle(0)
  8283. .textStyle("black")
  8284. .textAlign("left")
  8285. .textBaseline("bottom")
  8286. .textMargin(3);
  8287. /**
  8288. * Constructs a new line mark with default properties. Lines are not typically
  8289. * constructed directly, but by adding to a panel or an existing mark via
  8290. * {@link pv.Mark#add}.
  8291. *
  8292. * @class Represents a series of connected line segments, or <i>polyline</i>,
  8293. * that can be stroked with a configurable color and thickness. Each
  8294. * articulation point in the line corresponds to a datum; for <i>n</i> points,
  8295. * <i>n</i>-1 connected line segments are drawn. The point is positioned using
  8296. * the box model. Arbitrary paths are also possible, allowing radar plots and
  8297. * other custom visualizations.
  8298. *
  8299. * <p>Like areas, lines can be stroked and filled with arbitrary colors. In most
  8300. * cases, lines are only stroked, but the fill style can be used to construct
  8301. * arbitrary polygons.
  8302. *
  8303. * <p>See also the <a href="../../api/Line.html">Line guide</a>.
  8304. *
  8305. * @extends pv.Mark
  8306. */
  8307. pv.Line = function() {
  8308. pv.Mark.call(this);
  8309. };
  8310. pv.Line.prototype = pv.extend(pv.Mark)
  8311. .property("lineWidth", Number)
  8312. .property("lineJoin", String)
  8313. .property("strokeStyle", pv.color)
  8314. .property("fillStyle", pv.color)
  8315. .property("segmented", Boolean)
  8316. .property("interpolate", String)
  8317. .property("eccentricity", Number)
  8318. .property("tension", Number);
  8319. pv.Line.prototype.type = "line";
  8320. /**
  8321. * The width of stroked lines, in pixels; used in conjunction with
  8322. * <tt>strokeStyle</tt> to stroke the line.
  8323. *
  8324. * @type number
  8325. * @name pv.Line.prototype.lineWidth
  8326. */
  8327. /**
  8328. * The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
  8329. * stroke the line. The default value of this property is a categorical color.
  8330. *
  8331. * @type string
  8332. * @name pv.Line.prototype.strokeStyle
  8333. * @see pv.color
  8334. */
  8335. /**
  8336. * The type of corners where two lines meet. Accepted values are "bevel",
  8337. * "round" and "miter". The default value is "miter".
  8338. *
  8339. * <p>For segmented lines, only "miter" joins and "linear" interpolation are
  8340. * currently supported. Any other value, including null, will disable joins,
  8341. * producing disjoint line segments. Note that the miter joins must be computed
  8342. * manually (at least in the current SVG renderer); since this calculation may
  8343. * be expensive and unnecessary for small lines, specifying null can improve
  8344. * performance significantly.
  8345. *
  8346. * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
  8347. *
  8348. * @type string
  8349. * @name pv.Line.prototype.lineJoin
  8350. */
  8351. /**
  8352. * The line fill style; if non-null, the interior of the line is closed and
  8353. * filled with the specified color. The default value of this property is a
  8354. * null, meaning that lines are not filled by default.
  8355. *
  8356. * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
  8357. *
  8358. * @type string
  8359. * @name pv.Line.prototype.fillStyle
  8360. * @see pv.color
  8361. */
  8362. /**
  8363. * Whether the line is segmented; whether variations in stroke style, line width
  8364. * and the other properties are treated as fixed. Rendering segmented lines is
  8365. * noticeably slower than non-segmented lines.
  8366. *
  8367. * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
  8368. *
  8369. * @type boolean
  8370. * @name pv.Line.prototype.segmented
  8371. */
  8372. /**
  8373. * How to interpolate between values. Linear interpolation ("linear") is the
  8374. * default, producing a straight line between points. For piecewise constant
  8375. * functions (i.e., step functions), either "step-before" or "step-after" can be
  8376. * specified. To draw a clockwise circular arc between points, specify "polar";
  8377. * to draw a counterclockwise circular arc between points, specify
  8378. * "polar-reverse". To draw open uniform b-splines, specify "basis". To draw
  8379. * cardinal splines, specify "cardinal"; see also {@link #tension}.
  8380. *
  8381. * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
  8382. *
  8383. * @type string
  8384. * @name pv.Line.prototype.interpolate
  8385. */
  8386. /**
  8387. * The eccentricity of polar line segments; used in conjunction with
  8388. * interpolate("polar"). The default value of 0 means that line segments are
  8389. * drawn as circular arcs. A value of 1 draws a straight line. A value between 0
  8390. * and 1 draws an elliptical arc with the given eccentricity.
  8391. *
  8392. * @type number
  8393. * @name pv.Line.prototype.eccentricity
  8394. */
  8395. /**
  8396. * The tension of cardinal splines; used in conjunction with
  8397. * interpolate("cardinal"). A value between 0 and 1 draws cardinal splines with
  8398. * the given tension. In some sense, the tension can be interpreted as the
  8399. * "length" of the tangent; a tension of 1 will yield all zero tangents (i.e.,
  8400. * linear interpolation), and a tension of 0 yields a Catmull-Rom spline. The
  8401. * default value is 0.7.
  8402. *
  8403. * <p>This property is <i>fixed</i>. See {@link pv.Mark}.
  8404. *
  8405. * @type number
  8406. * @name pv.Line.prototype.tension
  8407. */
  8408. /**
  8409. * Default properties for lines. By default, there is no fill and the stroke
  8410. * style is a categorical color. The default interpolation is linear.
  8411. *
  8412. * @type pv.Line
  8413. */
  8414. pv.Line.prototype.defaults = new pv.Line()
  8415. .extend(pv.Mark.prototype.defaults)
  8416. .lineJoin("miter")
  8417. .lineWidth(1.5)
  8418. .strokeStyle(pv.Colors.category10().by(pv.parent))
  8419. .interpolate("linear")
  8420. .eccentricity(0)
  8421. .tension(.7);
  8422. /** @private Reuse Area's implementation for segmented bind & build. */
  8423. pv.Line.prototype.bind = pv.Area.prototype.bind;
  8424. pv.Line.prototype.buildInstance = pv.Area.prototype.buildInstance;
  8425. /**
  8426. * Constructs a new line anchor with default properties. Lines support five
  8427. * different anchors:<ul>
  8428. *
  8429. * <li>top
  8430. * <li>left
  8431. * <li>center
  8432. * <li>bottom
  8433. * <li>right
  8434. *
  8435. * </ul>In addition to positioning properties (left, right, top bottom), the
  8436. * anchors support text rendering properties (text-align, text-baseline). Text is
  8437. * rendered to appear outside the line. Note that this behavior is different
  8438. * from other mark anchors, which default to rendering text <i>inside</i> the
  8439. * mark.
  8440. *
  8441. * <p>For consistency with the other mark types, the anchor positions are
  8442. * defined in terms of their opposite edge. For example, the top anchor defines
  8443. * the bottom property, such that a bar added to the top anchor grows upward.
  8444. *
  8445. * @param {string} name the anchor name; either a string or a property function.
  8446. * @returns {pv.Anchor}
  8447. */
  8448. pv.Line.prototype.anchor = function(name) {
  8449. return pv.Area.prototype.anchor.call(this, name)
  8450. .textAlign(function(d) {
  8451. switch (this.name()) {
  8452. case "left": return "right";
  8453. case "bottom":
  8454. case "top":
  8455. case "center": return "center";
  8456. case "right": return "left";
  8457. }
  8458. })
  8459. .textBaseline(function(d) {
  8460. switch (this.name()) {
  8461. case "right":
  8462. case "left":
  8463. case "center": return "middle";
  8464. case "top": return "bottom";
  8465. case "bottom": return "top";
  8466. }
  8467. });
  8468. };
  8469. /**
  8470. * Constructs a new rule with default properties. Rules are not typically
  8471. * constructed directly, but by adding to a panel or an existing mark via
  8472. * {@link pv.Mark#add}.
  8473. *
  8474. * @class Represents a horizontal or vertical rule. Rules are frequently used
  8475. * for axes and grid lines. For example, specifying only the bottom property
  8476. * draws horizontal rules, while specifying only the left draws vertical
  8477. * rules. Rules can also be used as thin bars. The visual style is controlled in
  8478. * the same manner as lines.
  8479. *
  8480. * <p>Rules are positioned exclusively the standard box model properties. The
  8481. * following combinations of properties are supported:
  8482. *
  8483. * <table>
  8484. * <thead><th style="width:12em;">Properties</th><th>Orientation</th></thead>
  8485. * <tbody>
  8486. * <tr><td>left</td><td>vertical</td></tr>
  8487. * <tr><td>right</td><td>vertical</td></tr>
  8488. * <tr><td>left, bottom, top</td><td>vertical</td></tr>
  8489. * <tr><td>right, bottom, top</td><td>vertical</td></tr>
  8490. * <tr><td>top</td><td>horizontal</td></tr>
  8491. * <tr><td>bottom</td><td>horizontal</td></tr>
  8492. * <tr><td>top, left, right</td><td>horizontal</td></tr>
  8493. * <tr><td>bottom, left, right</td><td>horizontal</td></tr>
  8494. * <tr><td>left, top, height</td><td>vertical</td></tr>
  8495. * <tr><td>left, bottom, height</td><td>vertical</td></tr>
  8496. * <tr><td>right, top, height</td><td>vertical</td></tr>
  8497. * <tr><td>right, bottom, height</td><td>vertical</td></tr>
  8498. * <tr><td>left, top, width</td><td>horizontal</td></tr>
  8499. * <tr><td>left, bottom, width</td><td>horizontal</td></tr>
  8500. * <tr><td>right, top, width</td><td>horizontal</td></tr>
  8501. * <tr><td>right, bottom, width</td><td>horizontal</td></tr>
  8502. * </tbody>
  8503. * </table>
  8504. *
  8505. * <p>Small rules can be used as tick marks; alternatively, a {@link Dot} with
  8506. * the "tick" shape can be used.
  8507. *
  8508. * <p>See also the <a href="../../api/Rule.html">Rule guide</a>.
  8509. *
  8510. * @see pv.Line
  8511. * @extends pv.Mark
  8512. */
  8513. pv.Rule = function() {
  8514. pv.Mark.call(this);
  8515. };
  8516. pv.Rule.prototype = pv.extend(pv.Mark)
  8517. .property("width", Number)
  8518. .property("height", Number)
  8519. .property("lineWidth", Number)
  8520. .property("strokeStyle", pv.color);
  8521. pv.Rule.prototype.type = "rule";
  8522. /**
  8523. * The width of the rule, in pixels. If the left position is specified, the rule
  8524. * extends rightward from the left edge; if the right position is specified, the
  8525. * rule extends leftward from the right edge.
  8526. *
  8527. * @type number
  8528. * @name pv.Rule.prototype.width
  8529. */
  8530. /**
  8531. * The height of the rule, in pixels. If the bottom position is specified, the
  8532. * rule extends upward from the bottom edge; if the top position is specified,
  8533. * the rule extends downward from the top edge.
  8534. *
  8535. * @type number
  8536. * @name pv.Rule.prototype.height
  8537. */
  8538. /**
  8539. * The width of stroked lines, in pixels; used in conjunction with
  8540. * <tt>strokeStyle</tt> to stroke the rule. The default value is 1 pixel.
  8541. *
  8542. * @type number
  8543. * @name pv.Rule.prototype.lineWidth
  8544. */
  8545. /**
  8546. * The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
  8547. * stroke the rule. The default value of this property is black.
  8548. *
  8549. * @type string
  8550. * @name pv.Rule.prototype.strokeStyle
  8551. * @see pv.color
  8552. */
  8553. /**
  8554. * Default properties for rules. By default, a single-pixel black line is
  8555. * stroked.
  8556. *
  8557. * @type pv.Rule
  8558. */
  8559. pv.Rule.prototype.defaults = new pv.Rule()
  8560. .extend(pv.Mark.prototype.defaults)
  8561. .lineWidth(1)
  8562. .strokeStyle("black")
  8563. .antialias(false);
  8564. /**
  8565. * Constructs a new rule anchor with default properties. Rules support five
  8566. * different anchors:<ul>
  8567. *
  8568. * <li>top
  8569. * <li>left
  8570. * <li>center
  8571. * <li>bottom
  8572. * <li>right
  8573. *
  8574. * </ul>In addition to positioning properties (left, right, top bottom), the
  8575. * anchors support text rendering properties (text-align, text-baseline). Text is
  8576. * rendered to appear outside the rule. Note that this behavior is different
  8577. * from other mark anchors, which default to rendering text <i>inside</i> the
  8578. * mark.
  8579. *
  8580. * <p>For consistency with the other mark types, the anchor positions are
  8581. * defined in terms of their opposite edge. For example, the top anchor defines
  8582. * the bottom property, such that a bar added to the top anchor grows upward.
  8583. *
  8584. * @param {string} name the anchor name; either a string or a property function.
  8585. * @returns {pv.Anchor}
  8586. */
  8587. pv.Rule.prototype.anchor = pv.Line.prototype.anchor;
  8588. /** @private Sets width or height based on orientation. */
  8589. pv.Rule.prototype.buildImplied = function(s) {
  8590. var l = s.left, r = s.right, t = s.top, b = s.bottom;
  8591. /* Determine horizontal or vertical orientation. */
  8592. if ((s.width != null)
  8593. || ((l == null) && (r == null))
  8594. || ((r != null) && (l != null))) {
  8595. s.height = 0;
  8596. } else {
  8597. s.width = 0;
  8598. }
  8599. pv.Mark.prototype.buildImplied.call(this, s);
  8600. };
  8601. /**
  8602. * Constructs a new, empty panel with default properties. Panels, with the
  8603. * exception of the root panel, are not typically constructed directly; instead,
  8604. * they are added to an existing panel or mark via {@link pv.Mark#add}.
  8605. *
  8606. * @class Represents a container mark. Panels allow repeated or nested
  8607. * structures, commonly used in small multiple displays where a small
  8608. * visualization is tiled to facilitate comparison across one or more
  8609. * dimensions. Other types of visualizations may benefit from repeated and
  8610. * possibly overlapping structure as well, such as stacked area charts. Panels
  8611. * can also offset the position of marks to provide padding from surrounding
  8612. * content.
  8613. *
  8614. * <p>All Protovis displays have at least one panel; this is the root panel to
  8615. * which marks are rendered. The box model properties (four margins, width and
  8616. * height) are used to offset the positions of contained marks. The data
  8617. * property determines the panel count: a panel is generated once per associated
  8618. * datum. When nested panels are used, property functions can declare additional
  8619. * arguments to access the data associated with enclosing panels.
  8620. *
  8621. * <p>Panels can be rendered inline, facilitating the creation of sparklines.
  8622. * This allows designers to reuse browser layout features, such as text flow and
  8623. * tables; designers can also overlay HTML elements such as rich text and
  8624. * images.
  8625. *
  8626. * <p>All panels have a <tt>children</tt> array (possibly empty) containing the
  8627. * child marks in the order they were added. Panels also have a <tt>root</tt>
  8628. * field which points to the root (outermost) panel; the root panel's root field
  8629. * points to itself.
  8630. *
  8631. * <p>See also the <a href="../../api/">Protovis guide</a>.
  8632. *
  8633. * @extends pv.Bar
  8634. */
  8635. pv.Panel = function() {
  8636. pv.Bar.call(this);
  8637. /**
  8638. * The child marks; zero or more {@link pv.Mark}s in the order they were
  8639. * added.
  8640. *
  8641. * @see #add
  8642. * @type pv.Mark[]
  8643. */
  8644. this.children = [];
  8645. this.root = this;
  8646. /**
  8647. * The internal $dom field is set by the Protovis loader; see lang/init.js. It
  8648. * refers to the script element that contains the Protovis specification, so
  8649. * that the panel knows where in the DOM to insert the generated SVG element.
  8650. *
  8651. * @private
  8652. */
  8653. this.$dom = pv.$ && pv.$.s;
  8654. };
  8655. pv.Panel.prototype = pv.extend(pv.Bar)
  8656. .property("transform")
  8657. .property("overflow", String)
  8658. .property("canvas", function(c) {
  8659. return (typeof c == "string")
  8660. ? document.getElementById(c)
  8661. : c; // assume that c is the passed-in element
  8662. });
  8663. pv.Panel.prototype.type = "panel";
  8664. /**
  8665. * The canvas element; either the string ID of the canvas element in the current
  8666. * document, or a reference to the canvas element itself. If null, a canvas
  8667. * element will be created and inserted into the document at the location of the
  8668. * script element containing the current Protovis specification. This property
  8669. * only applies to root panels and is ignored on nested panels.
  8670. *
  8671. * <p>Note: the "canvas" element here refers to a <tt>div</tt> (or other suitable
  8672. * HTML container element), <i>not</i> a <tt>canvas</tt> element. The name of
  8673. * this property is a historical anachronism from the first implementation that
  8674. * used HTML 5 canvas, rather than SVG.
  8675. *
  8676. * @type string
  8677. * @name pv.Panel.prototype.canvas
  8678. */
  8679. /**
  8680. * Specifies whether child marks are clipped when they overflow this panel.
  8681. * This affects the clipping of all this panel's descendant marks.
  8682. *
  8683. * @type string
  8684. * @name pv.Panel.prototype.overflow
  8685. * @see <a href="http://www.w3.org/TR/CSS2/visufx.html#overflow">CSS2</a>
  8686. */
  8687. /**
  8688. * The transform to be applied to child marks. The default transform is
  8689. * identity, which has no effect. Note that the panel's own fill and stroke are
  8690. * not affected by the transform, and panel's transform only affects the
  8691. * <tt>scale</tt> of child marks, not the panel itself.
  8692. *
  8693. * @type pv.Transform
  8694. * @name pv.Panel.prototype.transform
  8695. * @see pv.Mark#scale
  8696. */
  8697. /**
  8698. * Default properties for panels. By default, the margins are zero, the fill
  8699. * style is transparent.
  8700. *
  8701. * @type pv.Panel
  8702. */
  8703. pv.Panel.prototype.defaults = new pv.Panel()
  8704. .extend(pv.Bar.prototype.defaults)
  8705. .fillStyle(null) // override Bar default
  8706. .overflow("visible");
  8707. /**
  8708. * Returns an anchor with the specified name. This method is overridden such
  8709. * that adding to a panel's anchor adds to the panel, rather than to the panel's
  8710. * parent.
  8711. *
  8712. * @param {string} name the anchor name; either a string or a property function.
  8713. * @returns {pv.Anchor} the new anchor.
  8714. */
  8715. pv.Panel.prototype.anchor = function(name) {
  8716. var anchor = pv.Bar.prototype.anchor.call(this, name);
  8717. anchor.parent = this;
  8718. return anchor;
  8719. };
  8720. /**
  8721. * Adds a new mark of the specified type to this panel. Unlike the normal
  8722. * {@link Mark#add} behavior, adding a mark to a panel does not cause the mark
  8723. * to inherit from the panel. Since the contained marks are offset by the panel
  8724. * margins already, inheriting properties is generally undesirable; of course,
  8725. * it is always possible to change this behavior by calling {@link Mark#extend}
  8726. * explicitly.
  8727. *
  8728. * @param {function} type the type of the new mark to add.
  8729. * @returns {pv.Mark} the new mark.
  8730. */
  8731. pv.Panel.prototype.add = function(type) {
  8732. var child = new type();
  8733. child.parent = this;
  8734. child.root = this.root;
  8735. child.childIndex = this.children.length;
  8736. this.children.push(child);
  8737. return child;
  8738. };
  8739. /** @private Bind this panel, then any child marks recursively. */
  8740. pv.Panel.prototype.bind = function() {
  8741. pv.Mark.prototype.bind.call(this);
  8742. for (var i = 0; i < this.children.length; i++) {
  8743. this.children[i].bind();
  8744. }
  8745. };
  8746. /**
  8747. * @private Evaluates all of the properties for this panel for the specified
  8748. * instance <tt>s</tt> in the scene graph, including recursively building the
  8749. * scene graph for child marks.
  8750. *
  8751. * @param s a node in the scene graph; the instance of the panel to build.
  8752. * @see Mark#scene
  8753. */
  8754. pv.Panel.prototype.buildInstance = function(s) {
  8755. pv.Bar.prototype.buildInstance.call(this, s);
  8756. if (!s.visible) return;
  8757. if (!s.children) s.children = [];
  8758. /*
  8759. * Multiply the current scale factor by this panel's transform. Also clear the
  8760. * default index as we recurse into child marks; it will be reset to the
  8761. * current index when the next panel instance is built.
  8762. */
  8763. var scale = this.scale * s.transform.k, child, n = this.children.length;
  8764. pv.Mark.prototype.index = -1;
  8765. /*
  8766. * Build each child, passing in the parent (this panel) scene graph node. The
  8767. * child mark's scene is initialized from the corresponding entry in the
  8768. * existing scene graph, such that properties from the previous build can be
  8769. * reused; this is largely to facilitate the recycling of SVG elements.
  8770. */
  8771. for (var i = 0; i < n; i++) {
  8772. child = this.children[i];
  8773. child.scene = s.children[i]; // possibly undefined
  8774. child.scale = scale;
  8775. child.build();
  8776. }
  8777. /*
  8778. * Once the child marks have been built, the new scene graph nodes are removed
  8779. * from the child marks and placed into the scene graph. The nodes cannot
  8780. * remain on the child nodes because this panel (or a parent panel) may be
  8781. * instantiated multiple times!
  8782. */
  8783. for (var i = 0; i < n; i++) {
  8784. child = this.children[i];
  8785. s.children[i] = child.scene;
  8786. delete child.scene;
  8787. delete child.scale;
  8788. }
  8789. /* Delete any expired child scenes. */
  8790. s.children.length = n;
  8791. };
  8792. /**
  8793. * @private Computes the implied properties for this panel for the specified
  8794. * instance <tt>s</tt> in the scene graph. Panels have two implied
  8795. * properties:<ul>
  8796. *
  8797. * <li>The <tt>canvas</tt> property references the DOM element, typically a DIV,
  8798. * that contains the SVG element that is used to display the visualization. This
  8799. * property may be specified as a string, referring to the unique ID of the
  8800. * element in the DOM. The string is converted to a reference to the DOM
  8801. * element. The width and height of the SVG element is inferred from this DOM
  8802. * element. If no canvas property is specified, a new SVG element is created and
  8803. * inserted into the document, using the panel dimensions; see
  8804. * {@link #createCanvas}.
  8805. *
  8806. * <li>The <tt>children</tt> array, while not a property per se, contains the
  8807. * scene graph for each child mark. This array is initialized to be empty, and
  8808. * is populated above in {@link #buildInstance}.
  8809. *
  8810. * </ul>The current implementation creates the SVG element, if necessary, during
  8811. * the build phase; in the future, it may be preferrable to move this to the
  8812. * update phase, although then the canvas property would be undefined. In
  8813. * addition, DOM inspection is necessary to define the implied width and height
  8814. * properties that may be inferred from the DOM.
  8815. *
  8816. * @param s a node in the scene graph; the instance of the panel to build.
  8817. */
  8818. pv.Panel.prototype.buildImplied = function(s) {
  8819. if (!this.parent) {
  8820. var c = s.canvas;
  8821. if (c) {
  8822. /* Clear the container if it's not associated with this panel. */
  8823. if (c.$panel != this) {
  8824. c.$panel = this;
  8825. while (c.lastChild) c.removeChild(c.lastChild);
  8826. }
  8827. /* If width and height weren't specified, inspect the container. */
  8828. var w, h;
  8829. if (s.width == null) {
  8830. w = parseFloat(pv.css(c, "width"));
  8831. s.width = w - s.left - s.right;
  8832. }
  8833. if (s.height == null) {
  8834. h = parseFloat(pv.css(c, "height"));
  8835. s.height = h - s.top - s.bottom;
  8836. }
  8837. } else {
  8838. var cache = this.$canvas || (this.$canvas = []);
  8839. if (!(c = cache[this.index])) {
  8840. c = cache[this.index] = document.createElement("span");
  8841. if (this.$dom) { // script element for text/javascript+protovis
  8842. /*
  8843. * this.$dom.parentNode.insertBefore(c, this.$dom);
  8844. * Changing this line to allow the direct definiton of the element where the graph should be placed
  8845. */
  8846. this.$dom.appendChild(c);
  8847. } else { // find the last element in the body
  8848. var n = document.body;
  8849. while (n.lastChild && n.lastChild.tagName) n = n.lastChild;
  8850. if (n != document.body) n = n.parentNode;
  8851. n.appendChild(c);
  8852. }
  8853. }
  8854. }
  8855. s.canvas = c;
  8856. }
  8857. if (!s.transform) s.transform = pv.Transform.identity;
  8858. pv.Mark.prototype.buildImplied.call(this, s);
  8859. };
  8860. /**
  8861. * Constructs a new image with default properties. Images are not typically
  8862. * constructed directly, but by adding to a panel or an existing mark via
  8863. * {@link pv.Mark#add}.
  8864. *
  8865. * @class Represents an image, either a static resource or a dynamically-
  8866. * generated pixel buffer. Images share the same layout and style properties as
  8867. * bars. The external image resource is specified via the {@link #url}
  8868. * property. The optional fill, if specified, appears beneath the image, while
  8869. * the optional stroke appears above the image.
  8870. *
  8871. * <p>Dynamic images such as heatmaps are supported using the {@link #image}
  8872. * psuedo-property. This function is passed the <i>x</i> and <i>y</i> index, in
  8873. * addition to the current data stack. The return value is a {@link pv.Color},
  8874. * or null for transparent. A string can also be returned, which will be parsed
  8875. * into a color; however, it is typically much faster to return an object with
  8876. * <tt>r</tt>, <tt>g</tt>, <tt>b</tt> and <tt>a</tt> attributes, to avoid the
  8877. * cost of parsing and object instantiation.
  8878. *
  8879. * <p>See {@link pv.Bar} for details on positioning properties.
  8880. *
  8881. * @extends pv.Bar
  8882. */
  8883. pv.Image = function() {
  8884. pv.Bar.call(this);
  8885. };
  8886. pv.Image.prototype = pv.extend(pv.Bar)
  8887. .property("url", String)
  8888. .property("imageWidth", Number)
  8889. .property("imageHeight", Number);
  8890. pv.Image.prototype.type = "image";
  8891. /**
  8892. * The URL of the image to display. The set of supported image types is
  8893. * browser-dependent; PNG and JPEG are recommended.
  8894. *
  8895. * @type string
  8896. * @name pv.Image.prototype.url
  8897. */
  8898. /**
  8899. * The width of the image in pixels. For static images, this property is
  8900. * computed implicitly from the loaded image resources. For dynamic images, this
  8901. * property can be used to specify the width of the pixel buffer; otherwise, the
  8902. * value is derived from the <tt>width</tt> property.
  8903. *
  8904. * @type number
  8905. * @name pv.Image.prototype.imageWidth
  8906. */
  8907. /**
  8908. * The height of the image in pixels. For static images, this property is
  8909. * computed implicitly from the loaded image resources. For dynamic images, this
  8910. * property can be used to specify the height of the pixel buffer; otherwise, the
  8911. * value is derived from the <tt>height</tt> property.
  8912. *
  8913. * @type number
  8914. * @name pv.Image.prototype.imageHeight
  8915. */
  8916. /**
  8917. * Default properties for images. By default, there is no stroke or fill style.
  8918. *
  8919. * @type pv.Image
  8920. */
  8921. pv.Image.prototype.defaults = new pv.Image()
  8922. .extend(pv.Bar.prototype.defaults)
  8923. .fillStyle(null);
  8924. /**
  8925. * Specifies the dynamic image function. By default, no image function is
  8926. * specified and the <tt>url</tt> property is used to load a static image
  8927. * resource. If an image function is specified, it will be invoked for each
  8928. * pixel in the image, based on the related <tt>imageWidth</tt> and
  8929. * <tt>imageHeight</tt> properties.
  8930. *
  8931. * <p>For example, given a two-dimensional array <tt>heatmap</tt>, containing
  8932. * numbers in the range [0, 1] in row-major order, a simple monochrome heatmap
  8933. * image can be specified as:
  8934. *
  8935. * <pre>vis.add(pv.Image)
  8936. * .imageWidth(heatmap[0].length)
  8937. * .imageHeight(heatmap.length)
  8938. * .image(pv.ramp("white", "black").by(function(x, y) heatmap[y][x]));</pre>
  8939. *
  8940. * For fastest performance, use an ordinal scale which caches the fixed color
  8941. * palette, or return an object literal with <tt>r</tt>, <tt>g</tt>, <tt>b</tt>
  8942. * and <tt>a</tt> attributes. A {@link pv.Color} or string can also be returned,
  8943. * though this typically results in slower performance.
  8944. *
  8945. * @param {function} f the new sizing function.
  8946. * @returns {pv.Layout.Pack} this.
  8947. */
  8948. pv.Image.prototype.image = function(f) {
  8949. /** @private */
  8950. this.$image = function() {
  8951. var c = f.apply(this, arguments);
  8952. return c == null ? pv.Color.transparent
  8953. : typeof c == "string" ? pv.color(c)
  8954. : c;
  8955. };
  8956. return this;
  8957. };
  8958. /** @private Scan the proto chain for an image function. */
  8959. pv.Image.prototype.bind = function() {
  8960. pv.Bar.prototype.bind.call(this);
  8961. var binds = this.binds, mark = this;
  8962. do {
  8963. binds.image = mark.$image;
  8964. } while (!binds.image && (mark = mark.proto));
  8965. };
  8966. /** @private */
  8967. pv.Image.prototype.buildImplied = function(s) {
  8968. pv.Bar.prototype.buildImplied.call(this, s);
  8969. if (!s.visible) return;
  8970. /* Compute the implied image dimensions. */
  8971. if (s.imageWidth == null) s.imageWidth = s.width;
  8972. if (s.imageHeight == null) s.imageHeight = s.height;
  8973. /* Compute the pixel values. */
  8974. if ((s.url == null) && this.binds.image) {
  8975. /* Cache the canvas element to reuse across renders. */
  8976. var canvas = this.$canvas || (this.$canvas = document.createElement("canvas")),
  8977. context = canvas.getContext("2d"),
  8978. w = s.imageWidth,
  8979. h = s.imageHeight,
  8980. stack = pv.Mark.stack,
  8981. data;
  8982. /* Evaluate the image function, storing into a CanvasPixelArray. */
  8983. canvas.width = w;
  8984. canvas.height = h;
  8985. data = (s.image = context.createImageData(w, h)).data;
  8986. stack.unshift(null, null);
  8987. for (var y = 0, p = 0; y < h; y++) {
  8988. stack[1] = y;
  8989. for (var x = 0; x < w; x++) {
  8990. stack[0] = x;
  8991. var color = this.binds.image.apply(this, stack);
  8992. data[p++] = color.r;
  8993. data[p++] = color.g;
  8994. data[p++] = color.b;
  8995. data[p++] = 255 * color.a;
  8996. }
  8997. }
  8998. stack.splice(0, 2);
  8999. }
  9000. };
  9001. /**
  9002. * Constructs a new wedge with default properties. Wedges are not typically
  9003. * constructed directly, but by adding to a panel or an existing mark via
  9004. * {@link pv.Mark#add}.
  9005. *
  9006. * @class Represents a wedge, or pie slice. Specified in terms of start and end
  9007. * angle, inner and outer radius, wedges can be used to construct donut charts
  9008. * and polar bar charts as well. If the {@link #angle} property is used, the end
  9009. * angle is implied by adding this value to start angle. By default, the start
  9010. * angle is the previously-generated wedge's end angle. This design allows
  9011. * explicit control over the wedge placement if desired, while offering
  9012. * convenient defaults for the construction of radial graphs.
  9013. *
  9014. * <p>The center point of the circle is positioned using the standard box model.
  9015. * The wedge can be stroked and filled, similar to {@link pv.Bar}.
  9016. *
  9017. * <p>See also the <a href="../../api/Wedge.html">Wedge guide</a>.
  9018. *
  9019. * @extends pv.Mark
  9020. */
  9021. pv.Wedge = function() {
  9022. pv.Mark.call(this);
  9023. };
  9024. pv.Wedge.prototype = pv.extend(pv.Mark)
  9025. .property("startAngle", Number)
  9026. .property("endAngle", Number)
  9027. .property("angle", Number)
  9028. .property("innerRadius", Number)
  9029. .property("outerRadius", Number)
  9030. .property("lineWidth", Number)
  9031. .property("strokeStyle", pv.color)
  9032. .property("fillStyle", pv.color);
  9033. pv.Wedge.prototype.type = "wedge";
  9034. /**
  9035. * The start angle of the wedge, in radians. The start angle is measured
  9036. * clockwise from the 3 o'clock position. The default value of this property is
  9037. * the end angle of the previous instance (the {@link Mark#sibling}), or -PI / 2
  9038. * for the first wedge; for pie and donut charts, typically only the
  9039. * {@link #angle} property needs to be specified.
  9040. *
  9041. * @type number
  9042. * @name pv.Wedge.prototype.startAngle
  9043. */
  9044. /**
  9045. * The end angle of the wedge, in radians. If not specified, the end angle is
  9046. * implied as the start angle plus the {@link #angle}.
  9047. *
  9048. * @type number
  9049. * @name pv.Wedge.prototype.endAngle
  9050. */
  9051. /**
  9052. * The angular span of the wedge, in radians. This property is used if end angle
  9053. * is not specified.
  9054. *
  9055. * @type number
  9056. * @name pv.Wedge.prototype.angle
  9057. */
  9058. /**
  9059. * The inner radius of the wedge, in pixels. The default value of this property
  9060. * is zero; a positive value will produce a donut slice rather than a pie slice.
  9061. * The inner radius can vary per-wedge.
  9062. *
  9063. * @type number
  9064. * @name pv.Wedge.prototype.innerRadius
  9065. */
  9066. /**
  9067. * The outer radius of the wedge, in pixels. This property is required. For
  9068. * pies, only this radius is required; for donuts, the inner radius must be
  9069. * specified as well. The outer radius can vary per-wedge.
  9070. *
  9071. * @type number
  9072. * @name pv.Wedge.prototype.outerRadius
  9073. */
  9074. /**
  9075. * The width of stroked lines, in pixels; used in conjunction with
  9076. * <tt>strokeStyle</tt> to stroke the wedge's border.
  9077. *
  9078. * @type number
  9079. * @name pv.Wedge.prototype.lineWidth
  9080. */
  9081. /**
  9082. * The style of stroked lines; used in conjunction with <tt>lineWidth</tt> to
  9083. * stroke the wedge's border. The default value of this property is null,
  9084. * meaning wedges are not stroked by default.
  9085. *
  9086. * @type string
  9087. * @name pv.Wedge.prototype.strokeStyle
  9088. * @see pv.color
  9089. */
  9090. /**
  9091. * The wedge fill style; if non-null, the interior of the wedge is filled with
  9092. * the specified color. The default value of this property is a categorical
  9093. * color.
  9094. *
  9095. * @type string
  9096. * @name pv.Wedge.prototype.fillStyle
  9097. * @see pv.color
  9098. */
  9099. /**
  9100. * Default properties for wedges. By default, there is no stroke and the fill
  9101. * style is a categorical color.
  9102. *
  9103. * @type pv.Wedge
  9104. */
  9105. pv.Wedge.prototype.defaults = new pv.Wedge()
  9106. .extend(pv.Mark.prototype.defaults)
  9107. .startAngle(function() {
  9108. var s = this.sibling();
  9109. return s ? s.endAngle : -Math.PI / 2;
  9110. })
  9111. .innerRadius(0)
  9112. .lineWidth(1.5)
  9113. .strokeStyle(null)
  9114. .fillStyle(pv.Colors.category20().by(pv.index));
  9115. /**
  9116. * Returns the mid-radius of the wedge, which is defined as half-way between the
  9117. * inner and outer radii.
  9118. *
  9119. * @see #innerRadius
  9120. * @see #outerRadius
  9121. * @returns {number} the mid-radius, in pixels.
  9122. */
  9123. pv.Wedge.prototype.midRadius = function() {
  9124. return (this.innerRadius() + this.outerRadius()) / 2;
  9125. };
  9126. /**
  9127. * Returns the mid-angle of the wedge, which is defined as half-way between the
  9128. * start and end angles.
  9129. *
  9130. * @see #startAngle
  9131. * @see #endAngle
  9132. * @returns {number} the mid-angle, in radians.
  9133. */
  9134. pv.Wedge.prototype.midAngle = function() {
  9135. return (this.startAngle() + this.endAngle()) / 2;
  9136. };
  9137. /**
  9138. * Constructs a new wedge anchor with default properties. Wedges support five
  9139. * different anchors:<ul>
  9140. *
  9141. * <li>outer
  9142. * <li>inner
  9143. * <li>center
  9144. * <li>start
  9145. * <li>end
  9146. *
  9147. * </ul>In addition to positioning properties (left, right, top bottom), the
  9148. * anchors support text rendering properties (text-align, text-baseline,
  9149. * textAngle). Text is rendered to appear inside the wedge.
  9150. *
  9151. * @param {string} name the anchor name; either a string or a property function.
  9152. * @returns {pv.Anchor}
  9153. */
  9154. pv.Wedge.prototype.anchor = function(name) {
  9155. function partial(s) { return s.innerRadius || s.angle < 2 * Math.PI; }
  9156. function midRadius(s) { return (s.innerRadius + s.outerRadius) / 2; }
  9157. function midAngle(s) { return (s.startAngle + s.endAngle) / 2; }
  9158. var scene;
  9159. return pv.Mark.prototype.anchor.call(this, name)
  9160. .def("$wedge.anchor", function() {
  9161. scene = this.scene.target;
  9162. })
  9163. .left(function() {
  9164. var s = scene[this.index];
  9165. if (partial(s)) switch (this.name()) {
  9166. case "outer": return s.left + s.outerRadius * Math.cos(midAngle(s));
  9167. case "inner": return s.left + s.innerRadius * Math.cos(midAngle(s));
  9168. case "start": return s.left + midRadius(s) * Math.cos(s.startAngle);
  9169. case "center": return s.left + midRadius(s) * Math.cos(midAngle(s));
  9170. case "end": return s.left + midRadius(s) * Math.cos(s.endAngle);
  9171. }
  9172. return s.left;
  9173. })
  9174. .top(function() {
  9175. var s = scene[this.index];
  9176. if (partial(s)) switch (this.name()) {
  9177. case "outer": return s.top + s.outerRadius * Math.sin(midAngle(s));
  9178. case "inner": return s.top + s.innerRadius * Math.sin(midAngle(s));
  9179. case "start": return s.top + midRadius(s) * Math.sin(s.startAngle);
  9180. case "center": return s.top + midRadius(s) * Math.sin(midAngle(s));
  9181. case "end": return s.top + midRadius(s) * Math.sin(s.endAngle);
  9182. }
  9183. return s.top;
  9184. })
  9185. .textAlign(function() {
  9186. var s = scene[this.index];
  9187. if (partial(s)) switch (this.name()) {
  9188. case "outer": return pv.Wedge.upright(midAngle(s)) ? "right" : "left";
  9189. case "inner": return pv.Wedge.upright(midAngle(s)) ? "left" : "right";
  9190. }
  9191. return "center";
  9192. })
  9193. .textBaseline(function() {
  9194. var s = scene[this.index];
  9195. if (partial(s)) switch (this.name()) {
  9196. case "start": return pv.Wedge.upright(s.startAngle) ? "top" : "bottom";
  9197. case "end": return pv.Wedge.upright(s.endAngle) ? "bottom" : "top";
  9198. }
  9199. return "middle";
  9200. })
  9201. .textAngle(function() {
  9202. var s = scene[this.index], a = 0;
  9203. if (partial(s)) switch (this.name()) {
  9204. case "center":
  9205. case "inner":
  9206. case "outer": a = midAngle(s); break;
  9207. case "start": a = s.startAngle; break;
  9208. case "end": a = s.endAngle; break;
  9209. }
  9210. return pv.Wedge.upright(a) ? a : (a + Math.PI);
  9211. });
  9212. };
  9213. /**
  9214. * Returns true if the specified angle is considered "upright", as in, text
  9215. * rendered at that angle would appear upright. If the angle is not upright,
  9216. * text is rotated 180 degrees to be upright, and the text alignment properties
  9217. * are correspondingly changed.
  9218. *
  9219. * @param {number} angle an angle, in radius.
  9220. * @returns {boolean} true if the specified angle is upright.
  9221. */
  9222. pv.Wedge.upright = function(angle) {
  9223. angle = angle % (2 * Math.PI);
  9224. angle = (angle < 0) ? (2 * Math.PI + angle) : angle;
  9225. return (angle < Math.PI / 2) || (angle >= 3 * Math.PI / 2);
  9226. };
  9227. /** @private Sets angle based on endAngle or vice versa. */
  9228. pv.Wedge.prototype.buildImplied = function(s) {
  9229. if (s.angle == null) s.angle = s.endAngle - s.startAngle;
  9230. else if (s.endAngle == null) s.endAngle = s.startAngle + s.angle;
  9231. pv.Mark.prototype.buildImplied.call(this, s);
  9232. };
  9233. /**
  9234. * Abstract; not implemented. There is no explicit constructor; this class
  9235. * merely serves to document the attributes that are used on particles in
  9236. * physics simulations.
  9237. *
  9238. * @class A weighted particle that can participate in a force simulation.
  9239. *
  9240. * @name pv.Particle
  9241. */
  9242. /**
  9243. * The next particle in the simulation. Particles form a singly-linked list.
  9244. *
  9245. * @field
  9246. * @type pv.Particle
  9247. * @name pv.Particle.prototype.next
  9248. */
  9249. /**
  9250. * The <i>x</i>-position of the particle.
  9251. *
  9252. * @field
  9253. * @type number
  9254. * @name pv.Particle.prototype.x
  9255. */
  9256. /**
  9257. * The <i>y</i>-position of the particle.
  9258. *
  9259. * @field
  9260. * @type number
  9261. * @name pv.Particle.prototype.y
  9262. */
  9263. /**
  9264. * The <i>x</i>-velocity of the particle.
  9265. *
  9266. * @field
  9267. * @type number
  9268. * @name pv.Particle.prototype.vx
  9269. */
  9270. /**
  9271. * The <i>y</i>-velocity of the particle.
  9272. *
  9273. * @field
  9274. * @type number
  9275. * @name pv.Particle.prototype.vy
  9276. */
  9277. /**
  9278. * The <i>x</i>-position of the particle at -dt.
  9279. *
  9280. * @field
  9281. * @type number
  9282. * @name pv.Particle.prototype.px
  9283. */
  9284. /**
  9285. * The <i>y</i>-position of the particle at -dt.
  9286. *
  9287. * @field
  9288. * @type number
  9289. * @name pv.Particle.prototype.py
  9290. */
  9291. /**
  9292. * The <i>x</i>-force on the particle.
  9293. *
  9294. * @field
  9295. * @type number
  9296. * @name pv.Particle.prototype.fx
  9297. */
  9298. /**
  9299. * The <i>y</i>-force on the particle.
  9300. *
  9301. * @field
  9302. * @type number
  9303. * @name pv.Particle.prototype.fy
  9304. */
  9305. /**
  9306. * Constructs a new empty simulation.
  9307. *
  9308. * @param {array} particles
  9309. * @returns {pv.Simulation} a new simulation for the specified particles.
  9310. * @see pv.Simulation
  9311. */
  9312. pv.simulation = function(particles) {
  9313. return new pv.Simulation(particles);
  9314. };
  9315. /**
  9316. * Constructs a new simulation for the specified particles.
  9317. *
  9318. * @class Represents a particle simulation. Particles are massive points in
  9319. * two-dimensional space. Forces can be applied to these particles, causing them
  9320. * to move. Constraints can also be applied to restrict particle movement, for
  9321. * example, constraining particles to a fixed position, or simulating collision
  9322. * between circular particles with area.
  9323. *
  9324. * <p>The simulation uses <a
  9325. * href="http://en.wikipedia.org/wiki/Verlet_integration">Position Verlet</a>
  9326. * integration, due to the ease with which <a
  9327. * href="http://www.teknikus.dk/tj/gdc2001.htm">geometric constraints</a> can be
  9328. * implemented. For each time step, Verlet integration is performed, new forces
  9329. * are accumulated, and then constraints are applied.
  9330. *
  9331. * <p>The simulation makes two simplifying assumptions: all particles are
  9332. * equal-mass, and the time step of the simulation is fixed. It would be easy to
  9333. * incorporate variable-mass particles as a future enhancement. Variable time
  9334. * steps are also possible, but are likely to introduce instability in the
  9335. * simulation.
  9336. *
  9337. * <p>This class can be used directly to simulate particle interaction.
  9338. * Alternatively, for network diagrams, see {@link pv.Layout.Force}.
  9339. *
  9340. * @param {array} particles an array of {@link pv.Particle}s to simulate.
  9341. * @see pv.Layout.Force
  9342. * @see pv.Force
  9343. * @see pv.Constraint
  9344. */
  9345. pv.Simulation = function(particles) {
  9346. for (var i = 0; i < particles.length; i++) this.particle(particles[i]);
  9347. };
  9348. /**
  9349. * The particles in the simulation. Particles are stored as a linked list; this
  9350. * field represents the first particle in the simulation.
  9351. *
  9352. * @field
  9353. * @type pv.Particle
  9354. * @name pv.Simulation.prototype.particles
  9355. */
  9356. /**
  9357. * The forces in the simulation. Forces are stored as a linked list; this field
  9358. * represents the first force in the simulation.
  9359. *
  9360. * @field
  9361. * @type pv.Force
  9362. * @name pv.Simulation.prototype.forces
  9363. */
  9364. /**
  9365. * The constraints in the simulation. Constraints are stored as a linked list;
  9366. * this field represents the first constraint in the simulation.
  9367. *
  9368. * @field
  9369. * @type pv.Constraint
  9370. * @name pv.Simulation.prototype.constraints
  9371. */
  9372. /**
  9373. * Adds the specified particle to the simulation.
  9374. *
  9375. * @param {pv.Particle} p the new particle.
  9376. * @returns {pv.Simulation} this.
  9377. */
  9378. pv.Simulation.prototype.particle = function(p) {
  9379. p.next = this.particles;
  9380. /* Default velocities and forces to zero if unset. */
  9381. if (isNaN(p.px)) p.px = p.x;
  9382. if (isNaN(p.py)) p.py = p.y;
  9383. if (isNaN(p.fx)) p.fx = 0;
  9384. if (isNaN(p.fy)) p.fy = 0;
  9385. this.particles = p;
  9386. return this;
  9387. };
  9388. /**
  9389. * Adds the specified force to the simulation.
  9390. *
  9391. * @param {pv.Force} f the new force.
  9392. * @returns {pv.Simulation} this.
  9393. */
  9394. pv.Simulation.prototype.force = function(f) {
  9395. f.next = this.forces;
  9396. this.forces = f;
  9397. return this;
  9398. };
  9399. /**
  9400. * Adds the specified constraint to the simulation.
  9401. *
  9402. * @param {pv.Constraint} c the new constraint.
  9403. * @returns {pv.Simulation} this.
  9404. */
  9405. pv.Simulation.prototype.constraint = function(c) {
  9406. c.next = this.constraints;
  9407. this.constraints = c;
  9408. return this;
  9409. };
  9410. /**
  9411. * Apply constraints, and then set the velocities to zero.
  9412. *
  9413. * @returns {pv.Simulation} this.
  9414. */
  9415. pv.Simulation.prototype.stabilize = function(n) {
  9416. var c;
  9417. if (!arguments.length) n = 3; // TODO use cooling schedule
  9418. for (var i = 0; i < n; i++) {
  9419. var q = new pv.Quadtree(this.particles);
  9420. for (c = this.constraints; c; c = c.next) c.apply(this.particles, q);
  9421. }
  9422. for (var p = this.particles; p; p = p.next) {
  9423. p.px = p.x;
  9424. p.py = p.y;
  9425. }
  9426. return this;
  9427. };
  9428. /**
  9429. * Advances the simulation one time-step.
  9430. */
  9431. pv.Simulation.prototype.step = function() {
  9432. var p, f, c;
  9433. /*
  9434. * Assumptions:
  9435. * - The mass (m) of every particles is 1.
  9436. * - The time step (dt) is 1.
  9437. */
  9438. /* Position Verlet integration. */
  9439. for (p = this.particles; p; p = p.next) {
  9440. var px = p.px, py = p.py;
  9441. p.px = p.x;
  9442. p.py = p.y;
  9443. p.x += p.vx = ((p.x - px) + p.fx);
  9444. p.y += p.vy = ((p.y - py) + p.fy);
  9445. }
  9446. /* Apply constraints, then accumulate new forces. */
  9447. var q = new pv.Quadtree(this.particles);
  9448. for (c = this.constraints; c; c = c.next) c.apply(this.particles, q);
  9449. for (p = this.particles; p; p = p.next) p.fx = p.fy = 0;
  9450. for (f = this.forces; f; f = f.next) f.apply(this.particles, q);
  9451. };
  9452. /**
  9453. * Constructs a new quadtree for the specified array of particles.
  9454. *
  9455. * @class Represents a quadtree: a two-dimensional recursive spatial
  9456. * subdivision. This particular implementation uses square partitions, dividing
  9457. * each square into four equally-sized squares. Each particle exists in a unique
  9458. * node; if multiple particles are in the same position, some particles may be
  9459. * stored on internal nodes rather than leaf nodes.
  9460. *
  9461. * <p>This quadtree can be used to accelerate various spatial operations, such
  9462. * as the Barnes-Hut approximation for computing n-body forces, or collision
  9463. * detection.
  9464. *
  9465. * @see pv.Force.charge
  9466. * @see pv.Constraint.collision
  9467. * @param {pv.Particle} particles the linked list of particles.
  9468. */
  9469. pv.Quadtree = function(particles) {
  9470. var p;
  9471. /* Compute bounds. */
  9472. var x1 = Number.POSITIVE_INFINITY, y1 = x1,
  9473. x2 = Number.NEGATIVE_INFINITY, y2 = x2;
  9474. for (p = particles; p; p = p.next) {
  9475. if (p.x < x1) x1 = p.x;
  9476. if (p.y < y1) y1 = p.y;
  9477. if (p.x > x2) x2 = p.x;
  9478. if (p.y > y2) y2 = p.y;
  9479. }
  9480. /* Squarify the bounds. */
  9481. var dx = x2 - x1, dy = y2 - y1;
  9482. if (dx > dy) y2 = y1 + dx;
  9483. else x2 = x1 + dy;
  9484. this.xMin = x1;
  9485. this.yMin = y1;
  9486. this.xMax = x2;
  9487. this.yMax = y2;
  9488. /**
  9489. * @ignore Recursively inserts the specified particle <i>p</i> at the node
  9490. * <i>n</i> or one of its descendants. The bounds are defined by [<i>x1</i>,
  9491. * <i>x2</i>] and [<i>y1</i>, <i>y2</i>].
  9492. */
  9493. function insert(n, p, x1, y1, x2, y2) {
  9494. if (isNaN(p.x) || isNaN(p.y)) return; // ignore invalid particles
  9495. if (n.leaf) {
  9496. if (n.p) {
  9497. /*
  9498. * If the particle at this leaf node is at the same position as the new
  9499. * particle we are adding, we leave the particle associated with the
  9500. * internal node while adding the new particle to a child node. This
  9501. * avoids infinite recursion.
  9502. */
  9503. if ((Math.abs(n.p.x - p.x) + Math.abs(n.p.y - p.y)) < .01) {
  9504. insertChild(n, p, x1, y1, x2, y2);
  9505. } else {
  9506. var v = n.p;
  9507. n.p = null;
  9508. insertChild(n, v, x1, y1, x2, y2);
  9509. insertChild(n, p, x1, y1, x2, y2);
  9510. }
  9511. } else {
  9512. n.p = p;
  9513. }
  9514. } else {
  9515. insertChild(n, p, x1, y1, x2, y2);
  9516. }
  9517. }
  9518. /**
  9519. * @ignore Recursively inserts the specified particle <i>p</i> into a
  9520. * descendant of node <i>n</i>. The bounds are defined by [<i>x1</i>,
  9521. * <i>x2</i>] and [<i>y1</i>, <i>y2</i>].
  9522. */
  9523. function insertChild(n, p, x1, y1, x2, y2) {
  9524. /* Compute the split point, and the quadrant in which to insert p. */
  9525. var sx = (x1 + x2) * .5,
  9526. sy = (y1 + y2) * .5,
  9527. right = p.x >= sx,
  9528. bottom = p.y >= sy;
  9529. /* Recursively insert into the child node. */
  9530. n.leaf = false;
  9531. switch ((bottom << 1) + right) {
  9532. case 0: n = n.c1 || (n.c1 = new pv.Quadtree.Node()); break;
  9533. case 1: n = n.c2 || (n.c2 = new pv.Quadtree.Node()); break;
  9534. case 2: n = n.c3 || (n.c3 = new pv.Quadtree.Node()); break;
  9535. case 3: n = n.c4 || (n.c4 = new pv.Quadtree.Node()); break;
  9536. }
  9537. /* Update the bounds as we recurse. */
  9538. if (right) x1 = sx; else x2 = sx;
  9539. if (bottom) y1 = sy; else y2 = sy;
  9540. insert(n, p, x1, y1, x2, y2);
  9541. }
  9542. /* Insert all particles. */
  9543. this.root = new pv.Quadtree.Node();
  9544. for (p = particles; p; p = p.next) insert(this.root, p, x1, y1, x2, y2);
  9545. };
  9546. /**
  9547. * The root node of the quadtree.
  9548. *
  9549. * @type pv.Quadtree.Node
  9550. * @name pv.Quadtree.prototype.root
  9551. */
  9552. /**
  9553. * The minimum x-coordinate value of all contained particles.
  9554. *
  9555. * @type number
  9556. * @name pv.Quadtree.prototype.xMin
  9557. */
  9558. /**
  9559. * The maximum x-coordinate value of all contained particles.
  9560. *
  9561. * @type number
  9562. * @name pv.Quadtree.prototype.xMax
  9563. */
  9564. /**
  9565. * The minimum y-coordinate value of all contained particles.
  9566. *
  9567. * @type number
  9568. * @name pv.Quadtree.prototype.yMin
  9569. */
  9570. /**
  9571. * The maximum y-coordinate value of all contained particles.
  9572. *
  9573. * @type number
  9574. * @name pv.Quadtree.prototype.yMax
  9575. */
  9576. /**
  9577. * Constructs a new node.
  9578. *
  9579. * @class A node in a quadtree.
  9580. *
  9581. * @see pv.Quadtree
  9582. */
  9583. pv.Quadtree.Node = function() {
  9584. /*
  9585. * Prepopulating all attributes significantly increases performance! Also,
  9586. * letting the language interpreter manage garbage collection was moderately
  9587. * faster than creating a cache pool.
  9588. */
  9589. this.leaf = true;
  9590. this.c1 = null;
  9591. this.c2 = null;
  9592. this.c3 = null;
  9593. this.c4 = null;
  9594. this.p = null;
  9595. };
  9596. /**
  9597. * True if this node is a leaf node; i.e., it has no children. Note that both
  9598. * leaf nodes and non-leaf (internal) nodes may have associated particles. If
  9599. * this is a non-leaf node, then at least one of {@link #c1}, {@link #c2},
  9600. * {@link #c3} or {@link #c4} is guaranteed to be non-null.
  9601. *
  9602. * @type boolean
  9603. * @name pv.Quadtree.Node.prototype.leaf
  9604. */
  9605. /**
  9606. * The particle associated with this node, if any.
  9607. *
  9608. * @type pv.Particle
  9609. * @name pv.Quadtree.Node.prototype.p
  9610. */
  9611. /**
  9612. * The child node for the second quadrant, if any.
  9613. *
  9614. * @type pv.Quadtree.Node
  9615. * @name pv.Quadtree.Node.prototype.c2
  9616. */
  9617. /**
  9618. * The child node for the third quadrant, if any.
  9619. *
  9620. * @type pv.Quadtree.Node
  9621. * @name pv.Quadtree.Node.prototype.c3
  9622. */
  9623. /**
  9624. * The child node for the fourth quadrant, if any.
  9625. *
  9626. * @type pv.Quadtree.Node
  9627. * @name pv.Quadtree.Node.prototype.c4
  9628. */
  9629. /**
  9630. * Abstract; see an implementing class.
  9631. *
  9632. * @class Represents a force that acts on particles. Note that this interface
  9633. * does not specify how to bind a force to specific particles; in general,
  9634. * forces are applied globally to all particles. However, some forces may be
  9635. * applied to specific particles or between particles, such as spring forces,
  9636. * through additional specialization.
  9637. *
  9638. * @see pv.Simulation
  9639. * @see pv.Particle
  9640. * @see pv.Force.charge
  9641. * @see pv.Force.drag
  9642. * @see pv.Force.spring
  9643. */
  9644. pv.Force = {};
  9645. /**
  9646. * Applies this force to the specified particles.
  9647. *
  9648. * @function
  9649. * @name pv.Force.prototype.apply
  9650. * @param {pv.Particle} particles particles to which to apply this force.
  9651. * @param {pv.Quadtree} q a quadtree for spatial acceleration.
  9652. */
  9653. /**
  9654. * Constructs a new charge force, with an optional charge constant. The charge
  9655. * constant can be negative for repulsion (e.g., particles with electrical
  9656. * charge of equal sign), or positive for attraction (e.g., massive particles
  9657. * with mutual gravity). The default charge constant is -40.
  9658. *
  9659. * @class An n-body force, as defined by Coulomb's law or Newton's law of
  9660. * gravitation, inversely proportional to the square of the distance between
  9661. * particles. Note that the force is independent of the <i>mass</i> of the
  9662. * associated particles, and that the particles do not have charges of varying
  9663. * magnitude; instead, the attraction or repulsion of all particles is globally
  9664. * specified as the charge {@link #constant}.
  9665. *
  9666. * <p>This particular implementation uses the Barnes-Hut algorithm. For details,
  9667. * see <a
  9668. * href="http://www.nature.com/nature/journal/v324/n6096/abs/324446a0.html">"A
  9669. * hierarchical O(N log N) force-calculation algorithm"</a>, J. Barnes &amp;
  9670. * P. Hut, <i>Nature</i> 1986.
  9671. *
  9672. * @name pv.Force.charge
  9673. * @param {number} [k] the charge constant.
  9674. */
  9675. pv.Force.charge = function(k) {
  9676. var min = 2, // minimum distance at which to observe forces
  9677. min1 = 1 / min,
  9678. max = 500, // maximum distance at which to observe forces
  9679. max1 = 1 / max,
  9680. theta = .9, // Barnes-Hut theta approximation constant
  9681. force = {};
  9682. if (!arguments.length) k = -40; // default charge constant (repulsion)
  9683. /**
  9684. * Sets or gets the charge constant. If an argument is specified, it is the
  9685. * new charge constant. The charge constant can be negative for repulsion
  9686. * (e.g., particles with electrical charge of equal sign), or positive for
  9687. * attraction (e.g., massive particles with mutual gravity). The default
  9688. * charge constant is -40.
  9689. *
  9690. * @function
  9691. * @name pv.Force.charge.prototype.constant
  9692. * @param {number} x the charge constant.
  9693. * @returns {pv.Force.charge} this.
  9694. */
  9695. force.constant = function(x) {
  9696. if (arguments.length) {
  9697. k = Number(x);
  9698. return force;
  9699. }
  9700. return k;
  9701. };
  9702. /**
  9703. * Sets or gets the domain; specifies the minimum and maximum domain within
  9704. * which charge forces are applied. A minimum distance threshold avoids
  9705. * applying forces that are two strong (due to granularity of the simulation's
  9706. * numeric integration). A maximum distance threshold improves performance by
  9707. * skipping force calculations for particles that are far apart.
  9708. *
  9709. * <p>The default domain is [2, 500].
  9710. *
  9711. * @function
  9712. * @name pv.Force.charge.prototype.domain
  9713. * @param {number} a
  9714. * @param {number} b
  9715. * @returns {pv.Force.charge} this.
  9716. */
  9717. force.domain = function(a, b) {
  9718. if (arguments.length) {
  9719. min = Number(a);
  9720. min1 = 1 / min;
  9721. max = Number(b);
  9722. max1 = 1 / max;
  9723. return force;
  9724. }
  9725. return [min, max];
  9726. };
  9727. /**
  9728. * Sets or gets the Barnes-Hut approximation factor. The Barnes-Hut
  9729. * approximation criterion is the ratio of the size of the quadtree node to
  9730. * the distance from the point to the node's center of mass is beneath some
  9731. * threshold.
  9732. *
  9733. * @function
  9734. * @name pv.Force.charge.prototype.theta
  9735. * @param {number} x the new Barnes-Hut approximation factor.
  9736. * @returns {pv.Force.charge} this.
  9737. */
  9738. force.theta = function(x) {
  9739. if (arguments.length) {
  9740. theta = Number(x);
  9741. return force;
  9742. }
  9743. return theta;
  9744. };
  9745. /**
  9746. * @ignore Recursively computes the center of charge for each node in the
  9747. * quadtree. This is equivalent to the center of mass, assuming that all
  9748. * particles have unit weight.
  9749. */
  9750. function accumulate(n) {
  9751. var cx = 0, cy = 0;
  9752. n.cn = 0;
  9753. function accumulateChild(c) {
  9754. accumulate(c);
  9755. n.cn += c.cn;
  9756. cx += c.cn * c.cx;
  9757. cy += c.cn * c.cy;
  9758. }
  9759. if (!n.leaf) {
  9760. if (n.c1) accumulateChild(n.c1);
  9761. if (n.c2) accumulateChild(n.c2);
  9762. if (n.c3) accumulateChild(n.c3);
  9763. if (n.c4) accumulateChild(n.c4);
  9764. }
  9765. if (n.p) {
  9766. n.cn += k;
  9767. cx += k * n.p.x;
  9768. cy += k * n.p.y;
  9769. }
  9770. n.cx = cx / n.cn;
  9771. n.cy = cy / n.cn;
  9772. }
  9773. /**
  9774. * @ignore Recursively computes forces on the given particle using the given
  9775. * quadtree node. The Barnes-Hut approximation criterion is the ratio of the
  9776. * size of the quadtree node to the distance from the point to the node's
  9777. * center of mass is beneath some threshold.
  9778. */
  9779. function forces(n, p, x1, y1, x2, y2) {
  9780. var dx = n.cx - p.x,
  9781. dy = n.cy - p.y,
  9782. dn = 1 / Math.sqrt(dx * dx + dy * dy);
  9783. /* Barnes-Hut criterion. */
  9784. if ((n.leaf && (n.p != p)) || ((x2 - x1) * dn < theta)) {
  9785. if (dn < max1) return;
  9786. if (dn > min1) dn = min1;
  9787. var kc = n.cn * dn * dn * dn,
  9788. fx = dx * kc,
  9789. fy = dy * kc;
  9790. p.fx += fx;
  9791. p.fy += fy;
  9792. } else if (!n.leaf) {
  9793. var sx = (x1 + x2) * .5, sy = (y1 + y2) * .5;
  9794. if (n.c1) forces(n.c1, p, x1, y1, sx, sy);
  9795. if (n.c2) forces(n.c2, p, sx, y1, x2, sy);
  9796. if (n.c3) forces(n.c3, p, x1, sy, sx, y2);
  9797. if (n.c4) forces(n.c4, p, sx, sy, x2, y2);
  9798. if (dn < max1) return;
  9799. if (dn > min1) dn = min1;
  9800. if (n.p && (n.p != p)) {
  9801. var kc = k * dn * dn * dn,
  9802. fx = dx * kc,
  9803. fy = dy * kc;
  9804. p.fx += fx;
  9805. p.fy += fy;
  9806. }
  9807. }
  9808. }
  9809. /**
  9810. * Applies this force to the specified particles. The force is applied between
  9811. * all pairs of particles within the domain, using the specified quadtree to
  9812. * accelerate n-body force calculation using the Barnes-Hut approximation
  9813. * criterion.
  9814. *
  9815. * @function
  9816. * @name pv.Force.charge.prototype.apply
  9817. * @param {pv.Particle} particles particles to which to apply this force.
  9818. * @param {pv.Quadtree} q a quadtree for spatial acceleration.
  9819. */
  9820. force.apply = function(particles, q) {
  9821. accumulate(q.root);
  9822. for (var p = particles; p; p = p.next) {
  9823. forces(q.root, p, q.xMin, q.yMin, q.xMax, q.yMax);
  9824. }
  9825. };
  9826. return force;
  9827. };
  9828. /**
  9829. * Constructs a new drag force with the specified constant.
  9830. *
  9831. * @class Implements a drag force, simulating friction. The drag force is
  9832. * applied in the opposite direction of the particle's velocity. Since Position
  9833. * Verlet integration does not track velocities explicitly, the error term with
  9834. * this estimate of velocity is fairly high, so the drag force may be
  9835. * inaccurate.
  9836. *
  9837. * @extends pv.Force
  9838. * @param {number} k the drag constant.
  9839. * @see #constant
  9840. */
  9841. pv.Force.drag = function(k) {
  9842. var force = {};
  9843. if (!arguments.length) k = .1; // default drag constant
  9844. /**
  9845. * Sets or gets the drag constant, in the range [0,1]. The default drag
  9846. * constant is 0.1. The drag forces scales linearly with the particle's
  9847. * velocity based on the given drag constant.
  9848. *
  9849. * @function
  9850. * @name pv.Force.drag.prototype.constant
  9851. * @param {number} x the new drag constant.
  9852. * @returns {pv.Force.drag} this, or the current drag constant.
  9853. */
  9854. force.constant = function(x) {
  9855. if (arguments.length) { k = x; return force; }
  9856. return k;
  9857. };
  9858. /**
  9859. * Applies this force to the specified particles.
  9860. *
  9861. * @function
  9862. * @name pv.Force.drag.prototype.apply
  9863. * @param {pv.Particle} particles particles to which to apply this force.
  9864. */
  9865. force.apply = function(particles) {
  9866. if (k) for (var p = particles; p; p = p.next) {
  9867. p.fx -= k * p.vx;
  9868. p.fy -= k * p.vy;
  9869. }
  9870. };
  9871. return force;
  9872. };
  9873. /**
  9874. * Constructs a new spring force with the specified constant. The links
  9875. * associated with this spring force must be specified before the spring force
  9876. * can be applied.
  9877. *
  9878. * @class Implements a spring force, per Hooke's law. The spring force can be
  9879. * configured with a tension constant, rest length, and damping factor. The
  9880. * tension and damping will automatically be normalized using the inverse square
  9881. * root of the maximum link degree of attached nodes; this makes springs weaker
  9882. * between nodes of high link degree.
  9883. *
  9884. * <p>Unlike other forces (such as charge and drag forces) which may be applied
  9885. * globally, spring forces are only applied between linked particles. Therefore,
  9886. * an array of links must be specified before this force can be applied; the
  9887. * links should be an array of {@link pv.Layout.Network.Link}s. See also
  9888. * {@link pv.Layout.Force} for an example of using spring and charge forces for
  9889. * network layout.
  9890. *
  9891. * @extends pv.Force
  9892. * @param {number} k the spring constant.
  9893. * @see #constant
  9894. * @see #links
  9895. */
  9896. pv.Force.spring = function(k) {
  9897. var d = .1, // default damping factor
  9898. l = 20, // default rest length
  9899. links, // links on which to apply spring forces
  9900. kl, // per-spring normalization
  9901. force = {};
  9902. if (!arguments.length) k = .1; // default spring constant (tension)
  9903. /**
  9904. * Sets or gets the links associated with this spring force. Unlike other
  9905. * forces (such as charge and drag forces) which may be applied globally,
  9906. * spring forces are only applied between linked particles. Therefore, an
  9907. * array of links must be specified before this force can be applied; the
  9908. * links should be an array of {@link pv.Layout.Network.Link}s.
  9909. *
  9910. * @function
  9911. * @name pv.Force.spring.prototype.links
  9912. * @param {array} x the new array of links.
  9913. * @returns {pv.Force.spring} this, or the current array of links.
  9914. */
  9915. force.links = function(x) {
  9916. if (arguments.length) {
  9917. links = x;
  9918. kl = x.map(function(l) {
  9919. return 1 / Math.sqrt(Math.max(
  9920. l.sourceNode.linkDegree,
  9921. l.targetNode.linkDegree));
  9922. });
  9923. return force;
  9924. }
  9925. return links;
  9926. };
  9927. /**
  9928. * Sets or gets the spring constant. The default value is 0.1; greater values
  9929. * will result in stronger tension. The spring tension is automatically
  9930. * normalized using the inverse square root of the maximum link degree of
  9931. * attached nodes.
  9932. *
  9933. * @function
  9934. * @name pv.Force.spring.prototype.constant
  9935. * @param {number} x the new spring constant.
  9936. * @returns {pv.Force.spring} this, or the current spring constant.
  9937. */
  9938. force.constant = function(x) {
  9939. if (arguments.length) {
  9940. k = Number(x);
  9941. return force;
  9942. }
  9943. return k;
  9944. };
  9945. /**
  9946. * The spring damping factor, in the range [0,1]. Damping functions
  9947. * identically to drag forces, damping spring bounciness by applying a force
  9948. * in the opposite direction of attached nodes' velocities. The default value
  9949. * is 0.1. The spring damping is automatically normalized using the inverse
  9950. * square root of the maximum link degree of attached nodes.
  9951. *
  9952. * @function
  9953. * @name pv.Force.spring.prototype.damping
  9954. * @param {number} x the new spring damping factor.
  9955. * @returns {pv.Force.spring} this, or the current spring damping factor.
  9956. */
  9957. force.damping = function(x) {
  9958. if (arguments.length) {
  9959. d = Number(x);
  9960. return force;
  9961. }
  9962. return d;
  9963. };
  9964. /**
  9965. * The spring rest length. The default value is 20 pixels.
  9966. *
  9967. * @function
  9968. * @name pv.Force.spring.prototype.length
  9969. * @param {number} x the new spring rest length.
  9970. * @returns {pv.Force.spring} this, or the current spring rest length.
  9971. */
  9972. force.length = function(x) {
  9973. if (arguments.length) {
  9974. l = Number(x);
  9975. return force;
  9976. }
  9977. return l;
  9978. };
  9979. /**
  9980. * Applies this force to the specified particles.
  9981. *
  9982. * @function
  9983. * @name pv.Force.spring.prototype.apply
  9984. * @param {pv.Particle} particles particles to which to apply this force.
  9985. */
  9986. force.apply = function(particles) {
  9987. for (var i = 0; i < links.length; i++) {
  9988. var a = links[i].sourceNode,
  9989. b = links[i].targetNode,
  9990. dx = a.x - b.x,
  9991. dy = a.y - b.y,
  9992. dn = Math.sqrt(dx * dx + dy * dy),
  9993. dd = dn ? (1 / dn) : 1,
  9994. ks = k * kl[i], // normalized tension
  9995. kd = d * kl[i], // normalized damping
  9996. kk = (ks * (dn - l) + kd * (dx * (a.vx - b.vx) + dy * (a.vy - b.vy)) * dd) * dd,
  9997. fx = -kk * (dn ? dx : (.01 * (.5 - Math.random()))),
  9998. fy = -kk * (dn ? dy : (.01 * (.5 - Math.random())));
  9999. a.fx += fx;
  10000. a.fy += fy;
  10001. b.fx -= fx;
  10002. b.fy -= fy;
  10003. }
  10004. };
  10005. return force;
  10006. };
  10007. /**
  10008. * Abstract; see an implementing class.
  10009. *
  10010. * @class Represents a constraint that acts on particles. Note that this
  10011. * interface does not specify how to bind a constraint to specific particles; in
  10012. * general, constraints are applied globally to all particles. However, some
  10013. * constraints may be applied to specific particles or between particles, such
  10014. * as position constraints, through additional specialization.
  10015. *
  10016. * @see pv.Simulation
  10017. * @see pv.Particle
  10018. * @see pv.Constraint.bound
  10019. * @see pv.Constraint.collision
  10020. * @see pv.Constraint.position
  10021. */
  10022. pv.Constraint = {};
  10023. /**
  10024. * Applies this constraint to the specified particles.
  10025. *
  10026. * @function
  10027. * @name pv.Constraint.prototype.apply
  10028. * @param {pv.Particle} particles particles to which to apply this constraint.
  10029. * @param {pv.Quadtree} q a quadtree for spatial acceleration.
  10030. * @returns {pv.Constraint} this.
  10031. */
  10032. /**
  10033. * Constructs a new collision constraint. The default search radius is 10, and
  10034. * the default repeat count is 1. A radius function must be specified to compute
  10035. * the radius of particles.
  10036. *
  10037. * @class Constraints circles to avoid overlap. Each particle is treated as a
  10038. * circle, with the radius of the particle computed using a specified function.
  10039. * For example, if the particle has an <tt>r</tt> attribute storing the radius,
  10040. * the radius <tt>function(d) d.r</tt> specifies a collision constraint using
  10041. * this radius. The radius function is passed each {@link pv.Particle} as the
  10042. * first argument.
  10043. *
  10044. * <p>To accelerate collision detection, this implementation uses a quadtree and
  10045. * a search radius. The search radius is computed as the maximum radius of all
  10046. * particles in the simulation.
  10047. *
  10048. * @see pv.Constraint
  10049. * @param {function} radius the radius function.
  10050. */
  10051. pv.Constraint.collision = function(radius) {
  10052. var n = 1, // number of times to repeat the constraint
  10053. r1,
  10054. px1,
  10055. py1,
  10056. px2,
  10057. py2,
  10058. constraint = {};
  10059. if (!arguments.length) r1 = 10; // default search radius
  10060. /**
  10061. * Sets or gets the repeat count. If the repeat count is greater than 1, the
  10062. * constraint will be applied repeatedly; this is a form of the Gauss-Seidel
  10063. * method for constraints relaxation. Repeating the collision constraint makes
  10064. * the constraint have more of an effect when there is a potential for many
  10065. * co-occurring collisions.
  10066. *
  10067. * @function
  10068. * @name pv.Constraint.collision.prototype.repeat
  10069. * @param {number} x the number of times to repeat this constraint.
  10070. * @returns {pv.Constraint.collision} this.
  10071. */
  10072. constraint.repeat = function(x) {
  10073. if (arguments.length) {
  10074. n = Number(x);
  10075. return constraint;
  10076. }
  10077. return n;
  10078. };
  10079. /** @private */
  10080. function constrain(n, p, x1, y1, x2, y2) {
  10081. if (!n.leaf) {
  10082. var sx = (x1 + x2) * .5,
  10083. sy = (y1 + y2) * .5,
  10084. top = sy > py1,
  10085. bottom = sy < py2,
  10086. left = sx > px1,
  10087. right = sx < px2;
  10088. if (top) {
  10089. if (n.c1 && left) constrain(n.c1, p, x1, y1, sx, sy);
  10090. if (n.c2 && right) constrain(n.c2, p, sx, y1, x2, sy);
  10091. }
  10092. if (bottom) {
  10093. if (n.c3 && left) constrain(n.c3, p, x1, sy, sx, y2);
  10094. if (n.c4 && right) constrain(n.c4, p, sx, sy, x2, y2);
  10095. }
  10096. }
  10097. if (n.p && (n.p != p)) {
  10098. var dx = p.x - n.p.x,
  10099. dy = p.y - n.p.y,
  10100. l = Math.sqrt(dx * dx + dy * dy),
  10101. d = r1 + radius(n.p);
  10102. if (l < d) {
  10103. var k = (l - d) / l * .5;
  10104. dx *= k;
  10105. dy *= k;
  10106. p.x -= dx;
  10107. p.y -= dy;
  10108. n.p.x += dx;
  10109. n.p.y += dy;
  10110. }
  10111. }
  10112. }
  10113. /**
  10114. * Applies this constraint to the specified particles.
  10115. *
  10116. * @function
  10117. * @name pv.Constraint.collision.prototype.apply
  10118. * @param {pv.Particle} particles particles to which to apply this constraint.
  10119. * @param {pv.Quadtree} q a quadtree for spatial acceleration.
  10120. */
  10121. constraint.apply = function(particles, q) {
  10122. var p, r, max = -Infinity;
  10123. for (p = particles; p; p = p.next) {
  10124. r = radius(p);
  10125. if (r > max) max = r;
  10126. }
  10127. for (var i = 0; i < n; i++) {
  10128. for (p = particles; p; p = p.next) {
  10129. r = (r1 = radius(p)) + max;
  10130. px1 = p.x - r;
  10131. px2 = p.x + r;
  10132. py1 = p.y - r;
  10133. py2 = p.y + r;
  10134. constrain(q.root, p, q.xMin, q.yMin, q.xMax, q.yMax);
  10135. }
  10136. }
  10137. };
  10138. return constraint;
  10139. };
  10140. /**
  10141. * Constructs a default position constraint using the <tt>fix</tt> attribute.
  10142. * An optional position function can be specified to determine how the fixed
  10143. * position per-particle is determined.
  10144. *
  10145. * @class Constraints particles to a fixed position. The fixed position per
  10146. * particle is determined using a given position function, which defaults to
  10147. * <tt>function(d) d.fix</tt>.
  10148. *
  10149. * <p>If the position function returns null, then no position constraint is
  10150. * applied to the given particle. Otherwise, the particle's position is set to
  10151. * the returned position, as expressed by a {@link pv.Vector}. (Note: the
  10152. * position does not need to be an instance of <tt>pv.Vector</tt>, but simply an
  10153. * object with <tt>x</tt> and <tt>y</tt> attributes.)
  10154. *
  10155. * <p>This constraint also supports a configurable alpha parameter, which
  10156. * defaults to 1. If the alpha parameter is in the range [0,1], then rather than
  10157. * setting the particle's new position directly to the position returned by the
  10158. * supplied position function, the particle's position is interpolated towards
  10159. * the fixed position. This results is a smooth (exponential) drift towards the
  10160. * fixed position, which can increase the stability of the physics simulation.
  10161. * In addition, the alpha parameter can be decayed over time, relaxing the
  10162. * position constraint, which helps to stabilize on an optimal solution.
  10163. *
  10164. * @param {function} [f] the position function.
  10165. */
  10166. pv.Constraint.position = function(f) {
  10167. var a = 1, // default alpha
  10168. constraint = {};
  10169. if (!arguments.length) /** @ignore */ f = function(p) { return p.fix; };
  10170. /**
  10171. * Sets or gets the alpha parameter for position interpolation. If the alpha
  10172. * parameter is in the range [0,1], then rather than setting the particle's
  10173. * new position directly to the position returned by the supplied position
  10174. * function, the particle's position is interpolated towards the fixed
  10175. * position.
  10176. *
  10177. * @function
  10178. * @name pv.Constraint.position.prototype.alpha
  10179. * @param {number} x the new alpha parameter, in the range [0,1].
  10180. * @returns {pv.Constraint.position} this.
  10181. */
  10182. constraint.alpha = function(x) {
  10183. if (arguments.length) {
  10184. a = Number(x);
  10185. return constraint;
  10186. }
  10187. return a;
  10188. };
  10189. /**
  10190. * Applies this constraint to the specified particles.
  10191. *
  10192. * @function
  10193. * @name pv.Constraint.position.prototype.apply
  10194. * @param {pv.Particle} particles particles to which to apply this constraint.
  10195. */
  10196. constraint.apply = function(particles) {
  10197. for (var p = particles; p; p = p.next) {
  10198. var v = f(p);
  10199. if (v) {
  10200. p.x += (v.x - p.x) * a;
  10201. p.y += (v.y - p.y) * a;
  10202. p.fx = p.fy = p.vx = p.vy = 0;
  10203. }
  10204. }
  10205. };
  10206. return constraint;
  10207. };
  10208. /**
  10209. * Constructs a new bound constraint. Before the constraint can be used, the
  10210. * {@link #x} and {@link #y} methods must be call to specify the bounds.
  10211. *
  10212. * @class Constrains particles to within fixed rectangular bounds. For example,
  10213. * this constraint can be used to constrain particles in a physics simulation
  10214. * within the bounds of an enclosing panel.
  10215. *
  10216. * <p>Note that the current implementation treats particles as points, with no
  10217. * area. If the particles are rendered as dots, be sure to include some
  10218. * additional padding to inset the bounds such that the edges of the dots do not
  10219. * get clipped by the panel bounds. If the particles have different radii, this
  10220. * constraint would need to be extended using a radius function, similar to
  10221. * {@link pv.Constraint.collision}.
  10222. *
  10223. * @see pv.Layout.Force
  10224. * @extends pv.Constraint
  10225. */
  10226. pv.Constraint.bound = function() {
  10227. var constraint = {},
  10228. x,
  10229. y;
  10230. /**
  10231. * Sets or gets the bounds on the x-coordinate.
  10232. *
  10233. * @function
  10234. * @name pv.Constraint.bound.prototype.x
  10235. * @param {number} min the minimum allowed x-coordinate.
  10236. * @param {number} max the maximum allowed x-coordinate.
  10237. * @returns {pv.Constraint.bound} this.
  10238. */
  10239. constraint.x = function(min, max) {
  10240. if (arguments.length) {
  10241. x = {min: Math.min(min, max), max: Math.max(min, max)};
  10242. return this;
  10243. }
  10244. return x;
  10245. };
  10246. /**
  10247. * Sets or gets the bounds on the y-coordinate.
  10248. *
  10249. * @function
  10250. * @name pv.Constraint.bound.prototype.y
  10251. * @param {number} min the minimum allowed y-coordinate.
  10252. * @param {number} max the maximum allowed y-coordinate.
  10253. * @returns {pv.Constraint.bound} this.
  10254. */
  10255. constraint.y = function(min, max) {
  10256. if (arguments.length) {
  10257. y = {min: Math.min(min, max), max: Math.max(min, max)};
  10258. return this;
  10259. }
  10260. return y;
  10261. };
  10262. /**
  10263. * Applies this constraint to the specified particles.
  10264. *
  10265. * @function
  10266. * @name pv.Constraint.bound.prototype.apply
  10267. * @param {pv.Particle} particles particles to which to apply this constraint.
  10268. */
  10269. constraint.apply = function(particles) {
  10270. if (x) for (var p = particles; p; p = p.next) {
  10271. p.x = p.x < x.min ? x.min : (p.x > x.max ? x.max : p.x);
  10272. }
  10273. if (y) for (var p = particles; p; p = p.next) {
  10274. p.y = p.y < y.min ? y.min : (p.y > y.max ? y.max : p.y);
  10275. }
  10276. };
  10277. return constraint;
  10278. };
  10279. /**
  10280. * Constructs a new, empty layout with default properties. Layouts are not
  10281. * typically constructed directly; instead, a concrete subclass is added to an
  10282. * existing panel via {@link pv.Mark#add}.
  10283. *
  10284. * @class Represents an abstract layout, encapsulating a visualization technique
  10285. * such as a streamgraph or treemap. Layouts are themselves containers,
  10286. * extending from {@link pv.Panel}, and defining a set of mark prototypes as
  10287. * children. These mark prototypes provide default properties that together
  10288. * implement the given visualization technique.
  10289. *
  10290. * <p>Layouts do not initially contain any marks; any exported marks (such as a
  10291. * network layout's <tt>link</tt> and <tt>node</tt>) are intended to be used as
  10292. * prototypes. By adding a concrete mark, such as a {@link pv.Bar}, to the
  10293. * appropriate mark prototype, the mark is added to the layout and inherits the
  10294. * given properties. This approach allows further customization of the layout,
  10295. * either by choosing a different mark type to add, or more simply by overriding
  10296. * some of the layout's defined properties.
  10297. *
  10298. * <p>Each concrete layout, such as treemap or circle-packing, has different
  10299. * behavior and may export different mark prototypes, depending on what marks
  10300. * are typically needed to render the desired visualization. Therefore it is
  10301. * important to understand how each layout is structured, such that the provided
  10302. * mark prototypes are used appropriately.
  10303. *
  10304. * <p>In addition to the mark prototypes, layouts may define custom properties
  10305. * that affect the overall behavior of the layout. For example, a treemap layout
  10306. * might use a property to specify which layout algorithm to use. These
  10307. * properties are just like other mark properties, and can be defined as
  10308. * constants or as functions. As with panels, the data property can be used to
  10309. * replicate layouts, and properties can be defined to in terms of layout data.
  10310. *
  10311. * @extends pv.Panel
  10312. */
  10313. pv.Layout = function() {
  10314. pv.Panel.call(this);
  10315. };
  10316. pv.Layout.prototype = pv.extend(pv.Panel);
  10317. /**
  10318. * @private Defines a local property with the specified name and cast. Note that
  10319. * although the property method is only defined locally, the cast function is
  10320. * global, which is necessary since properties are inherited!
  10321. *
  10322. * @param {string} name the property name.
  10323. * @param {function} [cast] the cast function for this property.
  10324. */
  10325. pv.Layout.prototype.property = function(name, cast) {
  10326. if (!this.hasOwnProperty("properties")) {
  10327. this.properties = pv.extend(this.properties);
  10328. }
  10329. this.properties[name] = true;
  10330. this.propertyMethod(name, false, pv.Mark.cast[name] = cast);
  10331. return this;
  10332. };
  10333. /**
  10334. * Constructs a new, empty network layout. Layouts are not typically constructed
  10335. * directly; instead, they are added to an existing panel via
  10336. * {@link pv.Mark#add}.
  10337. *
  10338. * @class Represents an abstract layout for network diagrams. This class
  10339. * provides the basic structure for both node-link diagrams (such as
  10340. * force-directed graph layout) and space-filling network diagrams (such as
  10341. * sunbursts and treemaps). Note that "network" here is a general term that
  10342. * includes hierarchical structures; a tree is represented using links from
  10343. * child to parent.
  10344. *
  10345. * <p>Network layouts require the graph data structure to be defined using two
  10346. * properties:<ul>
  10347. *
  10348. * <li><tt>nodes</tt> - an array of objects representing nodes. Objects in this
  10349. * array must conform to the {@link pv.Layout.Network.Node} interface; which is
  10350. * to say, be careful to avoid naming collisions with automatic attributes such
  10351. * as <tt>index</tt> and <tt>linkDegree</tt>. If the nodes property is defined
  10352. * as an array of primitives, such as numbers or strings, these primitives are
  10353. * automatically wrapped in an object; the resulting object's <tt>nodeValue</tt>
  10354. * attribute points to the original primitive value.
  10355. *
  10356. * <p><li><tt>links</tt> - an array of objects representing links. Objects in
  10357. * this array must conform to the {@link pv.Layout.Network.Link} interface; at a
  10358. * minimum, either <tt>source</tt> and <tt>target</tt> indexes or
  10359. * <tt>sourceNode</tt> and <tt>targetNode</tt> references must be set. Note that
  10360. * if the links property is defined after the nodes property, the links can be
  10361. * defined in terms of <tt>this.nodes()</tt>.
  10362. *
  10363. * </ul>
  10364. *
  10365. * <p>Three standard mark prototypes are provided:<ul>
  10366. *
  10367. * <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Dot}. The node
  10368. * mark is added directly to the layout, with the data property defined via the
  10369. * layout's <tt>nodes</tt> property. Properties such as <tt>strokeStyle</tt> and
  10370. * <tt>fillStyle</tt> can be overridden to compute properties from node data
  10371. * dynamically.
  10372. *
  10373. * <p><li><tt>link</tt> - for rendering links; typically a {@link pv.Line}. The
  10374. * link mark is added to a child panel, whose data property is defined as
  10375. * layout's <tt>links</tt> property. The link's data property is then a
  10376. * two-element array of the source node and target node. Thus, poperties such as
  10377. * <tt>strokeStyle</tt> and <tt>fillStyle</tt> can be overridden to compute
  10378. * properties from either the node data (the first argument) or the link data
  10379. * (the second argument; the parent panel data) dynamically.
  10380. *
  10381. * <p><li><tt>label</tt> - for rendering node labels; typically a
  10382. * {@link pv.Label}. The label mark is added directly to the layout, with the
  10383. * data property defined via the layout's <tt>nodes</tt> property. Properties
  10384. * such as <tt>strokeStyle</tt> and <tt>fillStyle</tt> can be overridden to
  10385. * compute properties from node data dynamically.
  10386. *
  10387. * </ul>Note that some network implementations may not support all three
  10388. * standard mark prototypes; for example, space-filling hierarchical layouts
  10389. * typically do not use a <tt>link</tt> prototype, as the parent-child links are
  10390. * implied by the structure of the space-filling <tt>node</tt> marks. Check the
  10391. * specific network layout for implementation details.
  10392. *
  10393. * <p>Network layout properties, including <tt>nodes</tt> and <tt>links</tt>,
  10394. * are typically cached rather than re-evaluated with every call to render. This
  10395. * is a performance optimization, as network layout algorithms can be
  10396. * expensive. If the network structure changes, call {@link #reset} to clear the
  10397. * cache before rendering. Note that although the network layout properties are
  10398. * cached, child mark properties, such as the marks used to render the nodes and
  10399. * links, <i>are not</i>. Therefore, non-structural changes to the network
  10400. * layout, such as changing the color of a mark on mouseover, do not need to
  10401. * reset the layout.
  10402. *
  10403. * @see pv.Layout.Hierarchy
  10404. * @see pv.Layout.Force
  10405. * @see pv.Layout.Matrix
  10406. * @see pv.Layout.Arc
  10407. * @see pv.Layout.Rollup
  10408. * @extends pv.Layout
  10409. */
  10410. pv.Layout.Network = function() {
  10411. pv.Layout.call(this);
  10412. var that = this;
  10413. /* @private Version tracking to cache layout state, improving performance. */
  10414. this.$id = pv.id();
  10415. /**
  10416. * The node prototype. This prototype is intended to be used with a Dot mark
  10417. * in conjunction with the link prototype.
  10418. *
  10419. * @type pv.Mark
  10420. * @name pv.Layout.Network.prototype.node
  10421. */
  10422. (this.node = new pv.Mark()
  10423. .data(function() { return that.nodes(); })
  10424. .strokeStyle("#1f77b4")
  10425. .fillStyle("#fff")
  10426. .left(function(n) { return n.x; })
  10427. .top(function(n) { return n.y; })).parent = this;
  10428. /**
  10429. * The link prototype, which renders edges between source nodes and target
  10430. * nodes. This prototype is intended to be used with a Line mark in
  10431. * conjunction with the node prototype.
  10432. *
  10433. * @type pv.Mark
  10434. * @name pv.Layout.Network.prototype.link
  10435. */
  10436. this.link = new pv.Mark()
  10437. .extend(this.node)
  10438. .data(function(p) { return [p.sourceNode, p.targetNode]; })
  10439. .fillStyle(null)
  10440. .lineWidth(function(d, p) { return p.linkValue * 1.5; })
  10441. .strokeStyle("rgba(0,0,0,.2)");
  10442. this.link.add = function(type) {
  10443. return that.add(pv.Panel)
  10444. .data(function() { return that.links(); })
  10445. .add(type)
  10446. .extend(this);
  10447. };
  10448. /**
  10449. * The node label prototype, which renders the node name adjacent to the node.
  10450. * This prototype is provided as an alternative to using the anchor on the
  10451. * node mark; it is primarily intended to be used with radial node-link
  10452. * layouts, since it provides a convenient mechanism to set the text angle.
  10453. *
  10454. * @type pv.Mark
  10455. * @name pv.Layout.Network.prototype.label
  10456. */
  10457. (this.label = new pv.Mark()
  10458. .extend(this.node)
  10459. .textMargin(7)
  10460. .textBaseline("middle")
  10461. .text(function(n) { return n.nodeName || n.nodeValue; })
  10462. .textAngle(function(n) {
  10463. var a = n.midAngle;
  10464. return pv.Wedge.upright(a) ? a : (a + Math.PI);
  10465. })
  10466. .textAlign(function(n) {
  10467. return pv.Wedge.upright(n.midAngle) ? "left" : "right";
  10468. })).parent = this;
  10469. };
  10470. /**
  10471. * @class Represents a node in a network layout. There is no explicit
  10472. * constructor; this class merely serves to document the attributes that are
  10473. * used on nodes in network layouts. (Note that hierarchical nodes place
  10474. * additional requirements on node representation, vis {@link pv.Dom.Node}.)
  10475. *
  10476. * @see pv.Layout.Network
  10477. * @name pv.Layout.Network.Node
  10478. */
  10479. /**
  10480. * The node index, zero-based. This attribute is populated automatically based
  10481. * on the index in the array returned by the <tt>nodes</tt> property.
  10482. *
  10483. * @type number
  10484. * @name pv.Layout.Network.Node.prototype.index
  10485. */
  10486. /**
  10487. * The link degree; the sum of link values for all incoming and outgoing links.
  10488. * This attribute is populated automatically.
  10489. *
  10490. * @type number
  10491. * @name pv.Layout.Network.Node.prototype.linkDegree
  10492. */
  10493. /**
  10494. * The node name; optional. If present, this attribute will be used to provide
  10495. * the text for node labels. If not present, the label text will fallback to the
  10496. * <tt>nodeValue</tt> attribute.
  10497. *
  10498. * @type string
  10499. * @name pv.Layout.Network.Node.prototype.nodeName
  10500. */
  10501. /**
  10502. * The node value; optional. If present, and no <tt>nodeName</tt> attribute is
  10503. * present, the node value will be used as the label text. This attribute is
  10504. * also automatically populated if the nodes are specified as an array of
  10505. * primitives, such as strings or numbers.
  10506. *
  10507. * @type object
  10508. * @name pv.Layout.Network.Node.prototype.nodeValue
  10509. */
  10510. /**
  10511. * @class Represents a link in a network layout. There is no explicit
  10512. * constructor; this class merely serves to document the attributes that are
  10513. * used on links in network layouts. For hierarchical layouts, this class is
  10514. * used to represent the parent-child links.
  10515. *
  10516. * @see pv.Layout.Network
  10517. * @name pv.Layout.Network.Link
  10518. */
  10519. /**
  10520. * The link value, or weight; optional. If not specified (or not a number), the
  10521. * default value of 1 is used.
  10522. *
  10523. * @type number
  10524. * @name pv.Layout.Network.Link.prototype.linkValue
  10525. */
  10526. /**
  10527. * The link's source node. If not set, this value will be derived from the
  10528. * <tt>source</tt> attribute index.
  10529. *
  10530. * @type pv.Layout.Network.Node
  10531. * @name pv.Layout.Network.Link.prototype.sourceNode
  10532. */
  10533. /**
  10534. * The link's target node. If not set, this value will be derived from the
  10535. * <tt>target</tt> attribute index.
  10536. *
  10537. * @type pv.Layout.Network.Node
  10538. * @name pv.Layout.Network.Link.prototype.targetNode
  10539. */
  10540. /**
  10541. * Alias for <tt>sourceNode</tt>, as expressed by the index of the source node.
  10542. * This attribute is not populated automatically, but may be used as a more
  10543. * convenient identification of the link's source, for example in a static JSON
  10544. * representation.
  10545. *
  10546. * @type number
  10547. * @name pv.Layout.Network.Link.prototype.source
  10548. */
  10549. /**
  10550. * Alias for <tt>targetNode</tt>, as expressed by the index of the target node.
  10551. * This attribute is not populated automatically, but may be used as a more
  10552. * convenient identification of the link's target, for example in a static JSON
  10553. * representation.
  10554. *
  10555. * @type number
  10556. * @name pv.Layout.Network.Link.prototype.target
  10557. */
  10558. /**
  10559. * Alias for <tt>linkValue</tt>. This attribute is not populated automatically,
  10560. * but may be used instead of the <tt>linkValue</tt> attribute when specifying
  10561. * links.
  10562. *
  10563. * @type number
  10564. * @name pv.Layout.Network.Link.prototype.value
  10565. */
  10566. /** @private Transform nodes and links on cast. */
  10567. pv.Layout.Network.prototype = pv.extend(pv.Layout)
  10568. .property("nodes", function(v) {
  10569. return v.map(function(d, i) {
  10570. if (typeof d != "object") d = {nodeValue: d};
  10571. d.index = i;
  10572. d.linkDegree = 0;
  10573. return d;
  10574. });
  10575. })
  10576. .property("links", function(v) {
  10577. return v.map(function(d) {
  10578. if (isNaN(d.linkValue)) d.linkValue = isNaN(d.value) ? 1 : d.value;
  10579. return d;
  10580. });
  10581. });
  10582. /**
  10583. * Resets the cache, such that changes to layout property definitions will be
  10584. * visible on subsequent render. Unlike normal marks (and normal layouts),
  10585. * properties associated with network layouts are not automatically re-evaluated
  10586. * on render; the properties are cached, and any expensive layout algorithms are
  10587. * only run after the layout is explicitly reset.
  10588. *
  10589. * @returns {pv.Layout.Network} this.
  10590. */
  10591. pv.Layout.Network.prototype.reset = function() {
  10592. this.$id = pv.id();
  10593. return this;
  10594. };
  10595. /** @private Skip evaluating properties if cached. */
  10596. pv.Layout.Network.prototype.buildProperties = function(s, properties) {
  10597. if ((s.$id || 0) < this.$id) {
  10598. pv.Layout.prototype.buildProperties.call(this, s, properties);
  10599. }
  10600. };
  10601. /** @private Compute link degrees; map source and target indexes to nodes. */
  10602. pv.Layout.Network.prototype.buildImplied = function(s) {
  10603. pv.Layout.prototype.buildImplied.call(this, s);
  10604. if (s.$id >= this.$id) return true;
  10605. s.$id = this.$id;
  10606. s.links.forEach(function(d) {
  10607. var v = d.linkValue;
  10608. (d.sourceNode || (d.sourceNode = s.nodes[d.source])).linkDegree += v;
  10609. (d.targetNode || (d.targetNode = s.nodes[d.target])).linkDegree += v;
  10610. });
  10611. };
  10612. /**
  10613. * Constructs a new, empty hierarchy layout. Layouts are not typically
  10614. * constructed directly; instead, they are added to an existing panel via
  10615. * {@link pv.Mark#add}.
  10616. *
  10617. * @class Represents an abstract layout for hierarchy diagrams. This class is a
  10618. * specialization of {@link pv.Layout.Network}, providing the basic structure
  10619. * for both hierarchical node-link diagrams (such as Reingold-Tilford trees) and
  10620. * space-filling hierarchy diagrams (such as sunbursts and treemaps).
  10621. *
  10622. * <p>Unlike general network layouts, the <tt>links</tt> property need not be
  10623. * defined explicitly. Instead, the links are computed implicitly from the
  10624. * <tt>parentNode</tt> attribute of the node objects, as defined by the
  10625. * <tt>nodes</tt> property. This implementation is also available as
  10626. * {@link #links}, for reuse with non-hierarchical layouts; for example, to
  10627. * render a tree using force-directed layout.
  10628. *
  10629. * <p>Correspondingly, the <tt>nodes</tt> property is represented as a union of
  10630. * {@link pv.Layout.Network.Node} and {@link pv.Dom.Node}. To construct a node
  10631. * hierarchy from a simple JSON map, use the {@link pv.Dom} operator; this
  10632. * operator also provides an easy way to sort nodes before passing them to the
  10633. * layout.
  10634. *
  10635. * <p>For more details on how to use this layout, see
  10636. * {@link pv.Layout.Network}.
  10637. *
  10638. * @see pv.Layout.Cluster
  10639. * @see pv.Layout.Partition
  10640. * @see pv.Layout.Tree
  10641. * @see pv.Layout.Treemap
  10642. * @see pv.Layout.Indent
  10643. * @see pv.Layout.Pack
  10644. * @extends pv.Layout.Network
  10645. */
  10646. pv.Layout.Hierarchy = function() {
  10647. pv.Layout.Network.call(this);
  10648. this.link.strokeStyle("#ccc");
  10649. };
  10650. pv.Layout.Hierarchy.prototype = pv.extend(pv.Layout.Network);
  10651. /** @private Compute the implied links. (Links are null by default.) */
  10652. pv.Layout.Hierarchy.prototype.buildImplied = function(s) {
  10653. if (!s.links) s.links = pv.Layout.Hierarchy.links.call(this);
  10654. pv.Layout.Network.prototype.buildImplied.call(this, s);
  10655. };
  10656. /** The implied links; computes links using the <tt>parentNode</tt> attribute. */
  10657. pv.Layout.Hierarchy.links = function() {
  10658. return this.nodes()
  10659. .filter(function(n) { return n.parentNode; })
  10660. .map(function(n) {
  10661. return {
  10662. sourceNode: n,
  10663. targetNode: n.parentNode,
  10664. linkValue: 1
  10665. };
  10666. });
  10667. };
  10668. /** @private Provides standard node-link layout based on breadth & depth. */
  10669. pv.Layout.Hierarchy.NodeLink = {
  10670. /** @private */
  10671. buildImplied: function(s) {
  10672. var nodes = s.nodes,
  10673. orient = s.orient,
  10674. horizontal = /^(top|bottom)$/.test(orient),
  10675. w = s.width,
  10676. h = s.height;
  10677. /* Compute default inner and outer radius. */
  10678. if (orient == "radial") {
  10679. var ir = s.innerRadius, or = s.outerRadius;
  10680. if (ir == null) ir = 0;
  10681. if (or == null) or = Math.min(w, h) / 2;
  10682. }
  10683. /** @private Returns the radius of the given node. */
  10684. function radius(n) {
  10685. return n.parentNode ? (n.depth * (or - ir) + ir) : 0;
  10686. }
  10687. /** @private Returns the angle of the given node. */
  10688. function midAngle(n) {
  10689. return (n.parentNode ? (n.breadth - .25) * 2 * Math.PI : 0);
  10690. }
  10691. /** @private */
  10692. function x(n) {
  10693. switch (orient) {
  10694. case "left": return n.depth * w;
  10695. case "right": return w - n.depth * w;
  10696. case "top": return n.breadth * w;
  10697. case "bottom": return w - n.breadth * w;
  10698. case "radial": return w / 2 + radius(n) * Math.cos(n.midAngle);
  10699. }
  10700. }
  10701. /** @private */
  10702. function y(n) {
  10703. switch (orient) {
  10704. case "left": return n.breadth * h;
  10705. case "right": return h - n.breadth * h;
  10706. case "top": return n.depth * h;
  10707. case "bottom": return h - n.depth * h;
  10708. case "radial": return h / 2 + radius(n) * Math.sin(n.midAngle);
  10709. }
  10710. }
  10711. for (var i = 0; i < nodes.length; i++) {
  10712. var n = nodes[i];
  10713. n.midAngle = orient == "radial" ? midAngle(n)
  10714. : horizontal ? Math.PI / 2 : 0;
  10715. n.x = x(n);
  10716. n.y = y(n);
  10717. if (n.firstChild) n.midAngle += Math.PI;
  10718. }
  10719. }
  10720. };
  10721. /** @private Provides standard space-filling layout based on breadth & depth. */
  10722. pv.Layout.Hierarchy.Fill = {
  10723. /** @private */
  10724. constructor: function() {
  10725. this.node
  10726. .strokeStyle("#fff")
  10727. .fillStyle("#ccc")
  10728. .width(function(n) { return n.dx; })
  10729. .height(function(n) { return n.dy; })
  10730. .innerRadius(function(n) { return n.innerRadius; })
  10731. .outerRadius(function(n) { return n.outerRadius; })
  10732. .startAngle(function(n) { return n.startAngle; })
  10733. .angle(function(n) { return n.angle; });
  10734. this.label
  10735. .textAlign("center")
  10736. .left(function(n) { return n.x + (n.dx / 2); })
  10737. .top(function(n) { return n.y + (n.dy / 2); });
  10738. /* Hide unsupported link. */
  10739. delete this.link;
  10740. },
  10741. /** @private */
  10742. buildImplied: function(s) {
  10743. var nodes = s.nodes,
  10744. orient = s.orient,
  10745. horizontal = /^(top|bottom)$/.test(orient),
  10746. w = s.width,
  10747. h = s.height,
  10748. depth = -nodes[0].minDepth;
  10749. /* Compute default inner and outer radius. */
  10750. if (orient == "radial") {
  10751. var ir = s.innerRadius, or = s.outerRadius;
  10752. if (ir == null) ir = 0;
  10753. if (ir) depth *= 2; // use full depth step for root
  10754. if (or == null) or = Math.min(w, h) / 2;
  10755. }
  10756. /** @private Scales the specified depth for a space-filling layout. */
  10757. function scale(d, depth) {
  10758. return (d + depth) / (1 + depth);
  10759. }
  10760. /** @private */
  10761. function x(n) {
  10762. switch (orient) {
  10763. case "left": return scale(n.minDepth, depth) * w;
  10764. case "right": return (1 - scale(n.maxDepth, depth)) * w;
  10765. case "top": return n.minBreadth * w;
  10766. case "bottom": return (1 - n.maxBreadth) * w;
  10767. case "radial": return w / 2;
  10768. }
  10769. }
  10770. /** @private */
  10771. function y(n) {
  10772. switch (orient) {
  10773. case "left": return n.minBreadth * h;
  10774. case "right": return (1 - n.maxBreadth) * h;
  10775. case "top": return scale(n.minDepth, depth) * h;
  10776. case "bottom": return (1 - scale(n.maxDepth, depth)) * h;
  10777. case "radial": return h / 2;
  10778. }
  10779. }
  10780. /** @private */
  10781. function dx(n) {
  10782. switch (orient) {
  10783. case "left":
  10784. case "right": return (n.maxDepth - n.minDepth) / (1 + depth) * w;
  10785. case "top":
  10786. case "bottom": return (n.maxBreadth - n.minBreadth) * w;
  10787. case "radial": return n.parentNode ? (n.innerRadius + n.outerRadius) * Math.cos(n.midAngle) : 0;
  10788. }
  10789. }
  10790. /** @private */
  10791. function dy(n) {
  10792. switch (orient) {
  10793. case "left":
  10794. case "right": return (n.maxBreadth - n.minBreadth) * h;
  10795. case "top":
  10796. case "bottom": return (n.maxDepth - n.minDepth) / (1 + depth) * h;
  10797. case "radial": return n.parentNode ? (n.innerRadius + n.outerRadius) * Math.sin(n.midAngle) : 0;
  10798. }
  10799. }
  10800. /** @private */
  10801. function innerRadius(n) {
  10802. return Math.max(0, scale(n.minDepth, depth / 2)) * (or - ir) + ir;
  10803. }
  10804. /** @private */
  10805. function outerRadius(n) {
  10806. return scale(n.maxDepth, depth / 2) * (or - ir) + ir;
  10807. }
  10808. /** @private */
  10809. function startAngle(n) {
  10810. return (n.parentNode ? n.minBreadth - .25 : 0) * 2 * Math.PI;
  10811. }
  10812. /** @private */
  10813. function angle(n) {
  10814. return (n.parentNode ? n.maxBreadth - n.minBreadth : 1) * 2 * Math.PI;
  10815. }
  10816. for (var i = 0; i < nodes.length; i++) {
  10817. var n = nodes[i];
  10818. n.x = x(n);
  10819. n.y = y(n);
  10820. if (orient == "radial") {
  10821. n.innerRadius = innerRadius(n);
  10822. n.outerRadius = outerRadius(n);
  10823. n.startAngle = startAngle(n);
  10824. n.angle = angle(n);
  10825. n.midAngle = n.startAngle + n.angle / 2;
  10826. } else {
  10827. n.midAngle = horizontal ? -Math.PI / 2 : 0;
  10828. }
  10829. n.dx = dx(n);
  10830. n.dy = dy(n);
  10831. }
  10832. }
  10833. };
  10834. /**
  10835. * Constructs a new, empty grid layout. Layouts are not typically constructed
  10836. * directly; instead, they are added to an existing panel via
  10837. * {@link pv.Mark#add}.
  10838. *
  10839. * @class Implements a grid layout with regularly-sized rows and columns. The
  10840. * number of rows and columns are determined from their respective
  10841. * properties. For example, the 2&times;3 array:
  10842. *
  10843. * <pre>1 2 3
  10844. * 4 5 6</pre>
  10845. *
  10846. * can be represented using the <tt>rows</tt> property as:
  10847. *
  10848. * <pre>[[1, 2, 3], [4, 5, 6]]</pre>
  10849. *
  10850. * If your data is in column-major order, you can equivalently use the
  10851. * <tt>columns</tt> property. If the <tt>rows</tt> property is an array, it
  10852. * takes priority over the <tt>columns</tt> property. The data is implicitly
  10853. * transposed, as if the {@link pv.transpose} operator were applied.
  10854. *
  10855. * <p>This layout exports a single <tt>cell</tt> mark prototype, which is
  10856. * intended to be used with a bar, panel, layout, or subclass thereof. The data
  10857. * property of the cell prototype is defined as the elements in the array. For
  10858. * example, if the array is a two-dimensional array of values in the range
  10859. * [0,1], a simple heatmap can be generated as:
  10860. *
  10861. * <pre>vis.add(pv.Layout.Grid)
  10862. * .rows(arrays)
  10863. * .cell.add(pv.Bar)
  10864. * .fillStyle(pv.ramp("white", "black"))</pre>
  10865. *
  10866. * The grid subdivides the full width and height of the parent panel into equal
  10867. * rectangles. Note, however, that for large, interactive, or animated heatmaps,
  10868. * you may see significantly better performance through dynamic {@link pv.Image}
  10869. * generation.
  10870. *
  10871. * <p>For irregular grids using value-based spatial partitioning, see {@link
  10872. * pv.Layout.Treemap}.
  10873. *
  10874. * @extends pv.Layout
  10875. */
  10876. pv.Layout.Grid = function() {
  10877. pv.Layout.call(this);
  10878. var that = this;
  10879. /**
  10880. * The cell prototype. This prototype is intended to be used with a bar,
  10881. * panel, or layout (or subclass thereof) to render the grid cells.
  10882. *
  10883. * @type pv.Mark
  10884. * @name pv.Layout.Grid.prototype.cell
  10885. */
  10886. (this.cell = new pv.Mark()
  10887. .data(function() {
  10888. return that.scene[that.index].$grid;
  10889. })
  10890. .width(function() {
  10891. return that.width() / that.cols();
  10892. })
  10893. .height(function() {
  10894. return that.height() / that.rows();
  10895. })
  10896. .left(function() {
  10897. return this.width() * (this.index % that.cols());
  10898. })
  10899. .top(function() {
  10900. return this.height() * Math.floor(this.index / that.cols());
  10901. })).parent = this;
  10902. };
  10903. pv.Layout.Grid.prototype = pv.extend(pv.Layout)
  10904. .property("rows")
  10905. .property("cols");
  10906. /**
  10907. * Default properties for grid layouts. By default, there is one row and one
  10908. * column, and the data is the propagated to the child cell.
  10909. *
  10910. * @type pv.Layout.Grid
  10911. */
  10912. pv.Layout.Grid.prototype.defaults = new pv.Layout.Grid()
  10913. .extend(pv.Layout.prototype.defaults)
  10914. .rows(1)
  10915. .cols(1);
  10916. /** @private */
  10917. pv.Layout.Grid.prototype.buildImplied = function(s) {
  10918. pv.Layout.prototype.buildImplied.call(this, s);
  10919. var r = s.rows, c = s.cols;
  10920. if (typeof c == "object") r = pv.transpose(c);
  10921. if (typeof r == "object") {
  10922. s.$grid = pv.blend(r);
  10923. s.rows = r.length;
  10924. s.cols = r[0] ? r[0].length : 0;
  10925. } else {
  10926. s.$grid = pv.repeat([s.data], r * c);
  10927. }
  10928. };
  10929. /**
  10930. * The number of rows. This property can also be specified as the data in
  10931. * row-major order; in this case, the rows property is implicitly set to the
  10932. * length of the array, and the cols property is set to the length of the first
  10933. * element in the array.
  10934. *
  10935. * @type number
  10936. * @name pv.Layout.Grid.prototype.rows
  10937. */
  10938. /**
  10939. * The number of columns. This property can also be specified as the data in
  10940. * column-major order; in this case, the cols property is implicitly set to the
  10941. * length of the array, and the rows property is set to the length of the first
  10942. * element in the array.
  10943. *
  10944. * @type number
  10945. * @name pv.Layout.Grid.prototype.cols
  10946. */
  10947. /**
  10948. * Constructs a new, empty stack layout. Layouts are not typically constructed
  10949. * directly; instead, they are added to an existing panel via
  10950. * {@link pv.Mark#add}.
  10951. *
  10952. * @class Implements a layout for stacked visualizations, ranging from simple
  10953. * stacked bar charts to more elaborate "streamgraphs" composed of stacked
  10954. * areas. Stack layouts uses length as a visual encoding, as opposed to
  10955. * position, as the layers do not share an aligned axis.
  10956. *
  10957. * <p>Marks can be stacked vertically or horizontally. For example,
  10958. *
  10959. * <pre>vis.add(pv.Layout.Stack)
  10960. * .layers([[1, 1.2, 1.7, 1.5, 1.7],
  10961. * [.5, 1, .8, 1.1, 1.3],
  10962. * [.2, .5, .8, .9, 1]])
  10963. * .x(function() this.index * 35)
  10964. * .y(function(d) d * 40)
  10965. * .layer.add(pv.Area);</pre>
  10966. *
  10967. * specifies a vertically-stacked area chart, using the default "bottom-left"
  10968. * orientation with "zero" offset. This visualization can be easily changed into
  10969. * a streamgraph using the "wiggle" offset, which attempts to minimize change in
  10970. * slope weighted by layer thickness. See the {@link #offset} property for more
  10971. * supported streamgraph algorithms.
  10972. *
  10973. * <p>In the simplest case, the layer data can be specified as a two-dimensional
  10974. * array of numbers. The <tt>x</tt> and <tt>y</tt> psuedo-properties are used to
  10975. * define the thickness of each layer at the given position, respectively; in
  10976. * the above example of the "bottom-left" orientation, the <tt>x</tt> and
  10977. * <tt>y</tt> psuedo-properties are equivalent to the <tt>left</tt> and
  10978. * <tt>height</tt> properties that you might use if you implemented a stacked
  10979. * area by hand.
  10980. *
  10981. * <p>The advantage of using the stack layout is that the baseline, i.e., the
  10982. * <tt>bottom</tt> property is computed automatically using the specified offset
  10983. * algorithm. In addition, the order of layers can be computed using a built-in
  10984. * algorithm via the <tt>order</tt> property.
  10985. *
  10986. * <p>With the exception of the "expand" <tt>offset</tt>, the stack layout does
  10987. * not perform any automatic scaling of data; the values returned from
  10988. * <tt>x</tt> and <tt>y</tt> specify pixel sizes. To simplify scaling math, use
  10989. * this layout in conjunction with {@link pv.Scale.linear} or similar.
  10990. *
  10991. * <p>In other cases, the <tt>values</tt> psuedo-property can be used to define
  10992. * the data more flexibly. As with a typical panel &amp; area, the
  10993. * <tt>layers</tt> property corresponds to the data in the enclosing panel,
  10994. * while the <tt>values</tt> psuedo-property corresponds to the data for the
  10995. * area within the panel. For example, given an array of data values:
  10996. *
  10997. * <pre>var crimea = [
  10998. * { date: "4/1854", wounds: 0, other: 110, disease: 110 },
  10999. * { date: "5/1854", wounds: 0, other: 95, disease: 105 },
  11000. * { date: "6/1854", wounds: 0, other: 40, disease: 95 },
  11001. * ...</pre>
  11002. *
  11003. * and a corresponding array of series names:
  11004. *
  11005. * <pre>var causes = ["wounds", "other", "disease"];</pre>
  11006. *
  11007. * Separate layers can be defined for each cause like so:
  11008. *
  11009. * <pre>vis.add(pv.Layout.Stack)
  11010. * .layers(causes)
  11011. * .values(crimea)
  11012. * .x(function(d) x(d.date))
  11013. * .y(function(d, p) y(d[p]))
  11014. * .layer.add(pv.Area)
  11015. * ...</pre>
  11016. *
  11017. * As with the panel &amp; area case, the datum that is passed to the
  11018. * psuedo-properties <tt>x</tt> and <tt>y</tt> are the values (an element in
  11019. * <tt>crimea</tt>); the second argument is the layer data (a string in
  11020. * <tt>causes</tt>). Additional arguments specify the data of enclosing panels,
  11021. * if any.
  11022. *
  11023. * @extends pv.Layout
  11024. */
  11025. pv.Layout.Stack = function() {
  11026. pv.Layout.call(this);
  11027. var that = this,
  11028. /** @ignore */ none = function() { return null; },
  11029. prop = {t: none, l: none, r: none, b: none, w: none, h: none},
  11030. values,
  11031. buildImplied = that.buildImplied;
  11032. /** @private Proxy the given property on the layer. */
  11033. function proxy(name) {
  11034. return function() {
  11035. return prop[name](this.parent.index, this.index);
  11036. };
  11037. }
  11038. /** @private Compute the layout! */
  11039. this.buildImplied = function(s) {
  11040. buildImplied.call(this, s);
  11041. var data = s.layers,
  11042. n = data.length,
  11043. m,
  11044. orient = s.orient,
  11045. horizontal = /^(top|bottom)\b/.test(orient),
  11046. h = this.parent[horizontal ? "height" : "width"](),
  11047. x = [],
  11048. y = [],
  11049. dy = [];
  11050. /*
  11051. * Iterate over the data, evaluating the values, x and y functions. The
  11052. * context in which the x and y psuedo-properties are evaluated is a
  11053. * pseudo-mark that is a grandchild of this layout.
  11054. */
  11055. var stack = pv.Mark.stack, o = {parent: {parent: this}};
  11056. stack.unshift(null);
  11057. values = [];
  11058. for (var i = 0; i < n; i++) {
  11059. dy[i] = [];
  11060. y[i] = [];
  11061. o.parent.index = i;
  11062. stack[0] = data[i];
  11063. values[i] = this.$values.apply(o.parent, stack);
  11064. if (!i) m = values[i].length;
  11065. stack.unshift(null);
  11066. for (var j = 0; j < m; j++) {
  11067. stack[0] = values[i][j];
  11068. o.index = j;
  11069. if (!i) x[j] = this.$x.apply(o, stack);
  11070. dy[i][j] = this.$y.apply(o, stack);
  11071. }
  11072. stack.shift();
  11073. }
  11074. stack.shift();
  11075. /* order */
  11076. var index;
  11077. switch (s.order) {
  11078. case "inside-out": {
  11079. var max = dy.map(function(v) { return pv.max.index(v); }),
  11080. map = pv.range(n).sort(function(a, b) { return max[a] - max[b]; }),
  11081. sums = dy.map(function(v) { return pv.sum(v); }),
  11082. top = 0,
  11083. bottom = 0,
  11084. tops = [],
  11085. bottoms = [];
  11086. for (var i = 0; i < n; i++) {
  11087. var j = map[i];
  11088. if (top < bottom) {
  11089. top += sums[j];
  11090. tops.push(j);
  11091. } else {
  11092. bottom += sums[j];
  11093. bottoms.push(j);
  11094. }
  11095. }
  11096. index = bottoms.reverse().concat(tops);
  11097. break;
  11098. }
  11099. case "reverse": index = pv.range(n - 1, -1, -1); break;
  11100. default: index = pv.range(n); break;
  11101. }
  11102. /* offset */
  11103. switch (s.offset) {
  11104. case "silohouette": {
  11105. for (var j = 0; j < m; j++) {
  11106. var o = 0;
  11107. for (var i = 0; i < n; i++) o += dy[i][j];
  11108. y[index[0]][j] = (h - o) / 2;
  11109. }
  11110. break;
  11111. }
  11112. case "wiggle": {
  11113. var o = 0;
  11114. for (var i = 0; i < n; i++) o += dy[i][0];
  11115. y[index[0]][0] = o = (h - o) / 2;
  11116. for (var j = 1; j < m; j++) {
  11117. var s1 = 0, s2 = 0, dx = x[j] - x[j - 1];
  11118. for (var i = 0; i < n; i++) s1 += dy[i][j];
  11119. for (var i = 0; i < n; i++) {
  11120. var s3 = (dy[index[i]][j] - dy[index[i]][j - 1]) / (2 * dx);
  11121. for (var k = 0; k < i; k++) {
  11122. s3 += (dy[index[k]][j] - dy[index[k]][j - 1]) / dx;
  11123. }
  11124. s2 += s3 * dy[index[i]][j];
  11125. }
  11126. y[index[0]][j] = o -= s1 ? s2 / s1 * dx : 0;
  11127. }
  11128. break;
  11129. }
  11130. case "expand": {
  11131. for (var j = 0; j < m; j++) {
  11132. y[index[0]][j] = 0;
  11133. var k = 0;
  11134. for (var i = 0; i < n; i++) k += dy[i][j];
  11135. if (k) {
  11136. k = h / k;
  11137. for (var i = 0; i < n; i++) dy[i][j] *= k;
  11138. } else {
  11139. k = h / n;
  11140. for (var i = 0; i < n; i++) dy[i][j] = k;
  11141. }
  11142. }
  11143. break;
  11144. }
  11145. default: {
  11146. for (var j = 0; j < m; j++) y[index[0]][j] = 0;
  11147. break;
  11148. }
  11149. }
  11150. /* Propagate the offset to the other series. */
  11151. for (var j = 0; j < m; j++) {
  11152. var o = y[index[0]][j];
  11153. for (var i = 1; i < n; i++) {
  11154. o += dy[index[i - 1]][j];
  11155. y[index[i]][j] = o;
  11156. }
  11157. }
  11158. /* Find the property definitions for dynamic substitution. */
  11159. var i = orient.indexOf("-"),
  11160. pdy = horizontal ? "h" : "w",
  11161. px = i < 0 ? (horizontal ? "l" : "b") : orient.charAt(i + 1),
  11162. py = orient.charAt(0);
  11163. for (var p in prop) prop[p] = none;
  11164. prop[px] = function(i, j) { return x[j]; };
  11165. prop[py] = function(i, j) { return y[i][j]; };
  11166. prop[pdy] = function(i, j) { return dy[i][j]; };
  11167. };
  11168. /**
  11169. * The layer prototype. This prototype is intended to be used with an area,
  11170. * bar or panel mark (or subclass thereof). Other mark types may be possible,
  11171. * though note that the stack layout is not currently designed to support
  11172. * radial stacked visualizations using wedges.
  11173. *
  11174. * <p>The layer is not a direct child of the stack layout; a hidden panel is
  11175. * used to replicate layers.
  11176. *
  11177. * @type pv.Mark
  11178. * @name pv.Layout.Stack.prototype.layer
  11179. */
  11180. this.layer = new pv.Mark()
  11181. .data(function() { return values[this.parent.index]; })
  11182. .top(proxy("t"))
  11183. .left(proxy("l"))
  11184. .right(proxy("r"))
  11185. .bottom(proxy("b"))
  11186. .width(proxy("w"))
  11187. .height(proxy("h"));
  11188. this.layer.add = function(type) {
  11189. return that.add(pv.Panel)
  11190. .data(function() { return that.layers(); })
  11191. .add(type)
  11192. .extend(this);
  11193. };
  11194. };
  11195. pv.Layout.Stack.prototype = pv.extend(pv.Layout)
  11196. .property("orient", String)
  11197. .property("offset", String)
  11198. .property("order", String)
  11199. .property("layers");
  11200. /**
  11201. * Default properties for stack layouts. The default orientation is
  11202. * "bottom-left", the default offset is "zero", and the default layers is
  11203. * <tt>[[]]</tt>.
  11204. *
  11205. * @type pv.Layout.Stack
  11206. */
  11207. pv.Layout.Stack.prototype.defaults = new pv.Layout.Stack()
  11208. .extend(pv.Layout.prototype.defaults)
  11209. .orient("bottom-left")
  11210. .offset("zero")
  11211. .layers([[]]);
  11212. /** @private */
  11213. pv.Layout.Stack.prototype.$x
  11214. = /** @private */ pv.Layout.Stack.prototype.$y
  11215. = function() { return 0; };
  11216. /**
  11217. * The x psuedo-property; determines the position of the value within the layer.
  11218. * This typically corresponds to the independent variable. For example, with the
  11219. * default "bottom-left" orientation, this function defines the "left" property.
  11220. *
  11221. * @param {function} f the x function.
  11222. * @returns {pv.Layout.Stack} this.
  11223. */
  11224. pv.Layout.Stack.prototype.x = function(f) {
  11225. /** @private */ this.$x = pv.functor(f);
  11226. return this;
  11227. };
  11228. /**
  11229. * The y psuedo-property; determines the thickness of the layer at the given
  11230. * value. This typically corresponds to the dependent variable. For example,
  11231. * with the default "bottom-left" orientation, this function defines the
  11232. * "height" property.
  11233. *
  11234. * @param {function} f the y function.
  11235. * @returns {pv.Layout.Stack} this.
  11236. */
  11237. pv.Layout.Stack.prototype.y = function(f) {
  11238. /** @private */ this.$y = pv.functor(f);
  11239. return this;
  11240. };
  11241. /** @private The default value function; identity. */
  11242. pv.Layout.Stack.prototype.$values = pv.identity;
  11243. /**
  11244. * The values function; determines the values for a given layer. The default
  11245. * value is the identity function, which assumes that the layers property is
  11246. * specified as a two-dimensional (i.e., nested) array.
  11247. *
  11248. * @param {function} f the values function.
  11249. * @returns {pv.Layout.Stack} this.
  11250. */
  11251. pv.Layout.Stack.prototype.values = function(f) {
  11252. this.$values = pv.functor(f);
  11253. return this;
  11254. };
  11255. /**
  11256. * The layer data in row-major order. The value of this property is typically a
  11257. * two-dimensional (i.e., nested) array, but any array can be used, provided the
  11258. * values psuedo-property is defined accordingly.
  11259. *
  11260. * @type array[]
  11261. * @name pv.Layout.Stack.prototype.layers
  11262. */
  11263. /**
  11264. * The layer orientation. The following values are supported:<ul>
  11265. *
  11266. * <li>bottom-left == bottom
  11267. * <li>bottom-right
  11268. * <li>top-left == top
  11269. * <li>top-right
  11270. * <li>left-top
  11271. * <li>left-bottom == left
  11272. * <li>right-top
  11273. * <li>right-bottom == right
  11274. *
  11275. * </ul>. The default value is "bottom-left", which means that the layers will
  11276. * be built from the bottom-up, and the values within layers will be laid out
  11277. * from left-to-right.
  11278. *
  11279. * <p>Note that with non-zero baselines, some orientations may give similar
  11280. * results. For example, offset("silohouette") centers the layers, resulting in
  11281. * a streamgraph. Thus, the orientations "bottom-left" and "top-left" will
  11282. * produce similar results, differing only in the layer order.
  11283. *
  11284. * @type string
  11285. * @name pv.Layout.Stack.prototype.orient
  11286. */
  11287. /**
  11288. * The layer order. The following values are supported:<ul>
  11289. *
  11290. * <li><i>null</i> - use given layer order.
  11291. * <li>inside-out - sort by maximum value, with balanced order.
  11292. * <li>reverse - use reverse of given layer order.
  11293. *
  11294. * </ul>For details on the inside-out order algorithm, refer to "Stacked Graphs
  11295. * -- Geometry &amp; Aesthetics" by L. Byron and M. Wattenberg, IEEE TVCG
  11296. * November/December 2008.
  11297. *
  11298. * @type string
  11299. * @name pv.Layout.Stack.prototype.order
  11300. */
  11301. /**
  11302. * The layer offset; the y-position of the bottom of the lowest layer. The
  11303. * following values are supported:<ul>
  11304. *
  11305. * <li>zero - use a zero baseline, i.e., the y-axis.
  11306. * <li>silohouette - center the stream, i.e., ThemeRiver.
  11307. * <li>wiggle - minimize weighted change in slope.
  11308. * <li>expand - expand layers to fill the enclosing layout dimensions.
  11309. *
  11310. * </ul>For details on these offset algorithms, refer to "Stacked Graphs --
  11311. * Geometry &amp; Aesthetics" by L. Byron and M. Wattenberg, IEEE TVCG
  11312. * November/December 2008.
  11313. *
  11314. * @type string
  11315. * @name pv.Layout.Stack.prototype.offset
  11316. */
  11317. /**
  11318. * Constructs a new, empty treemap layout. Layouts are not typically
  11319. * constructed directly; instead, they are added to an existing panel via
  11320. * {@link pv.Mark#add}.
  11321. *
  11322. * @class Implements a space-filling rectangular layout, with the hierarchy
  11323. * represented via containment. Treemaps represent nodes as boxes, with child
  11324. * nodes placed within parent boxes. The size of each box is proportional to the
  11325. * size of the node in the tree. This particular algorithm is taken from Bruls,
  11326. * D.M., C. Huizing, and J.J. van Wijk, <a
  11327. * href="http://www.win.tue.nl/~vanwijk/stm.pdf">"Squarified Treemaps"</a> in
  11328. * <i>Data Visualization 2000, Proceedings of the Joint Eurographics and IEEE
  11329. * TCVG Sumposium on Visualization</i>, 2000, pp. 33-42.
  11330. *
  11331. * <p>The meaning of the exported mark prototypes changes slightly in the
  11332. * space-filling implementation:<ul>
  11333. *
  11334. * <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Bar}. The node
  11335. * data is populated with <tt>dx</tt> and <tt>dy</tt> attributes, in addition to
  11336. * the standard <tt>x</tt> and <tt>y</tt> position attributes.
  11337. *
  11338. * <p><li><tt>leaf</tt> - for rendering leaf nodes only, with no fill or stroke
  11339. * style by default; typically a {@link pv.Panel} or another layout!
  11340. *
  11341. * <p><li><tt>link</tt> - unsupported; undefined. Links are encoded implicitly
  11342. * in the arrangement of the space-filling nodes.
  11343. *
  11344. * <p><li><tt>label</tt> - for rendering node labels; typically a
  11345. * {@link pv.Label}.
  11346. *
  11347. * </ul>For more details on how to use this layout, see
  11348. * {@link pv.Layout.Hierarchy}.
  11349. *
  11350. * @extends pv.Layout.Hierarchy
  11351. */
  11352. pv.Layout.Treemap = function() {
  11353. pv.Layout.Hierarchy.call(this);
  11354. this.node
  11355. .strokeStyle("#fff")
  11356. .fillStyle("rgba(31, 119, 180, .25)")
  11357. .width(function(n) { return n.dx; })
  11358. .height(function(n) { return n.dy; });
  11359. this.label
  11360. .visible(function(n) { return !n.firstChild; })
  11361. .left(function(n) { return n.x + (n.dx / 2); })
  11362. .top(function(n) { return n.y + (n.dy / 2); })
  11363. .textAlign("center")
  11364. .textAngle(function(n) { return n.dx > n.dy ? 0 : -Math.PI / 2; });
  11365. (this.leaf = new pv.Mark()
  11366. .extend(this.node)
  11367. .fillStyle(null)
  11368. .strokeStyle(null)
  11369. .visible(function(n) { return !n.firstChild; })).parent = this;
  11370. /* Hide unsupported link. */
  11371. delete this.link;
  11372. };
  11373. pv.Layout.Treemap.prototype = pv.extend(pv.Layout.Hierarchy)
  11374. .property("round", Boolean)
  11375. .property("paddingLeft", Number)
  11376. .property("paddingRight", Number)
  11377. .property("paddingTop", Number)
  11378. .property("paddingBottom", Number)
  11379. .property("mode", String)
  11380. .property("order", String);
  11381. /**
  11382. * Default propertiess for treemap layouts. The default mode is "squarify" and
  11383. * the default order is "ascending".
  11384. *
  11385. * @type pv.Layout.Treemap
  11386. */
  11387. pv.Layout.Treemap.prototype.defaults = new pv.Layout.Treemap()
  11388. .extend(pv.Layout.Hierarchy.prototype.defaults)
  11389. .mode("squarify") // squarify, slice-and-dice, slice, dice
  11390. .order("ascending"); // ascending, descending, reverse, null
  11391. /**
  11392. * Whether node sizes should be rounded to integer values. This has a similar
  11393. * effect to setting <tt>antialias(false)</tt> for node values, but allows the
  11394. * treemap algorithm to accumulate error related to pixel rounding.
  11395. *
  11396. * @type boolean
  11397. * @name pv.Layout.Treemap.prototype.round
  11398. */
  11399. /**
  11400. * The left inset between parent add child in pixels. Defaults to 0.
  11401. *
  11402. * @type number
  11403. * @name pv.Layout.Treemap.prototype.paddingLeft
  11404. * @see #padding
  11405. */
  11406. /**
  11407. * The right inset between parent add child in pixels. Defaults to 0.
  11408. *
  11409. * @type number
  11410. * @name pv.Layout.Treemap.prototype.paddingRight
  11411. * @see #padding
  11412. */
  11413. /**
  11414. * The top inset between parent and child in pixels. Defaults to 0.
  11415. *
  11416. * @type number
  11417. * @name pv.Layout.Treemap.prototype.paddingTop
  11418. * @see #padding
  11419. */
  11420. /**
  11421. * The bottom inset between parent and child in pixels. Defaults to 0.
  11422. *
  11423. * @type number
  11424. * @name pv.Layout.Treemap.prototype.paddingBottom
  11425. * @see #padding
  11426. */
  11427. /**
  11428. * The treemap algorithm. The default value is "squarify". The "slice-and-dice"
  11429. * algorithm may also be used, which alternates between horizontal and vertical
  11430. * slices for different depths. In addition, the "slice" and "dice" algorithms
  11431. * may be specified explicitly to control whether horizontal or vertical slices
  11432. * are used, which may be useful for nested treemap layouts.
  11433. *
  11434. * @type string
  11435. * @name pv.Layout.Treemap.prototype.mode
  11436. * @see <a
  11437. * href="ftp://ftp.cs.umd.edu/pub/hcil/Reports-Abstracts-Bibliography/2001-06html/2001-06.pdf"
  11438. * >"Ordered Treemap Layouts"</a> by B. Shneiderman &amp; M. Wattenberg, IEEE
  11439. * InfoVis 2001.
  11440. */
  11441. /**
  11442. * The sibling node order. A <tt>null</tt> value means to use the sibling order
  11443. * specified by the nodes property as-is; "reverse" will reverse the given
  11444. * order. The default value "ascending" will sort siblings in ascending order of
  11445. * size, while "descending" will do the reverse. For sorting based on data
  11446. * attributes other than size, use the default <tt>null</tt> for the order
  11447. * property, and sort the nodes beforehand using the {@link pv.Dom} operator.
  11448. *
  11449. * @type string
  11450. * @name pv.Layout.Treemap.prototype.order
  11451. */
  11452. /**
  11453. * Alias for setting the left, right, top and bottom padding properties
  11454. * simultaneously.
  11455. *
  11456. * @see #paddingLeft
  11457. * @see #paddingRight
  11458. * @see #paddingTop
  11459. * @see #paddingBottom
  11460. * @returns {pv.Layout.Treemap} this.
  11461. */
  11462. pv.Layout.Treemap.prototype.padding = function(n) {
  11463. return this.paddingLeft(n).paddingRight(n).paddingTop(n).paddingBottom(n);
  11464. };
  11465. /** @private The default size function. */
  11466. pv.Layout.Treemap.prototype.$size = function(d) {
  11467. return Number(d.nodeValue);
  11468. };
  11469. /**
  11470. * Specifies the sizing function. By default, the size function uses the
  11471. * <tt>nodeValue</tt> attribute of nodes as a numeric value: <tt>function(d)
  11472. * Number(d.nodeValue)</tt>.
  11473. *
  11474. * <p>The sizing function is invoked for each leaf node in the tree, per the
  11475. * <tt>nodes</tt> property. For example, if the tree data structure represents a
  11476. * file system, with files as leaf nodes, and each file has a <tt>bytes</tt>
  11477. * attribute, you can specify a size function as:
  11478. *
  11479. * <pre> .size(function(d) d.bytes)</pre>
  11480. *
  11481. * @param {function} f the new sizing function.
  11482. * @returns {pv.Layout.Treemap} this.
  11483. */
  11484. pv.Layout.Treemap.prototype.size = function(f) {
  11485. this.$size = pv.functor(f);
  11486. return this;
  11487. };
  11488. /** @private */
  11489. pv.Layout.Treemap.prototype.buildImplied = function(s) {
  11490. if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) return;
  11491. var that = this,
  11492. nodes = s.nodes,
  11493. root = nodes[0],
  11494. stack = pv.Mark.stack,
  11495. left = s.paddingLeft,
  11496. right = s.paddingRight,
  11497. top = s.paddingTop,
  11498. bottom = s.paddingBottom,
  11499. /** @ignore */ size = function(n) { return n.size; },
  11500. round = s.round ? Math.round : Number,
  11501. mode = s.mode;
  11502. /** @private */
  11503. function slice(row, sum, horizontal, x, y, w, h) {
  11504. for (var i = 0, d = 0; i < row.length; i++) {
  11505. var n = row[i];
  11506. if (horizontal) {
  11507. n.x = x + d;
  11508. n.y = y;
  11509. d += n.dx = round(w * n.size / sum);
  11510. n.dy = h;
  11511. } else {
  11512. n.x = x;
  11513. n.y = y + d;
  11514. n.dx = w;
  11515. d += n.dy = round(h * n.size / sum);
  11516. }
  11517. }
  11518. if (n) { // correct on-axis rounding error
  11519. if (horizontal) {
  11520. n.dx += w - d;
  11521. } else {
  11522. n.dy += h - d;
  11523. }
  11524. }
  11525. }
  11526. /** @private */
  11527. function ratio(row, l) {
  11528. var rmax = -Infinity, rmin = Infinity, s = 0;
  11529. for (var i = 0; i < row.length; i++) {
  11530. var r = row[i].size;
  11531. if (r < rmin) rmin = r;
  11532. if (r > rmax) rmax = r;
  11533. s += r;
  11534. }
  11535. s = s * s;
  11536. l = l * l;
  11537. return Math.max(l * rmax / s, s / (l * rmin));
  11538. }
  11539. /** @private */
  11540. function layout(n, i) {
  11541. var x = n.x + left,
  11542. y = n.y + top,
  11543. w = n.dx - left - right,
  11544. h = n.dy - top - bottom;
  11545. /* Assume squarify by default. */
  11546. if (mode != "squarify") {
  11547. slice(n.childNodes, n.size,
  11548. mode == "slice" ? true
  11549. : mode == "dice" ? false
  11550. : i & 1, x, y, w, h);
  11551. return;
  11552. }
  11553. var row = [],
  11554. mink = Infinity,
  11555. l = Math.min(w, h),
  11556. k = w * h / n.size;
  11557. /* Abort if the size is nonpositive. */
  11558. if (n.size <= 0) return;
  11559. /* Scale the sizes to fill the current subregion. */
  11560. n.visitBefore(function(n) { n.size *= k; });
  11561. /** @private Position the specified nodes along one dimension. */
  11562. function position(row) {
  11563. var horizontal = w == l,
  11564. sum = pv.sum(row, size),
  11565. r = l ? round(sum / l) : 0;
  11566. slice(row, sum, horizontal, x, y, horizontal ? w : r, horizontal ? r : h);
  11567. if (horizontal) {
  11568. y += r;
  11569. h -= r;
  11570. } else {
  11571. x += r;
  11572. w -= r;
  11573. }
  11574. l = Math.min(w, h);
  11575. return horizontal;
  11576. }
  11577. var children = n.childNodes.slice(); // copy
  11578. while (children.length) {
  11579. var child = children[children.length - 1];
  11580. if (!child.size) {
  11581. children.pop();
  11582. continue;
  11583. }
  11584. row.push(child);
  11585. var k = ratio(row, l);
  11586. if (k <= mink) {
  11587. children.pop();
  11588. mink = k;
  11589. } else {
  11590. row.pop();
  11591. position(row);
  11592. row.length = 0;
  11593. mink = Infinity;
  11594. }
  11595. }
  11596. /* correct off-axis rounding error */
  11597. if (position(row)) for (var i = 0; i < row.length; i++) {
  11598. row[i].dy += h;
  11599. } else for (var i = 0; i < row.length; i++) {
  11600. row[i].dx += w;
  11601. }
  11602. }
  11603. /* Recursively compute the node depth and size. */
  11604. stack.unshift(null);
  11605. root.visitAfter(function(n, i) {
  11606. n.depth = i;
  11607. n.x = n.y = n.dx = n.dy = 0;
  11608. n.size = n.firstChild
  11609. ? pv.sum(n.childNodes, function(n) { return n.size; })
  11610. : that.$size.apply(that, (stack[0] = n, stack));
  11611. });
  11612. stack.shift();
  11613. /* Sort. */
  11614. switch (s.order) {
  11615. case "ascending": {
  11616. root.sort(function(a, b) { return a.size - b.size; });
  11617. break;
  11618. }
  11619. case "descending": {
  11620. root.sort(function(a, b) { return b.size - a.size; });
  11621. break;
  11622. }
  11623. case "reverse": root.reverse(); break;
  11624. }
  11625. /* Recursively compute the layout. */
  11626. root.x = 0;
  11627. root.y = 0;
  11628. root.dx = s.width;
  11629. root.dy = s.height;
  11630. root.visitBefore(layout);
  11631. };
  11632. /**
  11633. * Constructs a new, empty tree layout. Layouts are not typically constructed
  11634. * directly; instead, they are added to an existing panel via
  11635. * {@link pv.Mark#add}.
  11636. *
  11637. * @class Implements a node-link tree diagram using the Reingold-Tilford "tidy"
  11638. * tree layout algorithm. The specific algorithm used by this layout is based on
  11639. * <a href="http://citeseer.ist.psu.edu/buchheim02improving.html">"Improving
  11640. * Walker's Algorithm to Run in Linear Time"</A> by C. Buchheim, M. J&uuml;nger
  11641. * &amp; S. Leipert, Graph Drawing 2002. This layout supports both cartesian and
  11642. * radial orientations orientations for node-link diagrams.
  11643. *
  11644. * <p>The tree layout supports a "group" property, which if true causes siblings
  11645. * to be positioned closer together than unrelated nodes at the same depth. The
  11646. * layout can be configured using the <tt>depth</tt> and <tt>breadth</tt>
  11647. * properties, which control the increments in pixel space between nodes in both
  11648. * dimensions, similar to the indent layout.
  11649. *
  11650. * <p>For more details on how to use this layout, see
  11651. * {@link pv.Layout.Hierarchy}.
  11652. *
  11653. * @extends pv.Layout.Hierarchy
  11654. */
  11655. pv.Layout.Tree = function() {
  11656. pv.Layout.Hierarchy.call(this);
  11657. };
  11658. pv.Layout.Tree.prototype = pv.extend(pv.Layout.Hierarchy)
  11659. .property("group", Number)
  11660. .property("breadth", Number)
  11661. .property("depth", Number)
  11662. .property("orient", String);
  11663. /**
  11664. * Default properties for tree layouts. The default orientation is "top", the
  11665. * default group parameter is 1, and the default breadth and depth offsets are
  11666. * 15 and 60 respectively.
  11667. *
  11668. * @type pv.Layout.Tree
  11669. */
  11670. pv.Layout.Tree.prototype.defaults = new pv.Layout.Tree()
  11671. .extend(pv.Layout.Hierarchy.prototype.defaults)
  11672. .group(1)
  11673. .breadth(15)
  11674. .depth(60)
  11675. .orient("top");
  11676. /** @private */
  11677. pv.Layout.Tree.prototype.buildImplied = function(s) {
  11678. if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) return;
  11679. var nodes = s.nodes,
  11680. orient = s.orient,
  11681. depth = s.depth,
  11682. breadth = s.breadth,
  11683. group = s.group,
  11684. w = s.width,
  11685. h = s.height;
  11686. /** @private */
  11687. function firstWalk(v) {
  11688. var l, r, a;
  11689. if (!v.firstChild) {
  11690. if (l = v.previousSibling) {
  11691. v.prelim = l.prelim + distance(v.depth, true);
  11692. }
  11693. } else {
  11694. l = v.firstChild;
  11695. r = v.lastChild;
  11696. a = l; // default ancestor
  11697. for (var c = l; c; c = c.nextSibling) {
  11698. firstWalk(c);
  11699. a = apportion(c, a);
  11700. }
  11701. executeShifts(v);
  11702. var midpoint = .5 * (l.prelim + r.prelim);
  11703. if (l = v.previousSibling) {
  11704. v.prelim = l.prelim + distance(v.depth, true);
  11705. v.mod = v.prelim - midpoint;
  11706. } else {
  11707. v.prelim = midpoint;
  11708. }
  11709. }
  11710. }
  11711. /** @private */
  11712. function secondWalk(v, m, depth) {
  11713. v.breadth = v.prelim + m;
  11714. m += v.mod;
  11715. for (var c = v.firstChild; c; c = c.nextSibling) {
  11716. secondWalk(c, m, depth);
  11717. }
  11718. }
  11719. /** @private */
  11720. function apportion(v, a) {
  11721. var w = v.previousSibling;
  11722. if (w) {
  11723. var vip = v,
  11724. vop = v,
  11725. vim = w,
  11726. vom = v.parentNode.firstChild,
  11727. sip = vip.mod,
  11728. sop = vop.mod,
  11729. sim = vim.mod,
  11730. som = vom.mod,
  11731. nr = nextRight(vim),
  11732. nl = nextLeft(vip);
  11733. while (nr && nl) {
  11734. vim = nr;
  11735. vip = nl;
  11736. vom = nextLeft(vom);
  11737. vop = nextRight(vop);
  11738. vop.ancestor = v;
  11739. var shift = (vim.prelim + sim) - (vip.prelim + sip) + distance(vim.depth, false);
  11740. if (shift > 0) {
  11741. moveSubtree(ancestor(vim, v, a), v, shift);
  11742. sip += shift;
  11743. sop += shift;
  11744. }
  11745. sim += vim.mod;
  11746. sip += vip.mod;
  11747. som += vom.mod;
  11748. sop += vop.mod;
  11749. nr = nextRight(vim);
  11750. nl = nextLeft(vip);
  11751. }
  11752. if (nr && !nextRight(vop)) {
  11753. vop.thread = nr;
  11754. vop.mod += sim - sop;
  11755. }
  11756. if (nl && !nextLeft(vom)) {
  11757. vom.thread = nl;
  11758. vom.mod += sip - som;
  11759. a = v;
  11760. }
  11761. }
  11762. return a;
  11763. }
  11764. /** @private */
  11765. function nextLeft(v) {
  11766. return v.firstChild || v.thread;
  11767. }
  11768. /** @private */
  11769. function nextRight(v) {
  11770. return v.lastChild || v.thread;
  11771. }
  11772. /** @private */
  11773. function moveSubtree(wm, wp, shift) {
  11774. var subtrees = wp.number - wm.number;
  11775. wp.change -= shift / subtrees;
  11776. wp.shift += shift;
  11777. wm.change += shift / subtrees;
  11778. wp.prelim += shift;
  11779. wp.mod += shift;
  11780. }
  11781. /** @private */
  11782. function executeShifts(v) {
  11783. var shift = 0, change = 0;
  11784. for (var c = v.lastChild; c; c = c.previousSibling) {
  11785. c.prelim += shift;
  11786. c.mod += shift;
  11787. change += c.change;
  11788. shift += c.shift + change;
  11789. }
  11790. }
  11791. /** @private */
  11792. function ancestor(vim, v, a) {
  11793. return (vim.ancestor.parentNode == v.parentNode) ? vim.ancestor : a;
  11794. }
  11795. /** @private */
  11796. function distance(depth, siblings) {
  11797. return (siblings ? 1 : (group + 1)) / ((orient == "radial") ? depth : 1);
  11798. }
  11799. /* Initialize temporary layout variables. TODO: store separately. */
  11800. var root = nodes[0];
  11801. root.visitAfter(function(v, i) {
  11802. v.ancestor = v;
  11803. v.prelim = 0;
  11804. v.mod = 0;
  11805. v.change = 0;
  11806. v.shift = 0;
  11807. v.number = v.previousSibling ? (v.previousSibling.number + 1) : 0;
  11808. v.depth = i;
  11809. });
  11810. /* Compute the layout using Buchheim et al.'s algorithm. */
  11811. firstWalk(root);
  11812. secondWalk(root, -root.prelim, 0);
  11813. /** @private Returns the angle of the given node. */
  11814. function midAngle(n) {
  11815. return (orient == "radial") ? n.breadth / depth : 0;
  11816. }
  11817. /** @private */
  11818. function x(n) {
  11819. switch (orient) {
  11820. case "left": return n.depth;
  11821. case "right": return w - n.depth;
  11822. case "top":
  11823. case "bottom": return n.breadth + w / 2;
  11824. case "radial": return w / 2 + n.depth * Math.cos(midAngle(n));
  11825. }
  11826. }
  11827. /** @private */
  11828. function y(n) {
  11829. switch (orient) {
  11830. case "left":
  11831. case "right": return n.breadth + h / 2;
  11832. case "top": return n.depth;
  11833. case "bottom": return h - n.depth;
  11834. case "radial": return h / 2 + n.depth * Math.sin(midAngle(n));
  11835. }
  11836. }
  11837. /* Clear temporary layout variables; transform depth and breadth. */
  11838. root.visitAfter(function(v) {
  11839. v.breadth *= breadth;
  11840. v.depth *= depth;
  11841. v.midAngle = midAngle(v);
  11842. v.x = x(v);
  11843. v.y = y(v);
  11844. if (v.firstChild) v.midAngle += Math.PI;
  11845. delete v.breadth;
  11846. delete v.depth;
  11847. delete v.ancestor;
  11848. delete v.prelim;
  11849. delete v.mod;
  11850. delete v.change;
  11851. delete v.shift;
  11852. delete v.number;
  11853. delete v.thread;
  11854. });
  11855. };
  11856. /**
  11857. * The offset between siblings nodes; defaults to 15.
  11858. *
  11859. * @type number
  11860. * @name pv.Layout.Tree.prototype.breadth
  11861. */
  11862. /**
  11863. * The offset between parent and child nodes; defaults to 60.
  11864. *
  11865. * @type number
  11866. * @name pv.Layout.Tree.prototype.depth
  11867. */
  11868. /**
  11869. * The orientation. The default orientation is "top", which means that the root
  11870. * node is placed on the top edge, leaf nodes appear at the bottom, and internal
  11871. * nodes are in-between. The following orientations are supported:<ul>
  11872. *
  11873. * <li>left - left-to-right.
  11874. * <li>right - right-to-left.
  11875. * <li>top - top-to-bottom.
  11876. * <li>bottom - bottom-to-top.
  11877. * <li>radial - radially, with the root at the center.</ul>
  11878. *
  11879. * @type string
  11880. * @name pv.Layout.Tree.prototype.orient
  11881. */
  11882. /**
  11883. * The sibling grouping, i.e., whether differentiating space is placed between
  11884. * sibling groups. The default is 1 (or true), causing sibling leaves to be
  11885. * separated by one breadth offset. Setting this to false (or 0) causes
  11886. * non-siblings to be adjacent.
  11887. *
  11888. * @type number
  11889. * @name pv.Layout.Tree.prototype.group
  11890. */
  11891. /**
  11892. * Constructs a new, empty indent layout. Layouts are not typically constructed
  11893. * directly; instead, they are added to an existing panel via
  11894. * {@link pv.Mark#add}.
  11895. *
  11896. * @class Implements a hierarchical layout using the indent algorithm. This
  11897. * layout implements a node-link diagram where the nodes are presented in
  11898. * preorder traversal, and nodes are indented based on their depth from the
  11899. * root. This technique is used ubiquitously by operating systems to represent
  11900. * file directories; although it requires much vertical space, indented trees
  11901. * allow efficient <i>interactive</i> exploration of trees to find a specific
  11902. * node. In addition they allow rapid scanning of node labels, and multivariate
  11903. * data such as file sizes can be displayed adjacent to the hierarchy.
  11904. *
  11905. * <p>The indent layout can be configured using the <tt>depth</tt> and
  11906. * <tt>breadth</tt> properties, which control the increments in pixel space for
  11907. * each indent and row in the layout. This layout does not support multiple
  11908. * orientations; the root node is rendered in the top-left, while
  11909. * <tt>breadth</tt> is a vertical offset from the top, and <tt>depth</tt> is a
  11910. * horizontal offset from the left.
  11911. *
  11912. * <p>For more details on how to use this layout, see
  11913. * {@link pv.Layout.Hierarchy}.
  11914. *
  11915. * @extends pv.Layout.Hierarchy
  11916. */
  11917. pv.Layout.Indent = function() {
  11918. pv.Layout.Hierarchy.call(this);
  11919. this.link.interpolate("step-after");
  11920. };
  11921. pv.Layout.Indent.prototype = pv.extend(pv.Layout.Hierarchy)
  11922. .property("depth", Number)
  11923. .property("breadth", Number);
  11924. /**
  11925. * The horizontal offset between different levels of the tree; defaults to 15.
  11926. *
  11927. * @type number
  11928. * @name pv.Layout.Indent.prototype.depth
  11929. */
  11930. /**
  11931. * The vertical offset between nodes; defaults to 15.
  11932. *
  11933. * @type number
  11934. * @name pv.Layout.Indent.prototype.breadth
  11935. */
  11936. /**
  11937. * Default properties for indent layouts. By default the depth and breadth
  11938. * offsets are 15 pixels.
  11939. *
  11940. * @type pv.Layout.Indent
  11941. */
  11942. pv.Layout.Indent.prototype.defaults = new pv.Layout.Indent()
  11943. .extend(pv.Layout.Hierarchy.prototype.defaults)
  11944. .depth(15)
  11945. .breadth(15);
  11946. /** @private */
  11947. pv.Layout.Indent.prototype.buildImplied = function(s) {
  11948. if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) return;
  11949. var nodes = s.nodes,
  11950. bspace = s.breadth,
  11951. dspace = s.depth,
  11952. ax = 0,
  11953. ay = 0;
  11954. /** @private */
  11955. function position(n, breadth, depth) {
  11956. n.x = ax + depth++ * dspace;
  11957. n.y = ay + breadth++ * bspace;
  11958. n.midAngle = 0;
  11959. for (var c = n.firstChild; c; c = c.nextSibling) {
  11960. breadth = position(c, breadth, depth);
  11961. }
  11962. return breadth;
  11963. }
  11964. position(nodes[0], 1, 1);
  11965. };
  11966. /**
  11967. * Constructs a new, empty circle-packing layout. Layouts are not typically
  11968. * constructed directly; instead, they are added to an existing panel via
  11969. * {@link pv.Mark#add}.
  11970. *
  11971. * @class Implements a hierarchical layout using circle-packing. The meaning of
  11972. * the exported mark prototypes changes slightly in the space-filling
  11973. * implementation:<ul>
  11974. *
  11975. * <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Dot}.
  11976. *
  11977. * <p><li><tt>link</tt> - unsupported; undefined. Links are encoded implicitly
  11978. * in the arrangement of the space-filling nodes.
  11979. *
  11980. * <p><li><tt>label</tt> - for rendering node labels; typically a
  11981. * {@link pv.Label}.
  11982. *
  11983. * </ul>The pack layout support dynamic sizing for leaf nodes, if a
  11984. * {@link #size} psuedo-property is specified. The default size function returns
  11985. * 1, causing all leaf nodes to be sized equally, and all internal nodes to be
  11986. * sized by the number of leaf nodes they have as descendants.
  11987. *
  11988. * <p>The size function can be used in conjunction with the order property,
  11989. * which allows the nodes to the sorted by the computed size. Note: for sorting
  11990. * based on other data attributes, simply use the default <tt>null</tt> for the
  11991. * order property, and sort the nodes beforehand using the {@link pv.Dom}
  11992. * operator.
  11993. *
  11994. * <p>For more details on how to use this layout, see
  11995. * {@link pv.Layout.Hierarchy}.
  11996. *
  11997. * @extends pv.Layout.Hierarchy
  11998. * @see <a href="http://portal.acm.org/citation.cfm?id=1124772.1124851"
  11999. * >"Visualization of large hierarchical data by circle packing"</a> by W. Wang,
  12000. * H. Wang, G. Dai, and H. Wang, ACM CHI 2006.
  12001. */
  12002. pv.Layout.Pack = function() {
  12003. pv.Layout.Hierarchy.call(this);
  12004. this.node
  12005. .radius(function(n) { return n.radius; })
  12006. .strokeStyle("rgb(31, 119, 180)")
  12007. .fillStyle("rgba(31, 119, 180, .25)");
  12008. this.label
  12009. .textAlign("center");
  12010. /* Hide unsupported link. */
  12011. delete this.link;
  12012. };
  12013. pv.Layout.Pack.prototype = pv.extend(pv.Layout.Hierarchy)
  12014. .property("spacing", Number)
  12015. .property("order", String); // ascending, descending, reverse, null
  12016. /**
  12017. * Default properties for circle-packing layouts. The default spacing parameter
  12018. * is 1 and the default order is "ascending".
  12019. *
  12020. * @type pv.Layout.Pack
  12021. */
  12022. pv.Layout.Pack.prototype.defaults = new pv.Layout.Pack()
  12023. .extend(pv.Layout.Hierarchy.prototype.defaults)
  12024. .spacing(1)
  12025. .order("ascending");
  12026. /**
  12027. * The spacing parameter; defaults to 1, which provides a little bit of padding
  12028. * between sibling nodes and the enclosing circle. Larger values increase the
  12029. * spacing, by making the sibling nodes smaller; a value of zero makes the leaf
  12030. * nodes as large as possible, with no padding on enclosing circles.
  12031. *
  12032. * @type number
  12033. * @name pv.Layout.Pack.prototype.spacing
  12034. */
  12035. /**
  12036. * The sibling node order. The default order is <tt>null</tt>, which means to
  12037. * use the sibling order specified by the nodes property as-is. A value of
  12038. * "ascending" will sort siblings in ascending order of size, while "descending"
  12039. * will do the reverse. For sorting based on data attributes other than size,
  12040. * use the default <tt>null</tt> for the order property, and sort the nodes
  12041. * beforehand using the {@link pv.Dom} operator.
  12042. *
  12043. * @see pv.Dom.Node#sort
  12044. * @type string
  12045. * @name pv.Layout.Pack.prototype.order
  12046. */
  12047. /** @private The default size function. */
  12048. pv.Layout.Pack.prototype.$radius = function() { return 1; };
  12049. // TODO is it possible for spacing to operate in pixel space?
  12050. // Right now it appears to be multiples of the smallest radius.
  12051. /**
  12052. * Specifies the sizing function. By default, a sizing function is disabled and
  12053. * all nodes are given constant size. The sizing function is invoked for each
  12054. * leaf node in the tree (passed to the constructor).
  12055. *
  12056. * <p>For example, if the tree data structure represents a file system, with
  12057. * files as leaf nodes, and each file has a <tt>bytes</tt> attribute, you can
  12058. * specify a size function as:
  12059. *
  12060. * <pre> .size(function(d) d.bytes)</pre>
  12061. *
  12062. * As with other properties, a size function may specify additional arguments to
  12063. * access the data associated with the layout and any enclosing panels.
  12064. *
  12065. * @param {function} f the new sizing function.
  12066. * @returns {pv.Layout.Pack} this.
  12067. */
  12068. pv.Layout.Pack.prototype.size = function(f) {
  12069. this.$radius = typeof f == "function"
  12070. ? function() { return Math.sqrt(f.apply(this, arguments)); }
  12071. : (f = Math.sqrt(f), function() { return f; });
  12072. return this;
  12073. };
  12074. /** @private */
  12075. pv.Layout.Pack.prototype.buildImplied = function(s) {
  12076. if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) return;
  12077. var that = this,
  12078. nodes = s.nodes,
  12079. root = nodes[0];
  12080. /** @private Compute the radii of the leaf nodes. */
  12081. function radii(nodes) {
  12082. var stack = pv.Mark.stack;
  12083. stack.unshift(null);
  12084. for (var i = 0, n = nodes.length; i < n; i++) {
  12085. var c = nodes[i];
  12086. if (!c.firstChild) {
  12087. c.radius = that.$radius.apply(that, (stack[0] = c, stack));
  12088. }
  12089. }
  12090. stack.shift();
  12091. }
  12092. /** @private */
  12093. function packTree(n) {
  12094. var nodes = [];
  12095. for (var c = n.firstChild; c; c = c.nextSibling) {
  12096. if (c.firstChild) c.radius = packTree(c);
  12097. c.n = c.p = c;
  12098. nodes.push(c);
  12099. }
  12100. /* Sort. */
  12101. switch (s.order) {
  12102. case "ascending": {
  12103. nodes.sort(function(a, b) { return a.radius - b.radius; });
  12104. break;
  12105. }
  12106. case "descending": {
  12107. nodes.sort(function(a, b) { return b.radius - a.radius; });
  12108. break;
  12109. }
  12110. case "reverse": nodes.reverse(); break;
  12111. }
  12112. return packCircle(nodes);
  12113. }
  12114. /** @private */
  12115. function packCircle(nodes) {
  12116. var xMin = Infinity,
  12117. xMax = -Infinity,
  12118. yMin = Infinity,
  12119. yMax = -Infinity,
  12120. a, b, c, j, k;
  12121. /** @private */
  12122. function bound(n) {
  12123. xMin = Math.min(n.x - n.radius, xMin);
  12124. xMax = Math.max(n.x + n.radius, xMax);
  12125. yMin = Math.min(n.y - n.radius, yMin);
  12126. yMax = Math.max(n.y + n.radius, yMax);
  12127. }
  12128. /** @private */
  12129. function insert(a, b) {
  12130. var c = a.n;
  12131. a.n = b;
  12132. b.p = a;
  12133. b.n = c;
  12134. c.p = b;
  12135. }
  12136. /** @private */
  12137. function splice(a, b) {
  12138. a.n = b;
  12139. b.p = a;
  12140. }
  12141. /** @private */
  12142. function intersects(a, b) {
  12143. var dx = b.x - a.x,
  12144. dy = b.y - a.y,
  12145. dr = a.radius + b.radius;
  12146. return (dr * dr - dx * dx - dy * dy) > .001; // within epsilon
  12147. }
  12148. /* Create first node. */
  12149. a = nodes[0];
  12150. a.x = -a.radius;
  12151. a.y = 0;
  12152. bound(a);
  12153. /* Create second node. */
  12154. if (nodes.length > 1) {
  12155. b = nodes[1];
  12156. b.x = b.radius;
  12157. b.y = 0;
  12158. bound(b);
  12159. /* Create third node and build chain. */
  12160. if (nodes.length > 2) {
  12161. c = nodes[2];
  12162. place(a, b, c);
  12163. bound(c);
  12164. insert(a, c);
  12165. a.p = c;
  12166. insert(c, b);
  12167. b = a.n;
  12168. /* Now iterate through the rest. */
  12169. for (var i = 3; i < nodes.length; i++) {
  12170. place(a, b, c = nodes[i]);
  12171. /* Search for the closest intersection. */
  12172. var isect = 0, s1 = 1, s2 = 1;
  12173. for (j = b.n; j != b; j = j.n, s1++) {
  12174. if (intersects(j, c)) {
  12175. isect = 1;
  12176. break;
  12177. }
  12178. }
  12179. if (isect == 1) {
  12180. for (k = a.p; k != j.p; k = k.p, s2++) {
  12181. if (intersects(k, c)) {
  12182. if (s2 < s1) {
  12183. isect = -1;
  12184. j = k;
  12185. }
  12186. break;
  12187. }
  12188. }
  12189. }
  12190. /* Update node chain. */
  12191. if (isect == 0) {
  12192. insert(a, c);
  12193. b = c;
  12194. bound(c);
  12195. } else if (isect > 0) {
  12196. splice(a, j);
  12197. b = j;
  12198. i--;
  12199. } else if (isect < 0) {
  12200. splice(j, b);
  12201. a = j;
  12202. i--;
  12203. }
  12204. }
  12205. }
  12206. }
  12207. /* Re-center the circles and return the encompassing radius. */
  12208. var cx = (xMin + xMax) / 2,
  12209. cy = (yMin + yMax) / 2,
  12210. cr = 0;
  12211. for (var i = 0; i < nodes.length; i++) {
  12212. var n = nodes[i];
  12213. n.x -= cx;
  12214. n.y -= cy;
  12215. cr = Math.max(cr, n.radius + Math.sqrt(n.x * n.x + n.y * n.y));
  12216. }
  12217. return cr + s.spacing;
  12218. }
  12219. /** @private */
  12220. function place(a, b, c) {
  12221. var da = b.radius + c.radius,
  12222. db = a.radius + c.radius,
  12223. dx = b.x - a.x,
  12224. dy = b.y - a.y,
  12225. dc = Math.sqrt(dx * dx + dy * dy),
  12226. cos = (db * db + dc * dc - da * da) / (2 * db * dc),
  12227. theta = Math.acos(cos),
  12228. x = cos * db,
  12229. h = Math.sin(theta) * db;
  12230. dx /= dc;
  12231. dy /= dc;
  12232. c.x = a.x + x * dx + h * dy;
  12233. c.y = a.y + x * dy - h * dx;
  12234. }
  12235. /** @private */
  12236. function transform(n, x, y, k) {
  12237. for (var c = n.firstChild; c; c = c.nextSibling) {
  12238. c.x += n.x;
  12239. c.y += n.y;
  12240. transform(c, x, y, k);
  12241. }
  12242. n.x = x + k * n.x;
  12243. n.y = y + k * n.y;
  12244. n.radius *= k;
  12245. }
  12246. radii(nodes);
  12247. /* Recursively compute the layout. */
  12248. root.x = 0;
  12249. root.y = 0;
  12250. root.radius = packTree(root);
  12251. var w = this.width(),
  12252. h = this.height(),
  12253. k = 1 / Math.max(2 * root.radius / w, 2 * root.radius / h);
  12254. transform(root, w / 2, h / 2, k);
  12255. };
  12256. /**
  12257. * Constructs a new, empty force-directed layout. Layouts are not typically
  12258. * constructed directly; instead, they are added to an existing panel via
  12259. * {@link pv.Mark#add}.
  12260. *
  12261. * @class Implements force-directed network layout as a node-link diagram. This
  12262. * layout uses the Fruchterman-Reingold algorithm, which applies an attractive
  12263. * spring force between neighboring nodes, and a repulsive electrical charge
  12264. * force between all nodes. An additional drag force improves stability of the
  12265. * simulation. See {@link pv.Force.spring}, {@link pv.Force.drag} and {@link
  12266. * pv.Force.charge} for more details; note that the n-body charge force is
  12267. * approximated using the Barnes-Hut algorithm.
  12268. *
  12269. * <p>This layout is implemented on top of {@link pv.Simulation}, which can be
  12270. * used directly for more control over simulation parameters. The simulation
  12271. * uses Position Verlet integration, which does not compute velocities
  12272. * explicitly, but allows for easy geometric constraints, such as bounding the
  12273. * nodes within the layout panel. Many of the configuration properties supported
  12274. * by this layout are simply passed through to the underlying forces and
  12275. * constraints of the simulation.
  12276. *
  12277. * <p>Force layouts are typically interactive. The gradual movement of the nodes
  12278. * as they stabilize to a local stress minimum can help reveal the structure of
  12279. * the network, as can {@link pv.Behavior.drag}, which allows the user to pick
  12280. * up nodes and reposition them while the physics simulation continues. This
  12281. * layout can also be used with pan &amp; zoom behaviors for interaction.
  12282. *
  12283. * <p>To facilitate interaction, this layout by default automatically re-renders
  12284. * using a <tt>setInterval</tt> every 42 milliseconds. This can be disabled via
  12285. * the <tt>iterations</tt> property, which if non-null specifies the number of
  12286. * simulation iterations to run before the force-directed layout is finalized.
  12287. * Be careful not to use too high an iteration count, as this can lead to an
  12288. * annoying delay on page load.
  12289. *
  12290. * <p>As with other network layouts, the network data can be updated
  12291. * dynamically, provided the property cache is reset. See
  12292. * {@link pv.Layout.Network} for details. New nodes are initialized with random
  12293. * positions near the center. Alternatively, positions can be specified manually
  12294. * by setting the <tt>x</tt> and <tt>y</tt> attributes on nodes.
  12295. *
  12296. * @extends pv.Layout.Network
  12297. * @see <a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.13.8444&rep=rep1&type=pdf"
  12298. * >"Graph Drawing by Force-directed Placement"</a> by T. Fruchterman &amp;
  12299. * E. Reingold, Software--Practice &amp; Experience, November 1991.
  12300. */
  12301. pv.Layout.Force = function() {
  12302. pv.Layout.Network.call(this);
  12303. /* Force-directed graphs can be messy, so reduce the link width. */
  12304. this.link.lineWidth(function(d, p) { return Math.sqrt(p.linkValue) * 1.5; });
  12305. this.label.textAlign("center");
  12306. };
  12307. pv.Layout.Force.prototype = pv.extend(pv.Layout.Network)
  12308. .property("bound", Boolean)
  12309. .property("iterations", Number)
  12310. .property("dragConstant", Number)
  12311. .property("chargeConstant", Number)
  12312. .property("chargeMinDistance", Number)
  12313. .property("chargeMaxDistance", Number)
  12314. .property("chargeTheta", Number)
  12315. .property("springConstant", Number)
  12316. .property("springDamping", Number)
  12317. .property("springLength", Number);
  12318. /**
  12319. * The bound parameter; true if nodes should be constrained within the layout
  12320. * panel. Bounding is disabled by default. Currently the layout does not observe
  12321. * the radius of the nodes; strictly speaking, only the center of the node is
  12322. * constrained to be within the panel, with an additional 6-pixel offset for
  12323. * padding. A future enhancement could extend the bound constraint to observe
  12324. * the node's radius, which would also support bounding for variable-size nodes.
  12325. *
  12326. * <p>Note that if this layout is used in conjunction with pan &amp; zoom
  12327. * behaviors, those behaviors should have their bound parameter set to the same
  12328. * value.
  12329. *
  12330. * @type boolean
  12331. * @name pv.Layout.Force.prototype.bound
  12332. */
  12333. /**
  12334. * The number of simulation iterations to run, or null if this layout is
  12335. * interactive. Force-directed layouts are interactive by default, using a
  12336. * <tt>setInterval</tt> to advance the physics simulation and re-render
  12337. * automatically.
  12338. *
  12339. * @type number
  12340. * @name pv.Layout.Force.prototype.iterations
  12341. */
  12342. /**
  12343. * The drag constant, in the range [0,1]. A value of 0 means no drag (a
  12344. * perfectly frictionless environment), while a value of 1 means friction
  12345. * immediately cancels all momentum. The default value is 0.1, which provides a
  12346. * minimum amount of drag that helps stabilize bouncy springs; lower values may
  12347. * result in excessive bounciness, while higher values cause the simulation to
  12348. * take longer to converge.
  12349. *
  12350. * @type number
  12351. * @name pv.Layout.Force.prototype.dragConstant
  12352. * @see pv.Force.drag#constant
  12353. */
  12354. /**
  12355. * The charge constant, which should be a negative number. The default value is
  12356. * -40; more negative values will result in a stronger repulsive force, which
  12357. * may lead to faster convergence at the risk of instability. Too strong
  12358. * repulsive charge forces can cause comparatively weak springs to be stretched
  12359. * well beyond their rest length, emphasizing global structure over local
  12360. * structure. A nonnegative value will break the Fruchterman-Reingold algorithm,
  12361. * and is for entertainment purposes only.
  12362. *
  12363. * @type number
  12364. * @name pv.Layout.Force.prototype.chargeConstant
  12365. * @see pv.Force.charge#constant
  12366. */
  12367. /**
  12368. * The minimum distance at which charge forces are applied. The default minimum
  12369. * distance of 2 avoids applying forces that are two strong; because the physics
  12370. * simulation is run at discrete time intervals, it is possible for two same-
  12371. * charged particles to become very close or even a singularity! Since the
  12372. * charge force is inversely proportional to the square of the distance, very
  12373. * small distances can break the simulation.
  12374. *
  12375. * <p>In rare cases, two particles can become stuck on top of each other, as a
  12376. * minimum distance threshold will prevent the charge force from repelling them.
  12377. * However, this occurs very rarely because other forces and momentum typically
  12378. * cause the particles to become separated again, at which point the repulsive
  12379. * charge force kicks in.
  12380. *
  12381. * @type number
  12382. * @name pv.Layout.Force.prototype.chargeMinDistance
  12383. * @see pv.Force.charge#domain
  12384. */
  12385. /**
  12386. * The maximum distance at which charge forces are applied. This improves
  12387. * performance by ignoring weak charge forces at great distances. Note that this
  12388. * parameter is partly redundant, as the Barnes-Hut algorithm for n-body forces
  12389. * already improves performance for far-away particles through approximation.
  12390. *
  12391. * @type number
  12392. * @name pv.Layout.Force.prototype.chargeMaxDistance
  12393. * @see pv.Force.charge#domain
  12394. */
  12395. /**
  12396. * The Barnes-Hut approximation factor. The Barnes-Hut approximation criterion
  12397. * is the ratio of the size of the quadtree node to the distance from the point
  12398. * to the node's center of mass is beneath some threshold. The default value is
  12399. * 0.9.
  12400. *
  12401. * @type number
  12402. * @name pv.Layout.Force.prototype.chargeTheta
  12403. * @see pv.Force.charge#theta
  12404. */
  12405. /**
  12406. * The spring constant, which should be a positive number. The default value is
  12407. * 0.1; greater values will result in a stronger attractive force, which may
  12408. * lead to faster convergence at the risk of instability. Too strong spring
  12409. * forces can cause comparatively weak charge forces to be ignored, emphasizing
  12410. * local structure over global structure. A nonpositive value will break the
  12411. * Fruchterman-Reingold algorithm, and is for entertainment purposes only.
  12412. *
  12413. * <p>The spring tension is automatically normalized using the inverse square
  12414. * root of the maximum link degree of attached nodes.
  12415. *
  12416. * @type number
  12417. * @name pv.Layout.Force.prototype.springConstant
  12418. * @see pv.Force.spring#constant
  12419. */
  12420. /**
  12421. * The spring damping factor, in the range [0,1]. Damping functions identically
  12422. * to drag forces, damping spring bounciness by applying a force in the opposite
  12423. * direction of attached nodes' velocities. The default value is 0.3.
  12424. *
  12425. * <p>The spring damping is automatically normalized using the inverse square
  12426. * root of the maximum link degree of attached nodes.
  12427. *
  12428. * @type number
  12429. * @name pv.Layout.Force.prototype.springDamping
  12430. * @see pv.Force.spring#damping
  12431. */
  12432. /**
  12433. * The spring rest length. The default value is 20 pixels. Larger values may be
  12434. * appropriate if the layout panel is larger, or if the nodes are rendered
  12435. * larger than the default dot size of 20.
  12436. *
  12437. * @type number
  12438. * @name pv.Layout.Force.prototype.springLength
  12439. * @see pv.Force.spring#length
  12440. */
  12441. /**
  12442. * Default properties for force-directed layouts. The default drag constant is
  12443. * 0.1, the default charge constant is -40 (with a domain of [2, 500] and theta
  12444. * of 0.9), and the default spring constant is 0.1 (with a damping of 0.3 and a
  12445. * rest length of 20).
  12446. *
  12447. * @type pv.Layout.Force
  12448. */
  12449. pv.Layout.Force.prototype.defaults = new pv.Layout.Force()
  12450. .extend(pv.Layout.Network.prototype.defaults)
  12451. .dragConstant(.1)
  12452. .chargeConstant(-40)
  12453. .chargeMinDistance(2)
  12454. .chargeMaxDistance(500)
  12455. .chargeTheta(.9)
  12456. .springConstant(.1)
  12457. .springDamping(.3)
  12458. .springLength(20);
  12459. /** @private Initialize the physics simulation. */
  12460. pv.Layout.Force.prototype.buildImplied = function(s) {
  12461. /* Any cached interactive layouts need to be rebound for the timer. */
  12462. if (pv.Layout.Network.prototype.buildImplied.call(this, s)) {
  12463. var f = s.$force;
  12464. if (f) {
  12465. f.next = this.binds.$force;
  12466. this.binds.$force = f;
  12467. }
  12468. return;
  12469. }
  12470. var that = this,
  12471. nodes = s.nodes,
  12472. links = s.links,
  12473. k = s.iterations,
  12474. w = s.width,
  12475. h = s.height;
  12476. /* Initialize positions randomly near the center. */
  12477. for (var i = 0, n; i < nodes.length; i++) {
  12478. n = nodes[i];
  12479. if (isNaN(n.x)) n.x = w / 2 + 40 * Math.random() - 20;
  12480. if (isNaN(n.y)) n.y = h / 2 + 40 * Math.random() - 20;
  12481. }
  12482. /* Initialize the simulation. */
  12483. var sim = pv.simulation(nodes);
  12484. /* Drag force. */
  12485. sim.force(pv.Force.drag(s.dragConstant));
  12486. /* Charge (repelling) force. */
  12487. sim.force(pv.Force.charge(s.chargeConstant)
  12488. .domain(s.chargeMinDistance, s.chargeMaxDistance)
  12489. .theta(s.chargeTheta));
  12490. /* Spring (attracting) force. */
  12491. sim.force(pv.Force.spring(s.springConstant)
  12492. .damping(s.springDamping)
  12493. .length(s.springLength)
  12494. .links(links));
  12495. /* Position constraint (for interactive dragging). */
  12496. sim.constraint(pv.Constraint.position());
  12497. /* Optionally add bound constraint. TODO: better padding. */
  12498. if (s.bound) {
  12499. sim.constraint(pv.Constraint.bound().x(6, w - 6).y(6, h - 6));
  12500. }
  12501. /** @private Returns the speed of the given node, to determine cooling. */
  12502. function speed(n) {
  12503. return n.fix ? 1 : n.vx * n.vx + n.vy * n.vy;
  12504. }
  12505. /*
  12506. * If the iterations property is null (the default), the layout is
  12507. * interactive. The simulation is run until the fastest particle drops below
  12508. * an arbitrary minimum speed. Although the timer keeps firing, this speed
  12509. * calculation is fast so there is minimal CPU overhead. Note: if a particle
  12510. * is fixed for interactivity, treat this as a high speed and resume
  12511. * simulation.
  12512. */
  12513. if (k == null) {
  12514. sim.step(); // compute initial previous velocities
  12515. sim.step(); // compute initial velocities
  12516. /* Add the simulation state to the bound list. */
  12517. var force = s.$force = this.binds.$force = {
  12518. next: this.binds.$force,
  12519. nodes: nodes,
  12520. min: 1e-4 * (links.length + 1),
  12521. sim: sim
  12522. };
  12523. /* Start the timer, if not already started. */
  12524. if (!this.$timer) this.$timer = setInterval(function() {
  12525. var render = false;
  12526. for (var f = that.binds.$force; f; f = f.next) {
  12527. if (pv.max(f.nodes, speed) > f.min) {
  12528. f.sim.step();
  12529. render = true;
  12530. }
  12531. }
  12532. if (render) that.render();
  12533. }, 42);
  12534. } else for (var i = 0; i < k; i++) {
  12535. sim.step();
  12536. }
  12537. };
  12538. /**
  12539. * Constructs a new, empty cluster layout. Layouts are not typically
  12540. * constructed directly; instead, they are added to an existing panel via
  12541. * {@link pv.Mark#add}.
  12542. *
  12543. * @class Implements a hierarchical layout using the cluster (or dendrogram)
  12544. * algorithm. This layout provides both node-link and space-filling
  12545. * implementations of cluster diagrams. In many ways it is similar to
  12546. * {@link pv.Layout.Partition}, except that leaf nodes are positioned at maximum
  12547. * depth, and the depth of internal nodes is based on their distance from their
  12548. * deepest descendant, rather than their distance from the root.
  12549. *
  12550. * <p>The cluster layout supports a "group" property, which if true causes
  12551. * siblings to be positioned closer together than unrelated nodes at the same
  12552. * depth. Unlike the partition layout, this layout does not support dynamic
  12553. * sizing for leaf nodes; all leaf nodes are the same size.
  12554. *
  12555. * <p>For more details on how to use this layout, see
  12556. * {@link pv.Layout.Hierarchy}.
  12557. *
  12558. * @see pv.Layout.Cluster.Fill
  12559. * @extends pv.Layout.Hierarchy
  12560. */
  12561. pv.Layout.Cluster = function() {
  12562. pv.Layout.Hierarchy.call(this);
  12563. var interpolate, // cached interpolate
  12564. buildImplied = this.buildImplied;
  12565. /** @private Cache layout state to optimize properties. */
  12566. this.buildImplied = function(s) {
  12567. buildImplied.call(this, s);
  12568. interpolate
  12569. = /^(top|bottom)$/.test(s.orient) ? "step-before"
  12570. : /^(left|right)$/.test(s.orient) ? "step-after"
  12571. : "linear";
  12572. };
  12573. this.link.interpolate(function() { return interpolate; });
  12574. };
  12575. pv.Layout.Cluster.prototype = pv.extend(pv.Layout.Hierarchy)
  12576. .property("group", Number)
  12577. .property("orient", String)
  12578. .property("innerRadius", Number)
  12579. .property("outerRadius", Number);
  12580. /**
  12581. * The group parameter; defaults to 0, disabling grouping of siblings. If this
  12582. * parameter is set to a positive number (or true, which is equivalent to 1),
  12583. * then additional space will be allotted between sibling groups. In other
  12584. * words, siblings (nodes that share the same parent) will be positioned more
  12585. * closely than nodes at the same depth that do not share a parent.
  12586. *
  12587. * @type number
  12588. * @name pv.Layout.Cluster.prototype.group
  12589. */
  12590. /**
  12591. * The orientation. The default orientation is "top", which means that the root
  12592. * node is placed on the top edge, leaf nodes appear on the bottom edge, and
  12593. * internal nodes are in-between. The following orientations are supported:<ul>
  12594. *
  12595. * <li>left - left-to-right.
  12596. * <li>right - right-to-left.
  12597. * <li>top - top-to-bottom.
  12598. * <li>bottom - bottom-to-top.
  12599. * <li>radial - radially, with the root at the center.</ul>
  12600. *
  12601. * @type string
  12602. * @name pv.Layout.Cluster.prototype.orient
  12603. */
  12604. /**
  12605. * The inner radius; defaults to 0. This property applies only to radial
  12606. * orientations, and can be used to compress the layout radially. Note that for
  12607. * the node-link implementation, the root node is always at the center,
  12608. * regardless of the value of this property; this property only affects internal
  12609. * and leaf nodes. For the space-filling implementation, a non-zero value of
  12610. * this property will result in the root node represented as a ring rather than
  12611. * a circle.
  12612. *
  12613. * @type number
  12614. * @name pv.Layout.Cluster.prototype.innerRadius
  12615. */
  12616. /**
  12617. * The outer radius; defaults to fill the containing panel, based on the height
  12618. * and width of the layout. If the layout has no height and width specified, it
  12619. * will extend to fill the enclosing panel.
  12620. *
  12621. * @type number
  12622. * @name pv.Layout.Cluster.prototype.outerRadius
  12623. */
  12624. /**
  12625. * Defaults for cluster layouts. The default group parameter is 0 and the
  12626. * default orientation is "top".
  12627. *
  12628. * @type pv.Layout.Cluster
  12629. */
  12630. pv.Layout.Cluster.prototype.defaults = new pv.Layout.Cluster()
  12631. .extend(pv.Layout.Hierarchy.prototype.defaults)
  12632. .group(0)
  12633. .orient("top");
  12634. /** @private */
  12635. pv.Layout.Cluster.prototype.buildImplied = function(s) {
  12636. if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) return;
  12637. var root = s.nodes[0],
  12638. group = s.group,
  12639. breadth,
  12640. depth,
  12641. leafCount = 0,
  12642. leafIndex = .5 - group / 2;
  12643. /* Count the leaf nodes and compute the depth of descendants. */
  12644. var p = undefined;
  12645. root.visitAfter(function(n) {
  12646. if (n.firstChild) {
  12647. n.depth = 1 + pv.max(n.childNodes, function(n) { return n.depth; });
  12648. } else {
  12649. if (group && (p != n.parentNode)) {
  12650. p = n.parentNode;
  12651. leafCount += group;
  12652. }
  12653. leafCount++;
  12654. n.depth = 0;
  12655. }
  12656. });
  12657. breadth = 1 / leafCount;
  12658. depth = 1 / root.depth;
  12659. /* Compute the unit breadth and depth of each node. */
  12660. var p = undefined;
  12661. root.visitAfter(function(n) {
  12662. if (n.firstChild) {
  12663. n.breadth = pv.mean(n.childNodes, function(n) { return n.breadth; });
  12664. } else {
  12665. if (group && (p != n.parentNode)) {
  12666. p = n.parentNode;
  12667. leafIndex += group;
  12668. }
  12669. n.breadth = breadth * leafIndex++;
  12670. }
  12671. n.depth = 1 - n.depth * depth;
  12672. });
  12673. /* Compute breadth and depth ranges for space-filling layouts. */
  12674. root.visitAfter(function(n) {
  12675. n.minBreadth = n.firstChild
  12676. ? n.firstChild.minBreadth
  12677. : (n.breadth - breadth / 2);
  12678. n.maxBreadth = n.firstChild
  12679. ? n.lastChild.maxBreadth
  12680. : (n.breadth + breadth / 2);
  12681. });
  12682. root.visitBefore(function(n) {
  12683. n.minDepth = n.parentNode
  12684. ? n.parentNode.maxDepth
  12685. : 0;
  12686. n.maxDepth = n.parentNode
  12687. ? (n.depth + root.depth)
  12688. : (n.minDepth + 2 * root.depth);
  12689. });
  12690. root.minDepth = -depth;
  12691. pv.Layout.Hierarchy.NodeLink.buildImplied.call(this, s);
  12692. };
  12693. /**
  12694. * Constructs a new, empty space-filling cluster layout. Layouts are not
  12695. * typically constructed directly; instead, they are added to an existing panel
  12696. * via {@link pv.Mark#add}.
  12697. *
  12698. * @class A variant of cluster layout that is space-filling. The meaning of the
  12699. * exported mark prototypes changes slightly in the space-filling
  12700. * implementation:<ul>
  12701. *
  12702. * <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Bar} for
  12703. * non-radial orientations, and a {@link pv.Wedge} for radial orientations.
  12704. *
  12705. * <p><li><tt>link</tt> - unsupported; undefined. Links are encoded implicitly
  12706. * in the arrangement of the space-filling nodes.
  12707. *
  12708. * <p><li><tt>label</tt> - for rendering node labels; typically a
  12709. * {@link pv.Label}.
  12710. *
  12711. * </ul>For more details on how to use this layout, see
  12712. * {@link pv.Layout.Cluster}.
  12713. *
  12714. * @extends pv.Layout.Cluster
  12715. */
  12716. pv.Layout.Cluster.Fill = function() {
  12717. pv.Layout.Cluster.call(this);
  12718. pv.Layout.Hierarchy.Fill.constructor.call(this);
  12719. };
  12720. pv.Layout.Cluster.Fill.prototype = pv.extend(pv.Layout.Cluster);
  12721. /** @private */
  12722. pv.Layout.Cluster.Fill.prototype.buildImplied = function(s) {
  12723. if (pv.Layout.Cluster.prototype.buildImplied.call(this, s)) return;
  12724. pv.Layout.Hierarchy.Fill.buildImplied.call(this, s);
  12725. };
  12726. /**
  12727. * Constructs a new, empty partition layout. Layouts are not typically
  12728. * constructed directly; instead, they are added to an existing panel via
  12729. * {@link pv.Mark#add}.
  12730. *
  12731. * @class Implemeents a hierarchical layout using the partition (or sunburst,
  12732. * icicle) algorithm. This layout provides both node-link and space-filling
  12733. * implementations of partition diagrams. In many ways it is similar to
  12734. * {@link pv.Layout.Cluster}, except that leaf nodes are positioned based on
  12735. * their distance from the root.
  12736. *
  12737. * <p>The partition layout support dynamic sizing for leaf nodes, if a
  12738. * {@link #size} psuedo-property is specified. The default size function returns
  12739. * 1, causing all leaf nodes to be sized equally, and all internal nodes to be
  12740. * sized by the number of leaf nodes they have as descendants.
  12741. *
  12742. * <p>The size function can be used in conjunction with the order property,
  12743. * which allows the nodes to the sorted by the computed size. Note: for sorting
  12744. * based on other data attributes, simply use the default <tt>null</tt> for the
  12745. * order property, and sort the nodes beforehand using the {@link pv.Dom}
  12746. * operator.
  12747. *
  12748. * <p>For more details on how to use this layout, see
  12749. * {@link pv.Layout.Hierarchy}.
  12750. *
  12751. * @see pv.Layout.Partition.Fill
  12752. * @extends pv.Layout.Hierarchy
  12753. */
  12754. pv.Layout.Partition = function() {
  12755. pv.Layout.Hierarchy.call(this);
  12756. };
  12757. pv.Layout.Partition.prototype = pv.extend(pv.Layout.Hierarchy)
  12758. .property("order", String) // null, ascending, descending?
  12759. .property("orient", String) // top, left, right, bottom, radial
  12760. .property("innerRadius", Number)
  12761. .property("outerRadius", Number);
  12762. /**
  12763. * The sibling node order. The default order is <tt>null</tt>, which means to
  12764. * use the sibling order specified by the nodes property as-is. A value of
  12765. * "ascending" will sort siblings in ascending order of size, while "descending"
  12766. * will do the reverse. For sorting based on data attributes other than size,
  12767. * use the default <tt>null</tt> for the order property, and sort the nodes
  12768. * beforehand using the {@link pv.Dom} operator.
  12769. *
  12770. * @see pv.Dom.Node#sort
  12771. * @type string
  12772. * @name pv.Layout.Partition.prototype.order
  12773. */
  12774. /**
  12775. * The orientation. The default orientation is "top", which means that the root
  12776. * node is placed on the top edge, leaf nodes appear at the bottom, and internal
  12777. * nodes are in-between. The following orientations are supported:<ul>
  12778. *
  12779. * <li>left - left-to-right.
  12780. * <li>right - right-to-left.
  12781. * <li>top - top-to-bottom.
  12782. * <li>bottom - bottom-to-top.
  12783. * <li>radial - radially, with the root at the center.</ul>
  12784. *
  12785. * @type string
  12786. * @name pv.Layout.Partition.prototype.orient
  12787. */
  12788. /**
  12789. * The inner radius; defaults to 0. This property applies only to radial
  12790. * orientations, and can be used to compress the layout radially. Note that for
  12791. * the node-link implementation, the root node is always at the center,
  12792. * regardless of the value of this property; this property only affects internal
  12793. * and leaf nodes. For the space-filling implementation, a non-zero value of
  12794. * this property will result in the root node represented as a ring rather than
  12795. * a circle.
  12796. *
  12797. * @type number
  12798. * @name pv.Layout.Partition.prototype.innerRadius
  12799. */
  12800. /**
  12801. * The outer radius; defaults to fill the containing panel, based on the height
  12802. * and width of the layout. If the layout has no height and width specified, it
  12803. * will extend to fill the enclosing panel.
  12804. *
  12805. * @type number
  12806. * @name pv.Layout.Partition.prototype.outerRadius
  12807. */
  12808. /**
  12809. * Default properties for partition layouts. The default orientation is "top".
  12810. *
  12811. * @type pv.Layout.Partition
  12812. */
  12813. pv.Layout.Partition.prototype.defaults = new pv.Layout.Partition()
  12814. .extend(pv.Layout.Hierarchy.prototype.defaults)
  12815. .orient("top");
  12816. /** @private */
  12817. pv.Layout.Partition.prototype.$size = function() { return 1; };
  12818. /**
  12819. * Specifies the sizing function. By default, a sizing function is disabled and
  12820. * all nodes are given constant size. The sizing function is invoked for each
  12821. * leaf node in the tree (passed to the constructor).
  12822. *
  12823. * <p>For example, if the tree data structure represents a file system, with
  12824. * files as leaf nodes, and each file has a <tt>bytes</tt> attribute, you can
  12825. * specify a size function as:
  12826. *
  12827. * <pre> .size(function(d) d.bytes)</pre>
  12828. *
  12829. * As with other properties, a size function may specify additional arguments to
  12830. * access the data associated with the layout and any enclosing panels.
  12831. *
  12832. * @param {function} f the new sizing function.
  12833. * @returns {pv.Layout.Partition} this.
  12834. */
  12835. pv.Layout.Partition.prototype.size = function(f) {
  12836. this.$size = f;
  12837. return this;
  12838. };
  12839. /** @private */
  12840. pv.Layout.Partition.prototype.buildImplied = function(s) {
  12841. if (pv.Layout.Hierarchy.prototype.buildImplied.call(this, s)) return;
  12842. var that = this,
  12843. root = s.nodes[0],
  12844. stack = pv.Mark.stack,
  12845. maxDepth = 0;
  12846. /* Recursively compute the tree depth and node size. */
  12847. stack.unshift(null);
  12848. root.visitAfter(function(n, i) {
  12849. if (i > maxDepth) maxDepth = i;
  12850. n.size = n.firstChild
  12851. ? pv.sum(n.childNodes, function(n) { return n.size; })
  12852. : that.$size.apply(that, (stack[0] = n, stack));
  12853. });
  12854. stack.shift();
  12855. /* Order */
  12856. switch (s.order) {
  12857. case "ascending": root.sort(function(a, b) { return a.size - b.size; }); break;
  12858. case "descending": root.sort(function(b, a) { return a.size - b.size; }); break;
  12859. }
  12860. /* Compute the unit breadth and depth of each node. */
  12861. var ds = 1 / maxDepth;
  12862. root.minBreadth = 0;
  12863. root.breadth = .5;
  12864. root.maxBreadth = 1;
  12865. root.visitBefore(function(n) {
  12866. var b = n.minBreadth, s = n.maxBreadth - b;
  12867. for (var c = n.firstChild; c; c = c.nextSibling) {
  12868. c.minBreadth = b;
  12869. c.maxBreadth = b += (c.size / n.size) * s;
  12870. c.breadth = (b + c.minBreadth) / 2;
  12871. }
  12872. });
  12873. root.visitAfter(function(n, i) {
  12874. n.minDepth = (i - 1) * ds;
  12875. n.maxDepth = n.depth = i * ds;
  12876. });
  12877. pv.Layout.Hierarchy.NodeLink.buildImplied.call(this, s);
  12878. };
  12879. /**
  12880. * Constructs a new, empty space-filling partition layout. Layouts are not
  12881. * typically constructed directly; instead, they are added to an existing panel
  12882. * via {@link pv.Mark#add}.
  12883. *
  12884. * @class A variant of partition layout that is space-filling. The meaning of
  12885. * the exported mark prototypes changes slightly in the space-filling
  12886. * implementation:<ul>
  12887. *
  12888. * <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Bar} for
  12889. * non-radial orientations, and a {@link pv.Wedge} for radial orientations.
  12890. *
  12891. * <p><li><tt>link</tt> - unsupported; undefined. Links are encoded implicitly
  12892. * in the arrangement of the space-filling nodes.
  12893. *
  12894. * <p><li><tt>label</tt> - for rendering node labels; typically a
  12895. * {@link pv.Label}.
  12896. *
  12897. * </ul>For more details on how to use this layout, see
  12898. * {@link pv.Layout.Partition}.
  12899. *
  12900. * @extends pv.Layout.Partition
  12901. */
  12902. pv.Layout.Partition.Fill = function() {
  12903. pv.Layout.Partition.call(this);
  12904. pv.Layout.Hierarchy.Fill.constructor.call(this);
  12905. };
  12906. pv.Layout.Partition.Fill.prototype = pv.extend(pv.Layout.Partition);
  12907. /** @private */
  12908. pv.Layout.Partition.Fill.prototype.buildImplied = function(s) {
  12909. if (pv.Layout.Partition.prototype.buildImplied.call(this, s)) return;
  12910. pv.Layout.Hierarchy.Fill.buildImplied.call(this, s);
  12911. };
  12912. /**
  12913. * Constructs a new, empty arc layout. Layouts are not typically constructed
  12914. * directly; instead, they are added to an existing panel via
  12915. * {@link pv.Mark#add}.
  12916. *
  12917. * @class Implements a layout for arc diagrams. An arc diagram is a network
  12918. * visualization with a one-dimensional layout of nodes, using circular arcs to
  12919. * render links between nodes. For undirected networks, arcs are rendering on a
  12920. * single side; this makes arc diagrams useful as annotations to other
  12921. * two-dimensional network layouts, such as rollup, matrix or table layouts. For
  12922. * directed networks, links in opposite directions can be rendered on opposite
  12923. * sides using <tt>directed(true)</tt>.
  12924. *
  12925. * <p>Arc layouts are particularly sensitive to node ordering; for best results,
  12926. * order the nodes such that related nodes are close to each other. A poor
  12927. * (e.g., random) order may result in large arcs with crossovers that impede
  12928. * visual processing. A future improvement to this layout may include automatic
  12929. * reordering using, e.g., spectral graph layout or simulated annealing.
  12930. *
  12931. * <p>This visualization technique is related to that developed by
  12932. * M. Wattenberg, <a
  12933. * href="http://www.research.ibm.com/visual/papers/arc-diagrams.pdf">"Arc
  12934. * Diagrams: Visualizing Structure in Strings"</a> in <i>IEEE InfoVis</i>, 2002.
  12935. * However, this implementation is limited to simple node-link networks, as
  12936. * opposed to structures with hierarchical self-similarity (such as strings).
  12937. *
  12938. * <p>As with other network layouts, three mark prototypes are provided:<ul>
  12939. *
  12940. * <li><tt>node</tt> - for rendering nodes; typically a {@link pv.Dot}.
  12941. * <li><tt>link</tt> - for rendering links; typically a {@link pv.Line}.
  12942. * <li><tt>label</tt> - for rendering node labels; typically a {@link pv.Label}.
  12943. *
  12944. * </ul>For more details on how this layout is structured and can be customized,
  12945. * see {@link pv.Layout.Network}.
  12946. *
  12947. * @extends pv.Layout.Network
  12948. **/
  12949. pv.Layout.Arc = function() {
  12950. pv.Layout.Network.call(this);
  12951. var interpolate, // cached interpolate
  12952. directed, // cached directed
  12953. reverse, // cached reverse
  12954. buildImplied = this.buildImplied;
  12955. /** @private Cache layout state to optimize properties. */
  12956. this.buildImplied = function(s) {
  12957. buildImplied.call(this, s);
  12958. directed = s.directed;
  12959. interpolate = s.orient == "radial" ? "linear" : "polar";
  12960. reverse = s.orient == "right" || s.orient == "top";
  12961. };
  12962. /* Override link properties to handle directedness and orientation. */
  12963. this.link
  12964. .data(function(p) {
  12965. var s = p.sourceNode, t = p.targetNode;
  12966. return reverse != (directed || (s.breadth < t.breadth)) ? [s, t] : [t, s];
  12967. })
  12968. .interpolate(function() { return interpolate; });
  12969. };
  12970. pv.Layout.Arc.prototype = pv.extend(pv.Layout.Network)
  12971. .property("orient", String)
  12972. .property("directed", Boolean);
  12973. /**
  12974. * Default properties for arc layouts. By default, the orientation is "bottom".
  12975. *
  12976. * @type pv.Layout.Arc
  12977. */
  12978. pv.Layout.Arc.prototype.defaults = new pv.Layout.Arc()
  12979. .extend(pv.Layout.Network.prototype.defaults)
  12980. .orient("bottom");
  12981. /**
  12982. * Specifies an optional sort function. The sort function follows the same
  12983. * comparator contract required by {@link pv.Dom.Node#sort}. Specifying a sort
  12984. * function provides an alternative to sort the nodes as they are specified by
  12985. * the <tt>nodes</tt> property; the main advantage of doing this is that the
  12986. * comparator function can access implicit fields populated by the network
  12987. * layout, such as the <tt>linkDegree</tt>.
  12988. *
  12989. * <p>Note that arc diagrams are particularly sensitive to order. This is
  12990. * referred to as the seriation problem, and many different techniques exist to
  12991. * find good node orders that emphasize clusters, such as spectral layout and
  12992. * simulated annealing.
  12993. *
  12994. * @param {function} f comparator function for nodes.
  12995. * @returns {pv.Layout.Arc} this.
  12996. */
  12997. pv.Layout.Arc.prototype.sort = function(f) {
  12998. this.$sort = f;
  12999. return this;
  13000. };
  13001. /** @private Populates the x, y and angle attributes on the nodes. */
  13002. pv.Layout.Arc.prototype.buildImplied = function(s) {
  13003. if (pv.Layout.Network.prototype.buildImplied.call(this, s)) return;
  13004. var nodes = s.nodes,
  13005. orient = s.orient,
  13006. sort = this.$sort,
  13007. index = pv.range(nodes.length),
  13008. w = s.width,
  13009. h = s.height,
  13010. r = Math.min(w, h) / 2;
  13011. /* Sort the nodes. */
  13012. if (sort) index.sort(function(a, b) { return sort(nodes[a], nodes[b]); });
  13013. /** @private Returns the mid-angle, given the breadth. */
  13014. function midAngle(b) {
  13015. switch (orient) {
  13016. case "top": return -Math.PI / 2;
  13017. case "bottom": return Math.PI / 2;
  13018. case "left": return Math.PI;
  13019. case "right": return 0;
  13020. case "radial": return (b - .25) * 2 * Math.PI;
  13021. }
  13022. }
  13023. /** @private Returns the x-position, given the breadth. */
  13024. function x(b) {
  13025. switch (orient) {
  13026. case "top":
  13027. case "bottom": return b * w;
  13028. case "left": return 0;
  13029. case "right": return w;
  13030. case "radial": return w / 2 + r * Math.cos(midAngle(b));
  13031. }
  13032. }
  13033. /** @private Returns the y-position, given the breadth. */
  13034. function y(b) {
  13035. switch (orient) {
  13036. case "top": return 0;
  13037. case "bottom": return h;
  13038. case "left":
  13039. case "right": return b * h;
  13040. case "radial": return h / 2 + r * Math.sin(midAngle(b));
  13041. }
  13042. }
  13043. /* Populate the x, y and mid-angle attributes. */
  13044. for (var i = 0; i < nodes.length; i++) {
  13045. var n = nodes[index[i]], b = n.breadth = (i + .5) / nodes.length;
  13046. n.x = x(b);
  13047. n.y = y(b);
  13048. n.midAngle = midAngle(b);
  13049. }
  13050. };
  13051. /**
  13052. * The orientation. The default orientation is "left", which means that nodes
  13053. * will be positioned from left-to-right in the order they are specified in the
  13054. * <tt>nodes</tt> property. The following orientations are supported:<ul>
  13055. *
  13056. * <li>left - left-to-right.
  13057. * <li>right - right-to-left.
  13058. * <li>top - top-to-bottom.
  13059. * <li>bottom - bottom-to-top.
  13060. * <li>radial - radially, starting at 12 o'clock and proceeding clockwise.</ul>
  13061. *
  13062. * @type string
  13063. * @name pv.Layout.Arc.prototype.orient
  13064. */
  13065. /**
  13066. * Whether this arc digram is directed (bidirectional); only applies to
  13067. * non-radial orientations. By default, arc digrams are undirected, such that
  13068. * all arcs appear on one side. If the arc digram is directed, then forward
  13069. * links are drawn on the conventional side (the same as as undirected
  13070. * links--right, left, bottom and top for left, right, top and bottom,
  13071. * respectively), while reverse links are drawn on the opposite side.
  13072. *
  13073. * @type boolean
  13074. * @name pv.Layout.Arc.prototype.directed
  13075. */
  13076. /**
  13077. * Constructs a new, empty horizon layout. Layouts are not typically constructed
  13078. * directly; instead, they are added to an existing panel via
  13079. * {@link pv.Mark#add}.
  13080. *
  13081. * @class Implements a horizon layout, which is a variation of a single-series
  13082. * area chart where the area is folded into multiple bands. Color is used to
  13083. * encode band, allowing the size of the chart to be reduced significantly
  13084. * without impeding readability. This layout algorithm is based on the work of
  13085. * J. Heer, N. Kong and M. Agrawala in <a
  13086. * href="http://hci.stanford.edu/publications/2009/heer-horizon-chi09.pdf">"Sizing
  13087. * the Horizon: The Effects of Chart Size and Layering on the Graphical
  13088. * Perception of Time Series Visualizations"</a>, CHI 2009.
  13089. *
  13090. * <p>This layout exports a single <tt>band</tt> mark prototype, which is
  13091. * intended to be used with an area mark. The band mark is contained in a panel
  13092. * which is replicated per band (and for negative/positive bands). For example,
  13093. * to create a simple horizon graph given an array of numbers:
  13094. *
  13095. * <pre>vis.add(pv.Layout.Horizon)
  13096. * .bands(n)
  13097. * .band.add(pv.Area)
  13098. * .data(data)
  13099. * .left(function() this.index * 35)
  13100. * .height(function(d) d * 40);</pre>
  13101. *
  13102. * The layout can be further customized by changing the number of bands, and
  13103. * toggling whether the negative bands are mirrored or offset. (See the
  13104. * above-referenced paper for guidance.)
  13105. *
  13106. * <p>The <tt>fillStyle</tt> of the area can be overridden, though typically it
  13107. * is easier to customize the layout's behavior through the custom
  13108. * <tt>backgroundStyle</tt>, <tt>positiveStyle</tt> and <tt>negativeStyle</tt>
  13109. * properties. By default, the background is white, positive bands are blue, and
  13110. * negative bands are red. For the most accurate presentation, use fully-opaque
  13111. * colors of equal intensity for the negative and positive bands.
  13112. *
  13113. * @extends pv.Layout
  13114. */
  13115. pv.Layout.Horizon = function() {
  13116. pv.Layout.call(this);
  13117. var that = this,
  13118. bands, // cached bands
  13119. mode, // cached mode
  13120. size, // cached height
  13121. fill, // cached background style
  13122. red, // cached negative color (ramp)
  13123. blue, // cached positive color (ramp)
  13124. buildImplied = this.buildImplied;
  13125. /** @private Cache the layout state to optimize properties. */
  13126. this.buildImplied = function(s) {
  13127. buildImplied.call(this, s);
  13128. bands = s.bands;
  13129. mode = s.mode;
  13130. size = Math.round((mode == "color" ? .5 : 1) * s.height);
  13131. fill = s.backgroundStyle;
  13132. red = pv.ramp(fill, s.negativeStyle).domain(0, bands);
  13133. blue = pv.ramp(fill, s.positiveStyle).domain(0, bands);
  13134. };
  13135. var bands = new pv.Panel()
  13136. .data(function() { return pv.range(bands * 2); })
  13137. .overflow("hidden")
  13138. .height(function() { return size; })
  13139. .top(function(i) { return mode == "color" ? (i & 1) * size : 0; })
  13140. .fillStyle(function(i) { return i ? null : fill; });
  13141. /**
  13142. * The band prototype. This prototype is intended to be used with an Area
  13143. * mark to render the horizon bands.
  13144. *
  13145. * @type pv.Mark
  13146. * @name pv.Layout.Horizon.prototype.band
  13147. */
  13148. this.band = new pv.Mark()
  13149. .top(function(d, i) {
  13150. return mode == "mirror" && i & 1
  13151. ? (i + 1 >> 1) * size
  13152. : null;
  13153. })
  13154. .bottom(function(d, i) {
  13155. return mode == "mirror"
  13156. ? (i & 1 ? null : (i + 1 >> 1) * -size)
  13157. : ((i & 1 || -1) * (i + 1 >> 1) * size);
  13158. })
  13159. .fillStyle(function(d, i) {
  13160. return (i & 1 ? red : blue)((i >> 1) + 1);
  13161. });
  13162. this.band.add = function(type) {
  13163. return that.add(pv.Panel).extend(bands).add(type).extend(this);
  13164. };
  13165. };
  13166. pv.Layout.Horizon.prototype = pv.extend(pv.Layout)
  13167. .property("bands", Number)
  13168. .property("mode", String)
  13169. .property("backgroundStyle", pv.color)
  13170. .property("positiveStyle", pv.color)
  13171. .property("negativeStyle", pv.color);
  13172. /**
  13173. * Default properties for horizon layouts. By default, there are two bands, the
  13174. * mode is "offset", the background style is "white", the positive style is
  13175. * blue, negative style is red.
  13176. *
  13177. * @type pv.Layout.Horizon
  13178. */
  13179. pv.Layout.Horizon.prototype.defaults = new pv.Layout.Horizon()
  13180. .extend(pv.Layout.prototype.defaults)
  13181. .bands(2)
  13182. .mode("offset")
  13183. .backgroundStyle("white")
  13184. .positiveStyle("#1f77b4")
  13185. .negativeStyle("#d62728");
  13186. /**
  13187. * The horizon mode: offset, mirror, or color. The default is "offset".
  13188. *
  13189. * @type string
  13190. * @name pv.Layout.Horizon.prototype.mode
  13191. */
  13192. /**
  13193. * The number of bands. Must be at least one. The default value is two.
  13194. *
  13195. * @type number
  13196. * @name pv.Layout.Horizon.prototype.bands
  13197. */
  13198. /**
  13199. * The positive band color; if non-null, the interior of positive bands are
  13200. * filled with the specified color. The default value of this property is blue.
  13201. * For accurate blending, this color should be fully opaque.
  13202. *
  13203. * @type pv.Color
  13204. * @name pv.Layout.Horizon.prototype.positiveStyle
  13205. */
  13206. /**
  13207. * The negative band color; if non-null, the interior of negative bands are
  13208. * filled with the specified color. The default value of this property is red.
  13209. * For accurate blending, this color should be fully opaque.
  13210. *
  13211. * @type pv.Color
  13212. * @name pv.Layout.Horizon.prototype.negativeStyle
  13213. */
  13214. /**
  13215. * The background color. The panel background is filled with the specified
  13216. * color, and the negative and positive bands are filled with an interpolated
  13217. * color between this color and the respective band color. The default value of
  13218. * this property is white. For accurate blending, this color should be fully
  13219. * opaque.
  13220. *
  13221. * @type pv.Color
  13222. * @name pv.Layout.Horizon.prototype.backgroundStyle
  13223. */
  13224. /**
  13225. * Constructs a new, empty rollup network layout. Layouts are not typically
  13226. * constructed directly; instead, they are added to an existing panel via
  13227. * {@link pv.Mark#add}.
  13228. *
  13229. * @class Implements a network visualization using a node-link diagram where
  13230. * nodes are rolled up along two dimensions. This implementation is based on the
  13231. * "PivotGraph" designed by Martin Wattenberg:
  13232. *
  13233. * <blockquote>The method is designed for graphs that are "multivariate", i.e.,
  13234. * where each node is associated with several attributes. Unlike visualizations
  13235. * which emphasize global graph topology, PivotGraph uses a simple grid-based
  13236. * approach to focus on the relationship between node attributes &amp;
  13237. * connections.</blockquote>
  13238. *
  13239. * This layout requires two psuedo-properties to be specified, which assign node
  13240. * positions along the two dimensions {@link #x} and {@link #y}, corresponding
  13241. * to the left and top properties, respectively. Typically, these functions are
  13242. * specified using an {@link pv.Scale.ordinal}. Nodes that share the same
  13243. * position in <i>x</i> and <i>y</i> are "rolled up" into a meta-node, and
  13244. * similarly links are aggregated between meta-nodes. For example, to construct
  13245. * a rollup to analyze links by gender and affiliation, first define two ordinal
  13246. * scales:
  13247. *
  13248. * <pre>var x = pv.Scale.ordinal(nodes, function(d) d.gender).split(0, w),
  13249. * y = pv.Scale.ordinal(nodes, function(d) d.aff).split(0, h);</pre>
  13250. *
  13251. * Next, define the position psuedo-properties:
  13252. *
  13253. * <pre> .x(function(d) x(d.gender))
  13254. * .y(function(d) y(d.aff))</pre>
  13255. *
  13256. * Linear and other quantitative scales can alternatively be used to position
  13257. * the nodes along either dimension. Note, however, that the rollup requires
  13258. * that the positions match exactly, and thus ordinal scales are recommended to
  13259. * avoid precision errors.
  13260. *
  13261. * <p>Note that because this layout provides a visualization of the rolled up
  13262. * graph, the data properties for the mark prototypes (<tt>node</tt>,
  13263. * <tt>link</tt> and <tt>label</tt>) are different from most other network
  13264. * layouts: they reference the rolled-up nodes and links, rather than the nodes
  13265. * and links of the full network. The underlying nodes and links for each
  13266. * rolled-up node and link can be accessed via the <tt>nodes</tt> and
  13267. * <tt>links</tt> attributes, respectively. The aggregated link values for
  13268. * rolled-up links can similarly be accessed via the <tt>linkValue</tt>
  13269. * attribute.
  13270. *
  13271. * <p>For undirected networks, links are duplicated in both directions. For
  13272. * directed networks, use <tt>directed(true)</tt>. The graph is assumed to be
  13273. * undirected by default.
  13274. *
  13275. * @extends pv.Layout.Network
  13276. * @see <a href="http://www.research.ibm.com/visual/papers/pivotgraph.pdf"
  13277. * >"Visual Exploration of Multivariate Graphs"</a> by M. Wattenberg, CHI 2006.
  13278. */
  13279. pv.Layout.Rollup = function() {
  13280. pv.Layout.Network.call(this);
  13281. var that = this,
  13282. nodes, // cached rollup nodes
  13283. links, // cached rollup links
  13284. buildImplied = that.buildImplied;
  13285. /** @private Cache layout state to optimize properties. */
  13286. this.buildImplied = function(s) {
  13287. buildImplied.call(this, s);
  13288. nodes = s.$rollup.nodes;
  13289. links = s.$rollup.links;
  13290. };
  13291. /* Render rollup nodes. */
  13292. this.node
  13293. .data(function() { return nodes; })
  13294. .size(function(d) { return d.nodes.length * 20; });
  13295. /* Render rollup links. */
  13296. this.link
  13297. .interpolate("polar")
  13298. .eccentricity(.8);
  13299. this.link.add = function(type) {
  13300. return that.add(pv.Panel)
  13301. .data(function() { return links; })
  13302. .add(type)
  13303. .extend(this);
  13304. };
  13305. };
  13306. pv.Layout.Rollup.prototype = pv.extend(pv.Layout.Network)
  13307. .property("directed", Boolean);
  13308. /**
  13309. * Whether the underlying network is directed. By default, the graph is assumed
  13310. * to be undirected, and links are rendered in both directions. If the network
  13311. * is directed, then forward links are drawn above the diagonal, while reverse
  13312. * links are drawn below.
  13313. *
  13314. * @type boolean
  13315. * @name pv.Layout.Rollup.prototype.directed
  13316. */
  13317. /**
  13318. * Specifies the <i>x</i>-position function used to rollup nodes. The rolled up
  13319. * nodes are positioned horizontally using the return values from the given
  13320. * function. Typically the function is specified as an ordinal scale. For
  13321. * single-dimension rollups, a constant value can be specified.
  13322. *
  13323. * @param {function} f the <i>x</i>-position function.
  13324. * @returns {pv.Layout.Rollup} this.
  13325. * @see pv.Scale.ordinal
  13326. */
  13327. pv.Layout.Rollup.prototype.x = function(f) {
  13328. this.$x = pv.functor(f);
  13329. return this;
  13330. };
  13331. /**
  13332. * Specifies the <i>y</i>-position function used to rollup nodes. The rolled up
  13333. * nodes are positioned vertically using the return values from the given
  13334. * function. Typically the function is specified as an ordinal scale. For
  13335. * single-dimension rollups, a constant value can be specified.
  13336. *
  13337. * @param {function} f the <i>y</i>-position function.
  13338. * @returns {pv.Layout.Rollup} this.
  13339. * @see pv.Scale.ordinal
  13340. */
  13341. pv.Layout.Rollup.prototype.y = function(f) {
  13342. this.$y = pv.functor(f);
  13343. return this;
  13344. };
  13345. /** @private */
  13346. pv.Layout.Rollup.prototype.buildImplied = function(s) {
  13347. if (pv.Layout.Network.prototype.buildImplied.call(this, s)) return;
  13348. var nodes = s.nodes,
  13349. links = s.links,
  13350. directed = s.directed,
  13351. n = nodes.length,
  13352. x = [],
  13353. y = [],
  13354. rnindex = 0,
  13355. rnodes = {},
  13356. rlinks = {};
  13357. /** @private */
  13358. function id(i) {
  13359. return x[i] + "," + y[i];
  13360. }
  13361. /* Iterate over the data, evaluating the x and y functions. */
  13362. var stack = pv.Mark.stack, o = {parent: this};
  13363. stack.unshift(null);
  13364. for (var i = 0; i < n; i++) {
  13365. o.index = i;
  13366. stack[0] = nodes[i];
  13367. x[i] = this.$x.apply(o, stack);
  13368. y[i] = this.$y.apply(o, stack);
  13369. }
  13370. stack.shift();
  13371. /* Compute rollup nodes. */
  13372. for (var i = 0; i < nodes.length; i++) {
  13373. var nodeId = id(i),
  13374. rn = rnodes[nodeId];
  13375. if (!rn) {
  13376. rn = rnodes[nodeId] = pv.extend(nodes[i]);
  13377. rn.index = rnindex++;
  13378. rn.x = x[i];
  13379. rn.y = y[i];
  13380. rn.nodes = [];
  13381. }
  13382. rn.nodes.push(nodes[i]);
  13383. }
  13384. /* Compute rollup links. */
  13385. for (var i = 0; i < links.length; i++) {
  13386. var source = links[i].sourceNode,
  13387. target = links[i].targetNode,
  13388. rsource = rnodes[id(source.index)],
  13389. rtarget = rnodes[id(target.index)],
  13390. reverse = !directed && rsource.index > rtarget.index,
  13391. linkId = reverse
  13392. ? rtarget.index + "," + rsource.index
  13393. : rsource.index + "," + rtarget.index,
  13394. rl = rlinks[linkId];
  13395. if (!rl) {
  13396. rl = rlinks[linkId] = {
  13397. sourceNode: rsource,
  13398. targetNode: rtarget,
  13399. linkValue: 0,
  13400. links: []
  13401. };
  13402. }
  13403. rl.links.push(links[i]);
  13404. rl.linkValue += links[i].linkValue;
  13405. }
  13406. /* Export the rolled up nodes and links to the scene. */
  13407. s.$rollup = {
  13408. nodes: pv.values(rnodes),
  13409. links: pv.values(rlinks)
  13410. };
  13411. };
  13412. /**
  13413. * Constructs a new, empty matrix network layout. Layouts are not typically
  13414. * constructed directly; instead, they are added to an existing panel via
  13415. * {@link pv.Mark#add}.
  13416. *
  13417. * @class Implements a network visualization using a matrix view. This is, in
  13418. * effect, a visualization of the graph's <i>adjacency matrix</i>: the cell at
  13419. * row <i>i</i>, column <i>j</i>, corresponds to the link from node <i>i</i> to
  13420. * node <i>j</i>. The fill color of each cell is binary by default, and
  13421. * corresponds to whether a link exists between the two nodes. If the underlying
  13422. * graph has links with variable values, the <tt>fillStyle</tt> property can be
  13423. * substited to use an appropriate color function, such as {@link pv.ramp}.
  13424. *
  13425. * <p>For undirected networks, the matrix is symmetric around the diagonal. For
  13426. * directed networks, links in opposite directions can be rendered on opposite
  13427. * sides of the diagonal using <tt>directed(true)</tt>. The graph is assumed to
  13428. * be undirected by default.
  13429. *
  13430. * <p>The mark prototypes for this network layout are slightly different than
  13431. * other implementations:<ul>
  13432. *
  13433. * <li><tt>node</tt> - unsupported; undefined. No mark is needed to visualize
  13434. * nodes directly, as the nodes are implicit in the location (rows and columns)
  13435. * of the links.
  13436. *
  13437. * <p><li><tt>link</tt> - for rendering links; typically a {@link pv.Bar}. The
  13438. * link mark is added directly to the layout, with the data property defined as
  13439. * all possible pairs of nodes. Each pair is represented as a
  13440. * {@link pv.Network.Layout.Link}, though the <tt>linkValue</tt> attribute may
  13441. * be 0 if no link exists in the graph.
  13442. *
  13443. * <p><li><tt>label</tt> - for rendering node labels; typically a
  13444. * {@link pv.Label}. The label mark is added directly to the layout, with the
  13445. * data property defined via the layout's <tt>nodes</tt> property; note,
  13446. * however, that the nodes are duplicated so as to provide a label across the
  13447. * top and down the side. Properties such as <tt>strokeStyle</tt> and
  13448. * <tt>fillStyle</tt> can be overridden to compute properties from node data
  13449. * dynamically.
  13450. *
  13451. * </ul>For more details on how to use this layout, see
  13452. * {@link pv.Layout.Network}.
  13453. *
  13454. * @extends pv.Layout.Network
  13455. */
  13456. pv.Layout.Matrix = function() {
  13457. pv.Layout.Network.call(this);
  13458. var that = this,
  13459. n, // cached matrix size
  13460. dx, // cached cell width
  13461. dy, // cached cell height
  13462. labels, // cached labels (array of strings)
  13463. pairs, // cached pairs (array of links)
  13464. buildImplied = that.buildImplied;
  13465. /** @private Cache layout state to optimize properties. */
  13466. this.buildImplied = function(s) {
  13467. buildImplied.call(this, s);
  13468. n = s.nodes.length;
  13469. dx = s.width / n;
  13470. dy = s.height / n;
  13471. labels = s.$matrix.labels;
  13472. pairs = s.$matrix.pairs;
  13473. };
  13474. /* Links are all pairs of nodes. */
  13475. this.link
  13476. .data(function() { return pairs; })
  13477. .left(function() { return dx * (this.index % n); })
  13478. .top(function() { return dy * Math.floor(this.index / n); })
  13479. .width(function() { return dx; })
  13480. .height(function() { return dy; })
  13481. .lineWidth(1.5)
  13482. .strokeStyle("#fff")
  13483. .fillStyle(function(l) { return l.linkValue ? "#555" : "#eee"; })
  13484. .parent = this;
  13485. /* No special add for links! */
  13486. delete this.link.add;
  13487. /* Labels are duplicated for top & left. */
  13488. this.label
  13489. .data(function() { return labels; })
  13490. .left(function() { return this.index & 1 ? dx * ((this.index >> 1) + .5) : null; })
  13491. .top(function() { return this.index & 1 ? null : dy * ((this.index >> 1) + .5); })
  13492. .textMargin(4)
  13493. .textAlign(function() { return this.index & 1 ? "left" : "right"; })
  13494. .textAngle(function() { return this.index & 1 ? -Math.PI / 2 : 0; });
  13495. /* The node mark is unused. */
  13496. delete this.node;
  13497. };
  13498. pv.Layout.Matrix.prototype = pv.extend(pv.Layout.Network)
  13499. .property("directed", Boolean);
  13500. /**
  13501. * Whether this matrix visualization is directed (bidirectional). By default,
  13502. * the graph is assumed to be undirected, such that the visualization is
  13503. * symmetric across the matrix diagonal. If the network is directed, then
  13504. * forward links are drawn above the diagonal, while reverse links are drawn
  13505. * below.
  13506. *
  13507. * @type boolean
  13508. * @name pv.Layout.Matrix.prototype.directed
  13509. */
  13510. /**
  13511. * Specifies an optional sort function. The sort function follows the same
  13512. * comparator contract required by {@link pv.Dom.Node#sort}. Specifying a sort
  13513. * function provides an alternative to sort the nodes as they are specified by
  13514. * the <tt>nodes</tt> property; the main advantage of doing this is that the
  13515. * comparator function can access implicit fields populated by the network
  13516. * layout, such as the <tt>linkDegree</tt>.
  13517. *
  13518. * <p>Note that matrix visualizations are particularly sensitive to order. This
  13519. * is referred to as the seriation problem, and many different techniques exist
  13520. * to find good node orders that emphasize clusters, such as spectral layout and
  13521. * simulated annealing.
  13522. *
  13523. * @param {function} f comparator function for nodes.
  13524. * @returns {pv.Layout.Matrix} this.
  13525. */
  13526. pv.Layout.Matrix.prototype.sort = function(f) {
  13527. this.$sort = f;
  13528. return this;
  13529. };
  13530. /** @private */
  13531. pv.Layout.Matrix.prototype.buildImplied = function(s) {
  13532. if (pv.Layout.Network.prototype.buildImplied.call(this, s)) return;
  13533. var nodes = s.nodes,
  13534. links = s.links,
  13535. sort = this.$sort,
  13536. n = nodes.length,
  13537. index = pv.range(n),
  13538. labels = [],
  13539. pairs = [],
  13540. map = {};
  13541. s.$matrix = {labels: labels, pairs: pairs};
  13542. /* Sort the nodes. */
  13543. if (sort) index.sort(function(a, b) { return sort(nodes[a], nodes[b]); });
  13544. /* Create pairs. */
  13545. for (var i = 0; i < n; i++) {
  13546. for (var j = 0; j < n; j++) {
  13547. var a = index[i],
  13548. b = index[j],
  13549. p = {
  13550. row: i,
  13551. col: j,
  13552. sourceNode: nodes[a],
  13553. targetNode: nodes[b],
  13554. linkValue: 0
  13555. };
  13556. pairs.push(map[a + "." + b] = p);
  13557. }
  13558. }
  13559. /* Create labels. */
  13560. for (var i = 0; i < n; i++) {
  13561. var a = index[i];
  13562. labels.push(nodes[a], nodes[a]);
  13563. }
  13564. /* Accumulate link values. */
  13565. for (var i = 0; i < links.length; i++) {
  13566. var l = links[i],
  13567. source = l.sourceNode.index,
  13568. target = l.targetNode.index,
  13569. value = l.linkValue;
  13570. map[source + "." + target].linkValue += value;
  13571. if (!s.directed) map[target + "." + source].linkValue += value;
  13572. }
  13573. };
  13574. // ranges (bad, satisfactory, good)
  13575. // measures (actual, forecast)
  13576. // markers (previous, goal)
  13577. /*
  13578. * Chart design based on the recommendations of Stephen Few. Implementation
  13579. * based on the work of Clint Ivy, Jamie Love, and Jason Davies.
  13580. * http://projects.instantcognition.com/protovis/bulletchart/
  13581. */
  13582. pv.Layout.Bullet = function() {
  13583. pv.Layout.call(this);
  13584. var that = this,
  13585. buildImplied = that.buildImplied,
  13586. scale = that.x = pv.Scale.linear(),
  13587. orient,
  13588. horizontal,
  13589. rangeColor,
  13590. measureColor,
  13591. x;
  13592. /** @private Cache layout state to optimize properties. */
  13593. this.buildImplied = function(s) {
  13594. buildImplied.call(this, x = s);
  13595. orient = s.orient;
  13596. horizontal = /^left|right$/.test(orient);
  13597. rangeColor = pv.ramp("#bbb", "#eee")
  13598. .domain(0, Math.max(1, x.ranges.length - 1));
  13599. measureColor = pv.ramp("steelblue", "lightsteelblue")
  13600. .domain(0, Math.max(1, x.measures.length - 1));
  13601. };
  13602. (this.range = new pv.Mark())
  13603. .data(function() { return x.ranges; })
  13604. .reverse(true)
  13605. .left(function() { return orient == "left" ? 0 : null; })
  13606. .top(function() { return orient == "top" ? 0 : null; })
  13607. .right(function() { return orient == "right" ? 0 : null; })
  13608. .bottom(function() { return orient == "bottom" ? 0 : null; })
  13609. .width(function(d) { return horizontal ? scale(d) : null; })
  13610. .height(function(d) { return horizontal ? null : scale(d); })
  13611. .fillStyle(function() { return rangeColor(this.index); })
  13612. .antialias(false)
  13613. .parent = that;
  13614. (this.measure = new pv.Mark())
  13615. .extend(this.range)
  13616. .data(function() { return x.measures; })
  13617. .left(function() { return orient == "left" ? 0 : horizontal ? null : this.parent.width() / 3.25; })
  13618. .top(function() { return orient == "top" ? 0 : horizontal ? this.parent.height() / 3.25 : null; })
  13619. .right(function() { return orient == "right" ? 0 : horizontal ? null : this.parent.width() / 3.25; })
  13620. .bottom(function() { return orient == "bottom" ? 0 : horizontal ? this.parent.height() / 3.25 : null; })
  13621. .fillStyle(function() { return measureColor(this.index); })
  13622. .parent = that;
  13623. (this.marker = new pv.Mark())
  13624. .data(function() { return x.markers; })
  13625. .left(function(d) { return orient == "left" ? scale(d) : horizontal ? null : this.parent.width() / 2; })
  13626. .top(function(d) { return orient == "top" ? scale(d) : horizontal ? this.parent.height() / 2 : null; })
  13627. .right(function(d) { return orient == "right" ? scale(d) : null; })
  13628. .bottom(function(d) { return orient == "bottom" ? scale(d) : null; })
  13629. .strokeStyle("black")
  13630. .shape("bar")
  13631. .angle(function() { return horizontal ? 0 : Math.PI / 2; })
  13632. .parent = that;
  13633. (this.tick = new pv.Mark())
  13634. .data(function() { return scale.ticks(7); })
  13635. .left(function(d) { return orient == "left" ? scale(d) : null; })
  13636. .top(function(d) { return orient == "top" ? scale(d) : null; })
  13637. .right(function(d) { return orient == "right" ? scale(d) : horizontal ? null : -6; })
  13638. .bottom(function(d) { return orient == "bottom" ? scale(d) : horizontal ? -8 : null; })
  13639. .height(function() { return horizontal ? 6 : null; })
  13640. .width(function() { return horizontal ? null : 6; })
  13641. .parent = that;
  13642. };
  13643. pv.Layout.Bullet.prototype = pv.extend(pv.Layout)
  13644. .property("orient", String) // left, right, top, bottom
  13645. .property("ranges")
  13646. .property("markers")
  13647. .property("measures")
  13648. .property("maximum", Number);
  13649. pv.Layout.Bullet.prototype.defaults = new pv.Layout.Bullet()
  13650. .extend(pv.Layout.prototype.defaults)
  13651. .orient("left")
  13652. .ranges([])
  13653. .markers([])
  13654. .measures([]);
  13655. /** @private */
  13656. pv.Layout.Bullet.prototype.buildImplied = function(s) {
  13657. pv.Layout.prototype.buildImplied.call(this, s);
  13658. var size = this.parent[/^left|right$/.test(s.orient) ? "width" : "height"]();
  13659. s.maximum = s.maximum || pv.max([].concat(s.ranges, s.markers, s.measures));
  13660. this.x.domain(0, s.maximum).range(0, size);
  13661. };
  13662. /**
  13663. * Abstract; see an implementing class for details.
  13664. *
  13665. * @class Represents a reusable interaction; applies an interactive behavior to
  13666. * a given mark. Behaviors are themselves functions designed to be used as event
  13667. * handlers. For example, to add pan and zoom support to any panel, say:
  13668. *
  13669. * <pre> .event("mousedown", pv.Behavior.pan())
  13670. * .event("mousewheel", pv.Behavior.zoom())</pre>
  13671. *
  13672. * The behavior should be registered on the event that triggers the start of the
  13673. * behavior. Typically, the behavior will take care of registering for any
  13674. * additional events that are necessary. For example, dragging starts on
  13675. * mousedown, while the drag behavior automatically listens for mousemove and
  13676. * mouseup events on the window. By listening to the window, the behavior can
  13677. * continue to receive mouse events even if the mouse briefly leaves the mark
  13678. * being dragged, or even the root panel.
  13679. *
  13680. * <p>Each behavior implementation has specific requirements as to which events
  13681. * it supports, and how it should be used. For example, the drag behavior
  13682. * requires that the data associated with the mark be an object with <tt>x</tt>
  13683. * and <tt>y</tt> attributes, such as a {@link pv.Vector}, storing the mark's
  13684. * position. See an implementing class for details.
  13685. *
  13686. * @see pv.Behavior.drag
  13687. * @see pv.Behavior.pan
  13688. * @see pv.Behavior.point
  13689. * @see pv.Behavior.select
  13690. * @see pv.Behavior.zoom
  13691. * @extends function
  13692. */
  13693. pv.Behavior = {};
  13694. /**
  13695. * Returns a new drag behavior to be registered on mousedown events.
  13696. *
  13697. * @class Implements interactive dragging starting with mousedown events.
  13698. * Register this behavior on marks that should be draggable by the user, such as
  13699. * the selected region for brushing and linking. This behavior can be used in
  13700. * tandom with {@link pv.Behavior.select} to allow the selected region to be
  13701. * dragged interactively.
  13702. *
  13703. * <p>After the initial mousedown event is triggered, this behavior listens for
  13704. * mousemove and mouseup events on the window. This allows dragging to continue
  13705. * even if the mouse temporarily leaves the mark that is being dragged, or even
  13706. * the root panel.
  13707. *
  13708. * <p>This behavior requires that the data associated with the mark being
  13709. * dragged have <tt>x</tt> and <tt>y</tt> attributes that correspond to the
  13710. * mark's location in pixels. The mark's positional properties are not set
  13711. * directly by this behavior; instead, the positional properties should be
  13712. * defined as:
  13713. *
  13714. * <pre> .left(function(d) d.x)
  13715. * .top(function(d) d.y)</pre>
  13716. *
  13717. * Thus, the behavior does not move the mark directly, but instead updates the
  13718. * mark position by updating the underlying data. Note that if the positional
  13719. * properties are defined with bottom and right (rather than top and left), the
  13720. * drag behavior will be inverted, which will confuse users!
  13721. *
  13722. * <p>The drag behavior is bounded by the parent panel; the <tt>x</tt> and
  13723. * <tt>y</tt> attributes are clamped such that the mark being dragged does not
  13724. * extend outside the enclosing panel's bounds. To facilitate this, the drag
  13725. * behavior also queries for <tt>dx</tt> and <tt>dy</tt> attributes on the
  13726. * underlying data, to determine the dimensions of the bar being dragged. For
  13727. * non-rectangular marks, the drag behavior simply treats the mark as a point,
  13728. * which means that only the mark's center is bounded.
  13729. *
  13730. * <p>The mark being dragged is automatically re-rendered for each mouse event
  13731. * as part of the drag operation. In addition, a <tt>fix</tt> attribute is
  13732. * populated on the mark, which allows visual feedback for dragging. For
  13733. * example, to change the mark fill color while dragging:
  13734. *
  13735. * <pre> .fillStyle(function(d) d.fix ? "#ff7f0e" : "#aec7e8")</pre>
  13736. *
  13737. * In some cases, such as with network layouts, dragging the mark may cause
  13738. * related marks to change, in which case additional marks may also need to be
  13739. * rendered. This can be accomplished by listening for the drag
  13740. * psuedo-events:<ul>
  13741. *
  13742. * <li>dragstart (on mousedown)
  13743. * <li>drag (on mousemove)
  13744. * <li>dragend (on mouseup)
  13745. *
  13746. * </ul>For example, to render the parent panel while dragging, thus
  13747. * re-rendering all sibling marks:
  13748. *
  13749. * <pre> .event("mousedown", pv.Behavior.drag())
  13750. * .event("drag", function() this.parent)</pre>
  13751. *
  13752. * This behavior may be enhanced in the future to allow more flexible
  13753. * configuration of drag behavior.
  13754. *
  13755. * @extends pv.Behavior
  13756. * @see pv.Behavior
  13757. * @see pv.Behavior.select
  13758. * @see pv.Layout.force
  13759. */
  13760. pv.Behavior.drag = function() {
  13761. var scene, // scene context
  13762. index, // scene context
  13763. p, // particle being dragged
  13764. v1, // initial mouse-particle offset
  13765. max;
  13766. /** @private */
  13767. function mousedown(d) {
  13768. index = this.index;
  13769. scene = this.scene;
  13770. var m = this.mouse();
  13771. v1 = ((p = d).fix = pv.vector(d.x, d.y)).minus(m);
  13772. max = {
  13773. x: this.parent.width() - (d.dx || 0),
  13774. y: this.parent.height() - (d.dy || 0)
  13775. };
  13776. scene.mark.context(scene, index, function() { this.render(); });
  13777. pv.Mark.dispatch("dragstart", scene, index);
  13778. }
  13779. /** @private */
  13780. function mousemove() {
  13781. if (!scene) return;
  13782. scene.mark.context(scene, index, function() {
  13783. var m = this.mouse();
  13784. p.x = p.fix.x = Math.max(0, Math.min(v1.x + m.x, max.x));
  13785. p.y = p.fix.y = Math.max(0, Math.min(v1.y + m.y, max.y));
  13786. this.render();
  13787. });
  13788. pv.Mark.dispatch("drag", scene, index);
  13789. }
  13790. /** @private */
  13791. function mouseup() {
  13792. if (!scene) return;
  13793. p.fix = null;
  13794. scene.mark.context(scene, index, function() { this.render(); });
  13795. pv.Mark.dispatch("dragend", scene, index);
  13796. scene = null;
  13797. }
  13798. pv.listen(window, "mousemove", mousemove);
  13799. pv.listen(window, "mouseup", mouseup);
  13800. return mousedown;
  13801. };
  13802. /**
  13803. * Returns a new point behavior to be registered on mousemove events.
  13804. *
  13805. * @class Implements interactive fuzzy pointing, identifying marks that are in
  13806. * close proximity to the mouse cursor. This behavior is an alternative to the
  13807. * native mouseover and mouseout events, improving usability. Rather than
  13808. * requiring the user to mouseover a mark exactly, the mouse simply needs to
  13809. * move near the given mark and a "point" event is triggered. In addition, if
  13810. * multiple marks overlap, the point behavior can be used to identify the mark
  13811. * instance closest to the cursor, as opposed to the one that is rendered on
  13812. * top.
  13813. *
  13814. * <p>The point behavior can also identify the closest mark instance for marks
  13815. * that produce a continuous graphic primitive. The point behavior can thus be
  13816. * used to provide details-on-demand for both discrete marks (such as dots and
  13817. * bars), as well as continuous marks (such as lines and areas).
  13818. *
  13819. * <p>This behavior is implemented by finding the closest mark instance to the
  13820. * mouse cursor on every mousemove event. If this closest mark is within the
  13821. * given radius threshold, which defaults to 30 pixels, a "point" psuedo-event
  13822. * is dispatched to the given mark instance. If any mark were previously
  13823. * pointed, it would receive a corresponding "unpoint" event. These two
  13824. * psuedo-event types correspond to the native "mouseover" and "mouseout"
  13825. * events, respectively. To increase the radius at which the point behavior can
  13826. * be applied, specify an appropriate threshold to the constructor, up to
  13827. * <tt>Infinity</tt>.
  13828. *
  13829. * <p>By default, the standard Cartesian distance is computed. However, with
  13830. * some visualizations it is desirable to consider only a single dimension, such
  13831. * as the <i>x</i>-dimension for an independent variable. In this case, the
  13832. * collapse parameter can be set to collapse the <i>y</i> dimension:
  13833. *
  13834. * <pre> .event("mousemove", pv.Behavior.point(Infinity).collapse("y"))</pre>
  13835. *
  13836. * <p>This behavior only listens to mousemove events on the assigned panel,
  13837. * which is typically the root panel. The behavior will search recursively for
  13838. * descendant marks to point. If the mouse leaves the assigned panel, the
  13839. * behavior no longer receives mousemove events; an unpoint psuedo-event is
  13840. * automatically dispatched to unpoint any pointed mark. Marks may be re-pointed
  13841. * when the mouse reenters the panel.
  13842. *
  13843. * <p>Panels have transparent fill styles by default; this means that panels may
  13844. * not receive the initial mousemove event to start pointing. To fix this
  13845. * problem, either given the panel a visible fill style (such as "white"), or
  13846. * set the <tt>events</tt> property to "all" such that the panel receives events
  13847. * despite its transparent fill.
  13848. *
  13849. * <p>Note: this behavior does not currently wedge marks.
  13850. *
  13851. * @extends pv.Behavior
  13852. *
  13853. * @param {number} [r] the fuzzy radius threshold in pixels
  13854. * @see <a href="http://www.tovigrossman.com/papers/chi2005bubblecursor.pdf"
  13855. * >"The Bubble Cursor: Enhancing Target Acquisition by Dynamic Resizing of the
  13856. * Cursor's Activation Area"</a> by T. Grossman &amp; R. Balakrishnan, CHI 2005.
  13857. */
  13858. pv.Behavior.point = function(r) {
  13859. var unpoint, // the current pointer target
  13860. collapse = null, // dimensions to collapse
  13861. kx = 1, // x-dimension cost scale
  13862. ky = 1, // y-dimension cost scale
  13863. r2 = arguments.length ? r * r : 900; // fuzzy radius
  13864. /** @private Search for the mark closest to the mouse. */
  13865. function search(scene, index) {
  13866. var s = scene[index],
  13867. point = {cost: Infinity};
  13868. for (var i = 0, n = s.visible && s.children.length; i < n; i++) {
  13869. var child = s.children[i], mark = child.mark, p;
  13870. if (mark.type == "panel") {
  13871. mark.scene = child;
  13872. for (var j = 0, m = child.length; j < m; j++) {
  13873. mark.index = j;
  13874. p = search(child, j);
  13875. if (p.cost < point.cost) point = p;
  13876. }
  13877. delete mark.scene;
  13878. delete mark.index;
  13879. } else if (mark.$handlers.point) {
  13880. var v = mark.mouse();
  13881. for (var j = 0, m = child.length; j < m; j++) {
  13882. var c = child[j],
  13883. dx = v.x - c.left - (c.width || 0) / 2,
  13884. dy = v.y - c.top - (c.height || 0) / 2,
  13885. dd = kx * dx * dx + ky * dy * dy;
  13886. if (dd < point.cost) {
  13887. point.distance = dx * dx + dy * dy;
  13888. point.cost = dd;
  13889. point.scene = child;
  13890. point.index = j;
  13891. }
  13892. }
  13893. }
  13894. }
  13895. return point;
  13896. }
  13897. /** @private */
  13898. function mousemove() {
  13899. /* If the closest mark is far away, clear the current target. */
  13900. var point = search(this.scene, this.index);
  13901. if ((point.cost == Infinity) || (point.distance > r2)) point = null;
  13902. /* Unpoint the old target, if it's not the new target. */
  13903. if (unpoint) {
  13904. if (point
  13905. && (unpoint.scene == point.scene)
  13906. && (unpoint.index == point.index)) return;
  13907. pv.Mark.dispatch("unpoint", unpoint.scene, unpoint.index);
  13908. }
  13909. /* Point the new target, if there is one. */
  13910. if (unpoint = point) {
  13911. pv.Mark.dispatch("point", point.scene, point.index);
  13912. /* Unpoint when the mouse leaves the root panel. */
  13913. pv.listen(this.root.canvas(), "mouseout", mouseout);
  13914. }
  13915. }
  13916. /** @private */
  13917. function mouseout(e) {
  13918. if (unpoint && !pv.ancestor(this, e.relatedTarget)) {
  13919. pv.Mark.dispatch("unpoint", unpoint.scene, unpoint.index);
  13920. unpoint = null;
  13921. }
  13922. }
  13923. /**
  13924. * Sets or gets the collapse parameter. By default, the standard Cartesian
  13925. * distance is computed. However, with some visualizations it is desirable to
  13926. * consider only a single dimension, such as the <i>x</i>-dimension for an
  13927. * independent variable. In this case, the collapse parameter can be set to
  13928. * collapse the <i>y</i> dimension:
  13929. *
  13930. * <pre> .event("mousemove", pv.Behavior.point(Infinity).collapse("y"))</pre>
  13931. *
  13932. * @function
  13933. * @returns {pv.Behavior.point} this, or the current collapse parameter.
  13934. * @name pv.Behavior.point.prototype.collapse
  13935. * @param {string} [x] the new collapse parameter
  13936. */
  13937. mousemove.collapse = function(x) {
  13938. if (arguments.length) {
  13939. collapse = String(x);
  13940. switch (collapse) {
  13941. case "y": kx = 1; ky = 0; break;
  13942. case "x": kx = 0; ky = 1; break;
  13943. default: kx = 1; ky = 1; break;
  13944. }
  13945. return mousemove;
  13946. }
  13947. return collapse;
  13948. };
  13949. return mousemove;
  13950. };
  13951. /**
  13952. * Returns a new select behavior to be registered on mousedown events.
  13953. *
  13954. * @class Implements interactive selecting starting with mousedown events.
  13955. * Register this behavior on panels that should be selectable by the user, such
  13956. * for brushing and linking. This behavior can be used in tandom with
  13957. * {@link pv.Behavior.drag} to allow the selected region to be dragged
  13958. * interactively.
  13959. *
  13960. * <p>After the initial mousedown event is triggered, this behavior listens for
  13961. * mousemove and mouseup events on the window. This allows selecting to continue
  13962. * even if the mouse temporarily leaves the assigned panel, or even the root
  13963. * panel.
  13964. *
  13965. * <p>This behavior requires that the data associated with the mark being
  13966. * dragged have <tt>x</tt>, <tt>y</tt>, <tt>dx</tt> and <tt>dy</tt> attributes
  13967. * that correspond to the mark's location and dimensions in pixels. The mark's
  13968. * positional properties are not set directly by this behavior; instead, the
  13969. * positional properties should be defined as:
  13970. *
  13971. * <pre> .left(function(d) d.x)
  13972. * .top(function(d) d.y)
  13973. * .width(function(d) d.dx)
  13974. * .height(function(d) d.dy)</pre>
  13975. *
  13976. * Thus, the behavior does not resize the mark directly, but instead updates the
  13977. * selection by updating the assigned panel's underlying data. Note that if the
  13978. * positional properties are defined with bottom and right (rather than top and
  13979. * left), the drag behavior will be inverted, which will confuse users!
  13980. *
  13981. * <p>The select behavior is bounded by the assigned panel; the positional
  13982. * attributes are clamped such that the selection does not extend outside the
  13983. * panel's bounds.
  13984. *
  13985. * <p>The panel being selected is automatically re-rendered for each mouse event
  13986. * as part of the drag operation. This behavior may be enhanced in the future to
  13987. * allow more flexible configuration of select behavior. In some cases, such as
  13988. * with parallel coordinates, making a selection may cause related marks to
  13989. * change, in which case additional marks may also need to be rendered. This can
  13990. * be accomplished by listening for the select psuedo-events:<ul>
  13991. *
  13992. * <li>selectstart (on mousedown)
  13993. * <li>select (on mousemove)
  13994. * <li>selectend (on mouseup)
  13995. *
  13996. * </ul>For example, to render the parent panel while selecting, thus
  13997. * re-rendering all sibling marks:
  13998. *
  13999. * <pre> .event("mousedown", pv.Behavior.drag())
  14000. * .event("select", function() this.parent)</pre>
  14001. *
  14002. * This behavior may be enhanced in the future to allow more flexible
  14003. * configuration of the selection behavior.
  14004. *
  14005. * @extends pv.Behavior
  14006. * @see pv.Behavior.drag
  14007. */
  14008. pv.Behavior.select = function() {
  14009. var scene, // scene context
  14010. index, // scene context
  14011. r, // region being selected
  14012. m1; // initial mouse position
  14013. /** @private */
  14014. function mousedown(d) {
  14015. index = this.index;
  14016. scene = this.scene;
  14017. m1 = this.mouse();
  14018. r = d;
  14019. r.x = m1.x;
  14020. r.y = m1.y;
  14021. r.dx = r.dy = 0;
  14022. pv.Mark.dispatch("selectstart", scene, index);
  14023. }
  14024. /** @private */
  14025. function mousemove() {
  14026. if (!scene) return;
  14027. scene.mark.context(scene, index, function() {
  14028. var m2 = this.mouse();
  14029. r.x = Math.max(0, Math.min(m1.x, m2.x));
  14030. r.y = Math.max(0, Math.min(m1.y, m2.y));
  14031. r.dx = Math.min(this.width(), Math.max(m2.x, m1.x)) - r.x;
  14032. r.dy = Math.min(this.height(), Math.max(m2.y, m1.y)) - r.y;
  14033. this.render();
  14034. });
  14035. pv.Mark.dispatch("select", scene, index);
  14036. }
  14037. /** @private */
  14038. function mouseup() {
  14039. if (!scene) return;
  14040. pv.Mark.dispatch("selectend", scene, index);
  14041. scene = null;
  14042. }
  14043. pv.listen(window, "mousemove", mousemove);
  14044. pv.listen(window, "mouseup", mouseup);
  14045. return mousedown;
  14046. };
  14047. /**
  14048. * Returns a new resize behavior to be registered on mousedown events.
  14049. *
  14050. * @class Implements interactive resizing of a selection starting with mousedown
  14051. * events. Register this behavior on selection handles that should be resizeable
  14052. * by the user, such for brushing and linking. This behavior can be used in
  14053. * tandom with {@link pv.Behavior.select} and {@link pv.Behavior.drag} to allow
  14054. * the selected region to be selected and dragged interactively.
  14055. *
  14056. * <p>After the initial mousedown event is triggered, this behavior listens for
  14057. * mousemove and mouseup events on the window. This allows resizing to continue
  14058. * even if the mouse temporarily leaves the assigned panel, or even the root
  14059. * panel.
  14060. *
  14061. * <p>This behavior requires that the data associated with the mark being
  14062. * resized have <tt>x</tt>, <tt>y</tt>, <tt>dx</tt> and <tt>dy</tt> attributes
  14063. * that correspond to the mark's location and dimensions in pixels. The mark's
  14064. * positional properties are not set directly by this behavior; instead, the
  14065. * positional properties should be defined as:
  14066. *
  14067. * <pre> .left(function(d) d.x)
  14068. * .top(function(d) d.y)
  14069. * .width(function(d) d.dx)
  14070. * .height(function(d) d.dy)</pre>
  14071. *
  14072. * Thus, the behavior does not resize the mark directly, but instead updates the
  14073. * size by updating the assigned panel's underlying data. Note that if the
  14074. * positional properties are defined with bottom and right (rather than top and
  14075. * left), the resize behavior will be inverted, which will confuse users!
  14076. *
  14077. * <p>The resize behavior is bounded by the assigned mark's enclosing panel; the
  14078. * positional attributes are clamped such that the selection does not extend
  14079. * outside the panel's bounds.
  14080. *
  14081. * <p>The mark being resized is automatically re-rendered for each mouse event
  14082. * as part of the resize operation. This behavior may be enhanced in the future
  14083. * to allow more flexible configuration. In some cases, such as with parallel
  14084. * coordinates, resizing the selection may cause related marks to change, in
  14085. * which case additional marks may also need to be rendered. This can be
  14086. * accomplished by listening for the select psuedo-events:<ul>
  14087. *
  14088. * <li>resizestart (on mousedown)
  14089. * <li>resize (on mousemove)
  14090. * <li>resizeend (on mouseup)
  14091. *
  14092. * </ul>For example, to render the parent panel while resizing, thus
  14093. * re-rendering all sibling marks:
  14094. *
  14095. * <pre> .event("mousedown", pv.Behavior.resize("left"))
  14096. * .event("resize", function() this.parent)</pre>
  14097. *
  14098. * This behavior may be enhanced in the future to allow more flexible
  14099. * configuration of the selection behavior.
  14100. *
  14101. * @extends pv.Behavior
  14102. * @see pv.Behavior.select
  14103. * @see pv.Behavior.drag
  14104. */
  14105. pv.Behavior.resize = function(side) {
  14106. var scene, // scene context
  14107. index, // scene context
  14108. r, // region being selected
  14109. m1; // initial mouse position
  14110. /** @private */
  14111. function mousedown(d) {
  14112. index = this.index;
  14113. scene = this.scene;
  14114. m1 = this.mouse();
  14115. r = d;
  14116. switch (side) {
  14117. case "left": m1.x = r.x + r.dx; break;
  14118. case "right": m1.x = r.x; break;
  14119. case "top": m1.y = r.y + r.dy; break;
  14120. case "bottom": m1.y = r.y; break;
  14121. }
  14122. pv.Mark.dispatch("resizestart", scene, index);
  14123. }
  14124. /** @private */
  14125. function mousemove() {
  14126. if (!scene) return;
  14127. scene.mark.context(scene, index, function() {
  14128. var m2 = this.mouse();
  14129. r.x = Math.max(0, Math.min(m1.x, m2.x));
  14130. r.y = Math.max(0, Math.min(m1.y, m2.y));
  14131. r.dx = Math.min(this.parent.width(), Math.max(m2.x, m1.x)) - r.x;
  14132. r.dy = Math.min(this.parent.height(), Math.max(m2.y, m1.y)) - r.y;
  14133. this.render();
  14134. });
  14135. pv.Mark.dispatch("resize", scene, index);
  14136. }
  14137. /** @private */
  14138. function mouseup() {
  14139. if (!scene) return;
  14140. pv.Mark.dispatch("resizeend", scene, index);
  14141. scene = null;
  14142. }
  14143. pv.listen(window, "mousemove", mousemove);
  14144. pv.listen(window, "mouseup", mouseup);
  14145. return mousedown;
  14146. };
  14147. /**
  14148. * Returns a new pan behavior to be registered on mousedown events.
  14149. *
  14150. * @class Implements interactive panning starting with mousedown events.
  14151. * Register this behavior on panels to allow panning. This behavior can be used
  14152. * in tandem with {@link pv.Behavior.zoom} to allow both panning and zooming:
  14153. *
  14154. * <pre> .event("mousedown", pv.Behavior.pan())
  14155. * .event("mousewheel", pv.Behavior.zoom())</pre>
  14156. *
  14157. * The pan behavior currently supports only mouse events; support for keyboard
  14158. * shortcuts to improve accessibility may be added in the future.
  14159. *
  14160. * <p>After the initial mousedown event is triggered, this behavior listens for
  14161. * mousemove and mouseup events on the window. This allows panning to continue
  14162. * even if the mouse temporarily leaves the panel that is being panned, or even
  14163. * the root panel.
  14164. *
  14165. * <p>The implementation of this behavior relies on the panel's
  14166. * <tt>transform</tt> property, which specifies a matrix transformation that is
  14167. * applied to child marks. Note that the transform property only affects the
  14168. * panel's children, but not the panel itself; therefore the panel's fill and
  14169. * stroke will not change when the contents are panned.
  14170. *
  14171. * <p>Panels have transparent fill styles by default; this means that panels may
  14172. * not receive the initial mousedown event to start panning. To fix this
  14173. * problem, either given the panel a visible fill style (such as "white"), or
  14174. * set the <tt>events</tt> property to "all" such that the panel receives events
  14175. * despite its transparent fill.
  14176. *
  14177. * <p>The pan behavior has optional support for bounding. If enabled, the user
  14178. * will not be able to pan the panel outside of the initial bounds. This feature
  14179. * is designed to work in conjunction with the zoom behavior; otherwise,
  14180. * bounding the panel effectively disables all panning.
  14181. *
  14182. * @extends pv.Behavior
  14183. * @see pv.Behavior.zoom
  14184. * @see pv.Panel#transform
  14185. */
  14186. pv.Behavior.pan = function() {
  14187. var scene, // scene context
  14188. index, // scene context
  14189. m1, // transformation matrix at the start of panning
  14190. v1, // mouse location at the start of panning
  14191. k, // inverse scale
  14192. bound; // whether to bound to the panel
  14193. /** @private */
  14194. function mousedown() {
  14195. index = this.index;
  14196. scene = this.scene;
  14197. v1 = pv.vector(pv.event.pageX, pv.event.pageY);
  14198. m1 = this.transform();
  14199. k = 1 / (m1.k * this.scale);
  14200. if (bound) {
  14201. bound = {
  14202. x: (1 - m1.k) * this.width(),
  14203. y: (1 - m1.k) * this.height()
  14204. };
  14205. }
  14206. }
  14207. /** @private */
  14208. function mousemove() {
  14209. if (!scene) return;
  14210. scene.mark.context(scene, index, function() {
  14211. var x = (pv.event.pageX - v1.x) * k,
  14212. y = (pv.event.pageY - v1.y) * k,
  14213. m = m1.translate(x, y);
  14214. if (bound) {
  14215. m.x = Math.max(bound.x, Math.min(0, m.x));
  14216. m.y = Math.max(bound.y, Math.min(0, m.y));
  14217. }
  14218. this.transform(m).render();
  14219. });
  14220. pv.Mark.dispatch("pan", scene, index);
  14221. }
  14222. /** @private */
  14223. function mouseup() {
  14224. scene = null;
  14225. }
  14226. /**
  14227. * Sets or gets the bound parameter. If bounding is enabled, the user will not
  14228. * be able to pan outside the initial panel bounds; this typically applies
  14229. * only when the pan behavior is used in tandem with the zoom behavior.
  14230. * Bounding is not enabled by default.
  14231. *
  14232. * <p>Note: enabling bounding after panning has already occurred will not
  14233. * immediately reset the transform. Bounding should be enabled before the
  14234. * panning behavior is applied.
  14235. *
  14236. * @function
  14237. * @returns {pv.Behavior.pan} this, or the current bound parameter.
  14238. * @name pv.Behavior.pan.prototype.bound
  14239. * @param {boolean} [x] the new bound parameter.
  14240. */
  14241. mousedown.bound = function(x) {
  14242. if (arguments.length) {
  14243. bound = Boolean(x);
  14244. return this;
  14245. }
  14246. return Boolean(bound);
  14247. };
  14248. pv.listen(window, "mousemove", mousemove);
  14249. pv.listen(window, "mouseup", mouseup);
  14250. return mousedown;
  14251. };
  14252. /**
  14253. * Returns a new zoom behavior to be registered on mousewheel events.
  14254. *
  14255. * @class Implements interactive zooming using mousewheel events. Register this
  14256. * behavior on panels to allow zooming. This behavior can be used in tandem with
  14257. * {@link pv.Behavior.pan} to allow both panning and zooming:
  14258. *
  14259. * <pre> .event("mousedown", pv.Behavior.pan())
  14260. * .event("mousewheel", pv.Behavior.zoom())</pre>
  14261. *
  14262. * The zoom behavior currently supports only mousewheel events; support for
  14263. * keyboard shortcuts and gesture events to improve accessibility may be added
  14264. * in the future.
  14265. *
  14266. * <p>The implementation of this behavior relies on the panel's
  14267. * <tt>transform</tt> property, which specifies a matrix transformation that is
  14268. * applied to child marks. Note that the transform property only affects the
  14269. * panel's children, but not the panel itself; therefore the panel's fill and
  14270. * stroke will not change when the contents are zoomed. The built-in support for
  14271. * transforms only supports uniform scaling and translates, which is sufficient
  14272. * for panning and zooming. Note that this is not a strict geometric
  14273. * transformation, as the <tt>lineWidth</tt> property is scale-aware: strokes
  14274. * are drawn at constant size independent of scale.
  14275. *
  14276. * <p>Panels have transparent fill styles by default; this means that panels may
  14277. * not receive mousewheel events to zoom. To fix this problem, either given the
  14278. * panel a visible fill style (such as "white"), or set the <tt>events</tt>
  14279. * property to "all" such that the panel receives events despite its transparent
  14280. * fill.
  14281. *
  14282. * <p>The zoom behavior has optional support for bounding. If enabled, the user
  14283. * will not be able to zoom out farther than the initial bounds. This feature is
  14284. * designed to work in conjunction with the pan behavior.
  14285. *
  14286. * @extends pv.Behavior
  14287. * @see pv.Panel#transform
  14288. * @see pv.Mark#scale
  14289. * @param {number} speed
  14290. */
  14291. pv.Behavior.zoom = function(speed) {
  14292. var bound; // whether to bound to the panel
  14293. if (!arguments.length) speed = 1 / 48;
  14294. /** @private */
  14295. function mousewheel() {
  14296. var v = this.mouse(),
  14297. k = pv.event.wheel * speed,
  14298. m = this.transform().translate(v.x, v.y)
  14299. .scale((k < 0) ? (1e3 / (1e3 - k)) : ((1e3 + k) / 1e3))
  14300. .translate(-v.x, -v.y);
  14301. if (bound) {
  14302. m.k = Math.max(1, m.k);
  14303. m.x = Math.max((1 - m.k) * this.width(), Math.min(0, m.x));
  14304. m.y = Math.max((1 - m.k) * this.height(), Math.min(0, m.y));
  14305. }
  14306. this.transform(m).render();
  14307. pv.Mark.dispatch("zoom", this.scene, this.index);
  14308. }
  14309. /**
  14310. * Sets or gets the bound parameter. If bounding is enabled, the user will not
  14311. * be able to zoom out farther than the initial panel bounds. Bounding is not
  14312. * enabled by default. If this behavior is used in tandem with the pan
  14313. * behavior, both should use the same bound parameter.
  14314. *
  14315. * <p>Note: enabling bounding after zooming has already occurred will not
  14316. * immediately reset the transform. Bounding should be enabled before the zoom
  14317. * behavior is applied.
  14318. *
  14319. * @function
  14320. * @returns {pv.Behavior.zoom} this, or the current bound parameter.
  14321. * @name pv.Behavior.zoom.prototype.bound
  14322. * @param {boolean} [x] the new bound parameter.
  14323. */
  14324. mousewheel.bound = function(x) {
  14325. if (arguments.length) {
  14326. bound = Boolean(x);
  14327. return this;
  14328. }
  14329. return Boolean(bound);
  14330. };
  14331. return mousewheel;
  14332. };
  14333. /**
  14334. * @ignore
  14335. * @namespace
  14336. */
  14337. pv.Geo = function() {};
  14338. /**
  14339. * Abstract; not implemented. There is no explicit constructor; this class
  14340. * merely serves to document the representation used by {@link pv.Geo.scale}.
  14341. *
  14342. * @class Represents a pair of geographic coordinates.
  14343. *
  14344. * @name pv.Geo.LatLng
  14345. * @see pv.Geo.scale
  14346. */
  14347. /**
  14348. * The <i>latitude</i> coordinate in degrees; positive is North.
  14349. *
  14350. * @type number
  14351. * @name pv.Geo.LatLng.prototype.lat
  14352. */
  14353. /**
  14354. * The <i>longitude</i> coordinate in degrees; positive is East.
  14355. *
  14356. * @type number
  14357. * @name pv.Geo.LatLng.prototype.lng
  14358. */
  14359. /**
  14360. * Abstract; not implemented. There is no explicit constructor; this class
  14361. * merely serves to document the representation used by {@link pv.Geo.scale}.
  14362. *
  14363. * @class Represents a geographic projection. This class provides the core
  14364. * implementation for {@link pv.Geo.scale}s, mapping between geographic
  14365. * coordinates (latitude and longitude) and normalized screen space in the range
  14366. * [-1,1]. The remaining mapping between normalized screen space and actual
  14367. * pixels is performed by <tt>pv.Geo.scale</tt>.
  14368. *
  14369. * <p>Many geographic projections have a point around which the projection is
  14370. * centered. Rather than have each implementation add support for a
  14371. * user-specified center point, the <tt>pv.Geo.scale</tt> translates the
  14372. * geographic coordinates relative to the center point for both the forward and
  14373. * inverse projection.
  14374. *
  14375. * <p>In general, this class should not be used directly, unless the desire is
  14376. * to implement a new geographic projection. Instead, use <tt>pv.Geo.scale</tt>.
  14377. * Implementations are not required to implement inverse projections, but are
  14378. * needed for some forms of interactivity. Also note that some inverse
  14379. * projections are ambiguous, such as the connecting points in Dymaxian maps.
  14380. *
  14381. * @name pv.Geo.Projection
  14382. * @see pv.Geo.scale
  14383. */
  14384. /**
  14385. * The <i>forward</i> projection.
  14386. *
  14387. * @function
  14388. * @name pv.Geo.Projection.prototype.project
  14389. * @param {pv.Geo.LatLng} latlng the latitude and longitude to project.
  14390. * @returns {pv.Vector} the xy-coordinates of the given point.
  14391. */
  14392. /**
  14393. * The <i>inverse</i> projection; optional.
  14394. *
  14395. * @function
  14396. * @name pv.Geo.Projection.prototype.invert
  14397. * @param {pv.Vector} xy the x- and y-coordinates to invert.
  14398. * @returns {pv.Geo.LatLng} the latitude and longitude of the given point.
  14399. */
  14400. /**
  14401. * The built-in projections.
  14402. *
  14403. * @see pv.Geo.Projection
  14404. * @namespace
  14405. */
  14406. pv.Geo.projections = {
  14407. /** @see http://en.wikipedia.org/wiki/Mercator_projection */
  14408. mercator: {
  14409. project: function(latlng) {
  14410. return {
  14411. x: latlng.lng / 180,
  14412. y: latlng.lat > 85 ? 1 : latlng.lat < -85 ? -1
  14413. : Math.log(Math.tan(Math.PI / 4
  14414. + pv.radians(latlng.lat) / 2)) / Math.PI
  14415. };
  14416. },
  14417. invert: function(xy) {
  14418. return {
  14419. lng: xy.x * 180,
  14420. lat: pv.degrees(2 * Math.atan(Math.exp(xy.y * Math.PI)) - Math.PI / 2)
  14421. };
  14422. }
  14423. },
  14424. /** @see http://en.wikipedia.org/wiki/Gall-Peters_projection */
  14425. "gall-peters": {
  14426. project: function(latlng) {
  14427. return {
  14428. x: latlng.lng / 180,
  14429. y: Math.sin(pv.radians(latlng.lat))
  14430. };
  14431. },
  14432. invert: function(xy) {
  14433. return {
  14434. lng: xy.x * 180,
  14435. lat: pv.degrees(Math.asin(xy.y))
  14436. };
  14437. }
  14438. },
  14439. /** @see http://en.wikipedia.org/wiki/Sinusoidal_projection */
  14440. sinusoidal: {
  14441. project: function(latlng) {
  14442. return {
  14443. x: pv.radians(latlng.lng) * Math.cos(pv.radians(latlng.lat)) / Math.PI,
  14444. y: latlng.lat / 90
  14445. };
  14446. },
  14447. invert: function(xy) {
  14448. return {
  14449. lng: pv.degrees((xy.x * Math.PI) / Math.cos(xy.y * Math.PI / 2)),
  14450. lat: xy.y * 90
  14451. };
  14452. }
  14453. },
  14454. /** @see http://en.wikipedia.org/wiki/Aitoff_projection */
  14455. aitoff: {
  14456. project: function(latlng) {
  14457. var l = pv.radians(latlng.lng),
  14458. f = pv.radians(latlng.lat),
  14459. a = Math.acos(Math.cos(f) * Math.cos(l / 2));
  14460. return {
  14461. x: 2 * (a ? (Math.cos(f) * Math.sin(l / 2) * a / Math.sin(a)) : 0) / Math.PI,
  14462. y: 2 * (a ? (Math.sin(f) * a / Math.sin(a)) : 0) / Math.PI
  14463. };
  14464. },
  14465. invert: function(xy) {
  14466. var x = xy.x * Math.PI / 2,
  14467. y = xy.y * Math.PI / 2;
  14468. return {
  14469. lng: pv.degrees(x / Math.cos(y)),
  14470. lat: pv.degrees(y)
  14471. };
  14472. }
  14473. },
  14474. /** @see http://en.wikipedia.org/wiki/Hammer_projection */
  14475. hammer: {
  14476. project: function(latlng) {
  14477. var l = pv.radians(latlng.lng),
  14478. f = pv.radians(latlng.lat),
  14479. c = Math.sqrt(1 + Math.cos(f) * Math.cos(l / 2));
  14480. return {
  14481. x: 2 * Math.SQRT2 * Math.cos(f) * Math.sin(l / 2) / c / 3,
  14482. y: Math.SQRT2 * Math.sin(f) / c / 1.5
  14483. };
  14484. },
  14485. invert: function(xy) {
  14486. var x = xy.x * 3,
  14487. y = xy.y * 1.5,
  14488. z = Math.sqrt(1 - x * x / 16 - y * y / 4);
  14489. return {
  14490. lng: pv.degrees(2 * Math.atan2(z * x, 2 * (2 * z * z - 1))),
  14491. lat: pv.degrees(Math.asin(z * y))
  14492. };
  14493. }
  14494. },
  14495. /** The identity or "none" projection. */
  14496. identity: {
  14497. project: function(latlng) {
  14498. return {
  14499. x: latlng.lng / 180,
  14500. y: latlng.lat / 90
  14501. };
  14502. },
  14503. invert: function(xy) {
  14504. return {
  14505. lng: xy.x * 180,
  14506. lat: xy.y * 90
  14507. };
  14508. }
  14509. }
  14510. };
  14511. /**
  14512. * Returns a geographic scale. The arguments to this constructor are optional,
  14513. * and equivalent to calling {@link #projection}.
  14514. *
  14515. * @class Represents a geographic scale; a mapping between latitude-longitude
  14516. * coordinates and screen pixel coordinates. By default, the domain is inferred
  14517. * from the geographic coordinates, so that the domain fills the output range.
  14518. *
  14519. * <p>Note that geographic scales are two-dimensional transformations, rather
  14520. * than the one-dimensional bidrectional mapping typical of other scales.
  14521. * Rather than mapping (for example) between a numeric domain and a numeric
  14522. * range, geographic scales map between two coordinate objects: {@link
  14523. * pv.Geo.LatLng} and {@link pv.Vector}.
  14524. *
  14525. * @param {pv.Geo.Projection} [p] optional projection.
  14526. * @see pv.Geo.scale#ticks
  14527. */
  14528. pv.Geo.scale = function(p) {
  14529. var rmin = {x: 0, y: 0}, // default range minimum
  14530. rmax = {x: 1, y: 1}, // default range maximum
  14531. d = [], // default domain
  14532. j = pv.Geo.projections.identity, // domain <-> normalized range
  14533. x = pv.Scale.linear(-1, 1).range(0, 1), // normalized <-> range
  14534. y = pv.Scale.linear(-1, 1).range(1, 0), // normalized <-> range
  14535. c = {lng: 0, lat: 0}, // Center Point
  14536. lastLatLng, // cached latlng
  14537. lastPoint; // cached point
  14538. /** @private */
  14539. function scale(latlng) {
  14540. if (!lastLatLng
  14541. || (latlng.lng != lastLatLng.lng)
  14542. || (latlng.lat != lastLatLng.lat)) {
  14543. lastLatLng = latlng;
  14544. var p = project(latlng);
  14545. lastPoint = {x: x(p.x), y: y(p.y)};
  14546. }
  14547. return lastPoint;
  14548. }
  14549. /** @private */
  14550. function project(latlng) {
  14551. var offset = {lng: latlng.lng - c.lng, lat: latlng.lat};
  14552. return j.project(offset);
  14553. }
  14554. /** @private */
  14555. function invert(xy) {
  14556. var latlng = j.invert(xy);
  14557. latlng.lng += c.lng;
  14558. return latlng;
  14559. }
  14560. /** Returns the projected x-coordinate. */
  14561. scale.x = function(latlng) {
  14562. return scale(latlng).x;
  14563. };
  14564. /** Returns the projected y-coordinate. */
  14565. scale.y = function(latlng) {
  14566. return scale(latlng).y;
  14567. };
  14568. /**
  14569. * Abstract; this is a local namespace on a given geographic scale.
  14570. *
  14571. * @namespace Tick functions for geographic scales. Because geographic scales
  14572. * represent two-dimensional transformations (as opposed to one-dimensional
  14573. * transformations typical of other scales), the tick values are similarly
  14574. * represented as two-dimensional coordinates in the input domain, i.e.,
  14575. * {@link pv.Geo.LatLng} objects.
  14576. *
  14577. * <p>Also, note that non-rectilinear projections, such as sinsuoidal and
  14578. * aitoff, may not produce straight lines for constant longitude or constant
  14579. * latitude. Therefore the returned array of ticks is a two-dimensional array,
  14580. * sampling various latitudes as constant longitude, and vice versa.
  14581. *
  14582. * <p>The tick lines can therefore be approximated as polylines, either with
  14583. * "linear" or "cardinal" interpolation. This is not as accurate as drawing
  14584. * the true curve through the projection space, but is usually sufficient.
  14585. *
  14586. * @name pv.Geo.scale.prototype.ticks
  14587. * @see pv.Geo.scale
  14588. * @see pv.Geo.LatLng
  14589. * @see pv.Line#interpolate
  14590. */
  14591. scale.ticks = {
  14592. /**
  14593. * Returns longitude ticks.
  14594. *
  14595. * @function
  14596. * @param {number} [m] the desired number of ticks.
  14597. * @returns {array} a nested array of <tt>pv.Geo.LatLng</tt> ticks.
  14598. * @name pv.Geo.scale.prototype.ticks.prototype.lng
  14599. */
  14600. lng: function(m) {
  14601. var lat, lng;
  14602. if (d.length > 1) {
  14603. var s = pv.Scale.linear();
  14604. if (m == undefined) m = 10;
  14605. lat = s.domain(d, function(d) { return d.lat; }).ticks(m);
  14606. lng = s.domain(d, function(d) { return d.lng; }).ticks(m);
  14607. } else {
  14608. lat = pv.range(-80, 81, 10);
  14609. lng = pv.range(-180, 181, 10);
  14610. }
  14611. return lng.map(function(lng) {
  14612. return lat.map(function(lat) {
  14613. return {lat: lat, lng: lng};
  14614. });
  14615. });
  14616. },
  14617. /**
  14618. * Returns latitude ticks.
  14619. *
  14620. * @function
  14621. * @param {number} [m] the desired number of ticks.
  14622. * @returns {array} a nested array of <tt>pv.Geo.LatLng</tt> ticks.
  14623. * @name pv.Geo.scale.prototype.ticks.prototype.lat
  14624. */
  14625. lat: function(m) {
  14626. return pv.transpose(scale.ticks.lng(m));
  14627. }
  14628. };
  14629. /**
  14630. * Inverts the specified value in the output range, returning the
  14631. * corresponding value in the input domain. This is frequently used to convert
  14632. * the mouse location (see {@link pv.Mark#mouse}) to a value in the input
  14633. * domain. Inversion is only supported for numeric ranges, and not colors.
  14634. *
  14635. * <p>Note that this method does not do any rounding or bounds checking. If
  14636. * the input domain is discrete (e.g., an array index), the returned value
  14637. * should be rounded. If the specified <tt>y</tt> value is outside the range,
  14638. * the returned value may be equivalently outside the input domain.
  14639. *
  14640. * @function
  14641. * @name pv.Geo.scale.prototype.invert
  14642. * @param {number} y a value in the output range (a pixel location).
  14643. * @returns {number} a value in the input domain.
  14644. */
  14645. scale.invert = function(p) {
  14646. return invert({x: x.invert(p.x), y: y.invert(p.y)});
  14647. };
  14648. /**
  14649. * Sets or gets the input domain. Note that unlike quantitative scales, the
  14650. * domain cannot be reduced to a simple rectangle (i.e., minimum and maximum
  14651. * values for latitude and longitude). Instead, the domain values must be
  14652. * projected to normalized space, effectively finding the domain in normalized
  14653. * space rather than in terms of latitude and longitude. Thus, changing the
  14654. * projection requires recomputing the normalized domain.
  14655. *
  14656. * <p>This method can be invoked several ways:
  14657. *
  14658. * <p>1. <tt>domain(values...)</tt>
  14659. *
  14660. * <p>Specifying the domain as a series of {@link pv.Geo.LatLng}s is the most
  14661. * explicit and recommended approach. However, if the domain values are
  14662. * derived from data, you may find the second method more appropriate.
  14663. *
  14664. * <p>2. <tt>domain(array, f)</tt>
  14665. *
  14666. * <p>Rather than enumerating the domain explicitly, you can specify a single
  14667. * argument of an array. In addition, you can specify an optional accessor
  14668. * function to extract the domain values (as {@link pv.Geo.LatLng}s) from the
  14669. * array. If the specified array has fewer than two elements, this scale will
  14670. * default to the full normalized domain.
  14671. *
  14672. * <p>2. <tt>domain()</tt>
  14673. *
  14674. * <p>Invoking the <tt>domain</tt> method with no arguments returns the
  14675. * current domain as an array.
  14676. *
  14677. * @function
  14678. * @name pv.Geo.scale.prototype.domain
  14679. * @param {...} domain... domain values.
  14680. * @returns {pv.Geo.scale} <tt>this</tt>, or the current domain.
  14681. */
  14682. scale.domain = function(array, f) {
  14683. if (arguments.length) {
  14684. d = (array instanceof Array)
  14685. ? ((arguments.length > 1) ? pv.map(array, f) : array)
  14686. : Array.prototype.slice.call(arguments);
  14687. if (d.length > 1) {
  14688. var lngs = d.map(function(c) { return c.lng; });
  14689. var lats = d.map(function(c) { return c.lat; });
  14690. c = {
  14691. lng: (pv.max(lngs) + pv.min(lngs)) / 2,
  14692. lat: (pv.max(lats) + pv.min(lats)) / 2
  14693. };
  14694. var n = d.map(project); // normalized domain
  14695. x.domain(n, function(p) { return p.x; });
  14696. y.domain(n, function(p) { return p.y; });
  14697. } else {
  14698. c = {lng: 0, lat: 0};
  14699. x.domain(-1, 1);
  14700. y.domain(-1, 1);
  14701. }
  14702. lastLatLng = null; // invalidate the cache
  14703. return this;
  14704. }
  14705. return d;
  14706. };
  14707. /**
  14708. * Sets or gets the output range. This method can be invoked several ways:
  14709. *
  14710. * <p>1. <tt>range(min, max)</tt>
  14711. *
  14712. * <p>If two objects are specified, the arguments should be {@link pv.Vector}s
  14713. * which specify the minimum and maximum values of the x- and y-coordinates
  14714. * explicitly.
  14715. *
  14716. * <p>2. <tt>range(width, height)</tt>
  14717. *
  14718. * <p>If two numbers are specified, the arguments specify the maximum values
  14719. * of the x- and y-coordinates explicitly; the minimum values are implicitly
  14720. * zero.
  14721. *
  14722. * <p>3. <tt>range()</tt>
  14723. *
  14724. * <p>Invoking the <tt>range</tt> method with no arguments returns the current
  14725. * range as an array of two {@link pv.Vector}s: the minimum (top-left) and
  14726. * maximum (bottom-right) values.
  14727. *
  14728. * @function
  14729. * @name pv.Geo.scale.prototype.range
  14730. * @param {...} range... range values.
  14731. * @returns {pv.Geo.scale} <tt>this</tt>, or the current range.
  14732. */
  14733. scale.range = function(min, max) {
  14734. if (arguments.length) {
  14735. if (typeof min == "object") {
  14736. rmin = {x: Number(min.x), y: Number(min.y)};
  14737. rmax = {x: Number(max.x), y: Number(max.y)};
  14738. } else {
  14739. rmin = {x: 0, y: 0};
  14740. rmax = {x: Number(min), y: Number(max)};
  14741. }
  14742. x.range(rmin.x, rmax.x);
  14743. y.range(rmax.y, rmin.y); // XXX flipped?
  14744. lastLatLng = null; // invalidate the cache
  14745. return this;
  14746. }
  14747. return [rmin, rmax];
  14748. };
  14749. /**
  14750. * Sets or gets the projection. This method can be invoked several ways:
  14751. *
  14752. * <p>1. <tt>projection(string)</tt>
  14753. *
  14754. * <p>Specifying a string sets the projection to the given named projection in
  14755. * {@link pv.Geo.projections}. If no such projection is found, the identity
  14756. * projection is used.
  14757. *
  14758. * <p>2. <tt>projection(object)</tt>
  14759. *
  14760. * <p>Specifying an object sets the projection to the given custom projection,
  14761. * which must implement the <i>forward</i> and <i>inverse</i> methods per the
  14762. * {@link pv.Geo.Projection} interface.
  14763. *
  14764. * <p>3. <tt>projection()</tt>
  14765. *
  14766. * <p>Invoking the <tt>projection</tt> method with no arguments returns the
  14767. * current object that defined the projection.
  14768. *
  14769. * @function
  14770. * @name pv.Scale.geo.prototype.projection
  14771. * @param {...} range... range values.
  14772. * @returns {pv.Scale.geo} <tt>this</tt>, or the current range.
  14773. */
  14774. scale.projection = function(p) {
  14775. if (arguments.length) {
  14776. j = typeof p == "string"
  14777. ? pv.Geo.projections[p] || pv.Geo.projections.identity
  14778. : p;
  14779. return this.domain(d); // recompute normalized domain
  14780. }
  14781. return p;
  14782. };
  14783. /**
  14784. * Returns a view of this scale by the specified accessor function <tt>f</tt>.
  14785. * Given a scale <tt>g</tt>, <tt>g.by(function(d) d.foo)</tt> is equivalent to
  14786. * <tt>function(d) g(d.foo)</tt>. This method should be used judiciously; it
  14787. * is typically more clear to invoke the scale directly, passing in the value
  14788. * to be scaled.
  14789. *
  14790. * @function
  14791. * @name pv.Geo.scale.prototype.by
  14792. * @param {function} f an accessor function.
  14793. * @returns {pv.Geo.scale} a view of this scale by the specified accessor
  14794. * function.
  14795. */
  14796. scale.by = function(f) {
  14797. function by() { return scale(f.apply(this, arguments)); }
  14798. for (var method in scale) by[method] = scale[method];
  14799. return by;
  14800. };
  14801. if (arguments.length) scale.projection(p);
  14802. return scale;
  14803. };