protovis-d3.2.js 516 KB

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