vwf.js 281 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957
  1. "use strict";
  2. // Copyright 2012 United States Government, as represented by the Secretary of Defense, Under
  3. // Secretary of Defense (Personnel & Readiness).
  4. //
  5. // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed under the License
  11. // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
  12. // or implied. See the License for the specific language governing permissions and limitations under
  13. // the License.
  14. /// @module vwf
  15. /// vwf.js is the main Virtual World Framework manager. It is constructed as a JavaScript module
  16. /// (http://www.yuiblog.com/blog/2007/06/12/module-pattern) to isolate it from the rest of the
  17. /// page's JavaScript environment. The vwf module self-creates its own instance when loaded and
  18. /// attaches to the global window object as window.vwf. Nothing else should affect the global
  19. /// environment.
  20. ( function( window ) {
  21. window.console && console.debug && console.debug( "loading vwf" );
  22. window.vwf = new function() {
  23. window.console && console.debug && console.debug( "creating vwf" );
  24. // == Public variables =====================================================================
  25. /// The runtime environment (production, development, testing) and other configuration
  26. /// settings appear here.
  27. ///
  28. /// @name module:vwf.configuration
  29. ///
  30. /// @private
  31. this.configuration = undefined; // require( "vwf/configuration" ).active; // "active" updates in place and changes don't invalidate the reference // TODO: assign here after converting vwf.js to a RequireJS module and listing "vwf/configuration" as a dependency
  32. /// Kernel utility functions and objects.
  33. ///
  34. /// @name module:vwf.utility
  35. ///
  36. /// @private
  37. this.kutility = undefined; // require( "vwf/kernel/utility" ); // TODO: assign here after converting vwf.js to a RequireJS module and listing "vwf/kernel/utility" as a dependency
  38. /// The kernel logger.
  39. ///
  40. /// @name module:vwf.logger
  41. ///
  42. /// @private
  43. this.logger = undefined; // require( "logger" ).for( undefined, this ); // TODO: for( "vwf", ... ), and update existing calls // TODO: assign here after converting vwf.js to a RequireJS module and listing "vwf/logger" as a dependency
  44. /// Each model and view module loaded by the main page registers itself here.
  45. ///
  46. /// @name module:vwf.modules
  47. ///
  48. /// @private
  49. this.modules = [];
  50. /// vwf.initialize() creates an instance of each model and view module configured on the main
  51. /// page and attaches them here.
  52. ///
  53. /// @name module:vwf.models
  54. ///
  55. /// @private
  56. this.models = [];
  57. /// vwf.initialize() creates an instance of each model and view module configured on the main
  58. /// page and attaches them here.
  59. ///
  60. /// @name module:vwf.views
  61. ///
  62. /// @private
  63. this.views = [];
  64. /// this.models is a list of references to the head of each driver pipeline. Define an
  65. /// `actual` property that evaluates to a list of references to the pipeline tails. This is
  66. /// a list of the actual drivers after any intermediate stages and is useful for debugging.
  67. ///
  68. /// @name module:vwf.models.actual
  69. Object.defineProperty( this.models, "actual", {
  70. get: function() {
  71. // Map the array to the result.
  72. var actual = this.map( function( model ) {
  73. return last( model );
  74. } );
  75. // Map the non-integer properties too.
  76. for ( var propertyName in this ) {
  77. if ( isNaN( Number( propertyName ) ) ) {
  78. actual[propertyName] = last( this[propertyName] );
  79. }
  80. }
  81. // Follow a pipeline to the last stage.
  82. function last( model ) {
  83. while ( model.model ) model = model.model;
  84. return model;
  85. }
  86. return actual;
  87. }
  88. } );
  89. /// this.views is a list of references to the head of each driver pipeline. Define an
  90. /// `actual` property that evaluates to a list of references to the pipeline tails. This is
  91. /// a list of the actual drivers after any intermediate stages and is useful for debugging.
  92. ///
  93. /// @name module:vwf.views.actual
  94. Object.defineProperty( this.views, "actual", {
  95. get: function() {
  96. // Map the array to the result.
  97. var actual = this.map( function( model ) {
  98. return last( model );
  99. } );
  100. // Map the non-integer properties too.
  101. for ( var propertyName in this ) {
  102. if ( isNaN( Number( propertyName ) ) ) {
  103. actual[propertyName] = last( this[propertyName] );
  104. }
  105. }
  106. // Follow a pipeline to the last stage.
  107. function last( model ) {
  108. while ( model.model ) model = model.model;
  109. return model;
  110. }
  111. return actual;
  112. }
  113. } );
  114. /// The simulation clock, which contains the current time in seconds. Time is controlled by
  115. /// the reflector and updates here as we receive control messages.
  116. ///
  117. /// @name module:vwf.now
  118. ///
  119. /// @private
  120. this.now = 0;
  121. /// The queue's sequence number for the currently executing action.
  122. ///
  123. /// The queue enumerates actions in order of arrival, which is distinct from execution order
  124. /// since actions may be scheduled to run in the future. `sequence_` can be used to
  125. /// distinguish between actions that were previously placed on the queue for execution at a
  126. /// later time, and those that arrived after the current action, regardless of their
  127. /// scheduled time.
  128. ///
  129. /// @name module:vwf.sequence_
  130. ///
  131. /// @private
  132. this.sequence_ = undefined;
  133. /// The moniker of the client responsible for the currently executing action. `client_` will
  134. /// be falsy for actions originating in the server, such as time ticks.
  135. ///
  136. /// @name module:vwf.client_
  137. ///
  138. /// @private
  139. this.client_ = undefined;
  140. /// The identifer assigned to the client by the server.
  141. ///
  142. /// @name module:vwf.moniker_
  143. ///
  144. /// @private
  145. this.moniker_ = undefined;
  146. /// Nodes that are receiving ticks.
  147. ///
  148. /// @name module:vwf.tickable
  149. ///
  150. /// @private
  151. this.tickable = {
  152. // models: [],
  153. // views: [],
  154. nodeIDs: [],
  155. };
  156. // == Private variables ====================================================================
  157. /// @name module:vwf.private
  158. ///
  159. /// @private
  160. this.private = {}; // for debugging
  161. /// Components describe the objects that make up the simulation. They may also serve as
  162. /// prototype objects for further derived components. External components are identified by
  163. /// URIs. Once loaded, we save a mapping here from its URI to the node ID of its prototype so
  164. /// that we can find it if it is reused. Components specified internally as object literals
  165. /// are anonymous and are not indexed here.
  166. ///
  167. /// @name module:vwf~components
  168. var components = this.private.components = {}; // maps component node ID => component specification
  169. /// This is the connection to the reflector. In this sample implementation, "socket" is a
  170. /// socket.io client that communicates over a channel provided by the server hosting the
  171. /// client documents.
  172. ///
  173. /// @name module:vwf~socket
  174. var socket = this.private.socket = undefined;
  175. // Each node is assigned an ID as it is created. This is the most recent ID assigned.
  176. // Communication between the manager and the models and views uses these IDs to refer to the
  177. // nodes. The manager doesn't maintain any particular state for the nodes and knows them
  178. // only as their IDs. The models work in federation to provide the meaning to each node.
  179. // var lastID = 0;
  180. /// Callback functions defined in this scope use this local "vwf" to locate the manager.
  181. ///
  182. /// @name module:vwf~vwf
  183. var vwf = this;
  184. // Store the jQuery module for reuse
  185. var jQuery;
  186. // == Public functions =====================================================================
  187. // -- loadConfiguration ---------------------------------------------------------------------------
  188. // The main page only needs to call vwf.loadConfiguration() to launch the application. Use
  189. // require.ready() or jQuery(document).ready() to call loadConfiguration() once the page has
  190. // loaded. loadConfiguration() accepts three parameters.
  191. //
  192. // A component specification identifies the application to be loaded. modelInitializers and
  193. // viewInitializers identify the model and view libraries that were parsed out of the URL that
  194. // should be attached to the simulation. Each is specified as an object with each library
  195. // name as a property of the object with any arguments as the value of the property.
  196. // Arguments may be specified as an array [1], as a single value if there is only one [2], or as
  197. // undefined if there are none[3].
  198. //
  199. // [1] vwf.loadConfiguration( ..., { "vwf/model/glge": [ "#scene, "second param" ] }, { ... } )
  200. // [2] vwf.loadConfiguration( ..., { "vwf/model/glge": "#scene" }, { ... } )
  201. // [3] vwf.loadConfiguration( ..., { "vwf/model/javascript": undefined }, { ... } )
  202. this.loadConfiguration = function(/* [ componentURI|componentObject ] { modelInitializers }
  203. { viewInitializers } */) {
  204. var args = Array.prototype.slice.call( arguments );
  205. if ( typeof args[0] != "object" || ! ( args[0] instanceof Array ) ) {
  206. application = args.shift();
  207. }
  208. var userLibraries = args.shift() || {};
  209. var applicationConfig = {};
  210. var callback = args.shift();
  211. var requireConfig = {
  212. shim: {
  213. "vwf/model/aframe/addon/aframe-interpolation": {
  214. deps: [ "vwf/model/aframe/aframe-master" ]
  215. },
  216. "vwf/model/aframe/extras/aframe-extras": {
  217. deps: [ "vwf/model/aframe/aframe-master" ]
  218. },
  219. "vwf/model/aframe/addon/aframe-sun-sky": {
  220. deps: [ "vwf/model/aframe/aframe-master" ]
  221. },
  222. "vwf/model/aframe/addon/BVHLoader": {
  223. deps: [ "vwf/model/aframe/aframe-master" ]
  224. },
  225. "vwf/model/aframe/addon/TransformControls": {
  226. deps: [ "vwf/model/aframe/aframe-master" ]
  227. },
  228. "vwf/model/aframe/addon/THREE.MeshLine": {
  229. deps: [ "vwf/model/aframe/aframe-master" ]
  230. },
  231. "vwf/model/aframe/addon/monument-app": {
  232. deps: [ "vwf/model/aframe/aframe-master",
  233. "vwf/model/aframe/extras/aframe-extras",
  234. "vwf/model/aframe/addon/aframe-sun-sky",
  235. "vwf/model/aframe/addon/BVHLoader",
  236. "vwf/model/aframe/addon/TransformControls",
  237. "vwf/model/aframe/addon/THREE.MeshLine"
  238. ]
  239. }
  240. }
  241. };
  242. jQuery = require("jquery");
  243. var requireArray = [
  244. { library: "domReady", active: true },
  245. { library: "vwf/configuration", active: true },
  246. { library: "vwf/kernel/model", active: true },
  247. { library: "vwf/model/javascript", active: true },
  248. { library: "vwf/model/object", active: true },
  249. { library: "vwf/model/stage/log", active: true },
  250. { library: "vwf/model/ohm", active: true },
  251. { library: "vwf/model/osc", active: true },
  252. { library: "vwf/model/aframe",
  253. linkedLibraries: [ "vwf/model/aframe/aframe-master",
  254. "vwf/model/aframe/extras/aframe-extras",
  255. "vwf/model/aframe/addon/aframe-interpolation",
  256. "vwf/model/aframe/addon/aframe-sun-sky",
  257. "vwf/model/aframe/addon/monument-app",
  258. "vwf/model/aframe/addon/BVHLoader",
  259. "vwf/model/aframe/addon/TransformControls",
  260. "vwf/model/aframe/addon/THREE.MeshLine"
  261. ],
  262. active: false
  263. },
  264. { library: "vwf/model/aframeComponent", active: true },
  265. { library: "vwf/kernel/view", active: true },
  266. { library: "vwf/view/document", active: true },
  267. { library: "vwf/view/editor-new", active: false },
  268. { library: "vwf/view/webrtc",
  269. linkedLibraries: ["vwf/view/webrtc/adapter"],
  270. active: false
  271. },
  272. { library: "vwf/view/ohm", active: true },
  273. { library: "vwf/view/osc", active: true },
  274. { library: "vwf/view/aframe", active: false },
  275. { library: "vwf/model/aframe/aframe-master", active: false },
  276. { library: "vwf/model/aframe/extras/aframe-extras", active: false },
  277. { library: "vwf/model/aframe/addon/aframe-interpolation", active: false },
  278. { library: "vwf/model/aframe/addon/aframe-sun-sky", active: false },
  279. { library: "vwf/model/aframe/addon/monument-app", active: false },
  280. { library: "vwf/model/aframe/addon/BVHLoader", active: false },
  281. { library: "vwf/model/aframe/addon/TransformControls", active: false },
  282. { library: "vwf/model/aframe/addon/THREE.MeshLine", active: false },
  283. { library: "vwf/view/aframeComponent", active: true },
  284. { library: "vwf/kernel/utility", active: true },
  285. { library: "vwf/utility", active: true },
  286. { library: "vwf/view/webrtc/adapter", active: false },
  287. { library: "vwf/admin", active: true }
  288. ];
  289. var initializers = {
  290. model: [
  291. { library: "vwf/model/javascript", active: true },
  292. { library: "vwf/model/ohm", active: true },
  293. { library: "vwf/model/osc", active: true },
  294. { library: "vwf/model/aframe", active: false },
  295. { library: "vwf/model/aframeComponent", active: true },
  296. { library: "vwf/model/object", active: true }
  297. ],
  298. view: [
  299. { library: "vwf/view/document", active: true },
  300. { library: "vwf/view/editor-new", active: false },
  301. { library: "vwf/view/ohm", active: true },
  302. { library: "vwf/view/osc", active: true },
  303. { library: "vwf/view/aframe", active: false },
  304. { library: "vwf/view/aframeComponent", active: true },
  305. { library: "vwf/view/webrtc", active: false}
  306. ]
  307. };
  308. mapLibraryName(requireArray);
  309. mapLibraryName(initializers["model"]);
  310. mapLibraryName(initializers["view"]);
  311. function mapLibraryName(array) {
  312. for(var i=0;i<array.length;i++) {
  313. array[array[i].library] = array[i];
  314. }
  315. }
  316. function getActiveLibraries(libraryList, includeParameters) {
  317. var activeLibraryList = [];
  318. for(var i=0; i<libraryList.length; i++) {
  319. if(libraryList[i].active) {
  320. if(includeParameters) {
  321. var activeLibrary = {};
  322. activeLibrary[libraryList[i].library] = libraryList[i].parameters;
  323. activeLibraryList.push(activeLibrary);
  324. }
  325. else {
  326. activeLibraryList.push(libraryList[i].library);
  327. }
  328. }
  329. }
  330. return activeLibraryList;
  331. }
  332. jQuery.getJSON("admin/config", function(configLibraries) {
  333. if(configLibraries && typeof configLibraries == "object") {
  334. if (typeof configLibraries.configuration == "object") {
  335. applicationConfig = configLibraries.configuration;
  336. }
  337. Object.keys(configLibraries).forEach(function(libraryType) {
  338. if(libraryType == 'info' && configLibraries[libraryType]["title"])
  339. {
  340. jQuery('title').html(configLibraries[libraryType]["title"]);
  341. }
  342. if(!userLibraries[libraryType]) {
  343. userLibraries[libraryType] = {};
  344. }
  345. // Merge libraries from config file and URL together. Check for incompatible
  346. // libraries, and disable them.
  347. Object.keys(configLibraries[libraryType]).forEach(function(libraryName) {
  348. var disabled = false;
  349. if(requireArray[libraryName] && requireArray[libraryName].disabledBy) {
  350. for(var i=0; i<requireArray[libraryName].disabledBy.length; i++) {
  351. Object.keys(userLibraries).forEach(function(userLibraryType) {
  352. Object.keys(userLibraries[userLibraryType]).forEach(function(userLibraryName) {
  353. if(requireArray[libraryName].disabledBy[i] == userLibraryName) {
  354. disabled = true;
  355. }
  356. })
  357. })
  358. }
  359. }
  360. if(!disabled) {
  361. if(userLibraries[libraryType][libraryName] == undefined) {
  362. userLibraries[libraryType][libraryName] = configLibraries[libraryType][libraryName];
  363. }
  364. else if(typeof userLibraries[libraryType][libraryName] == "object" && typeof configLibraries[libraryType][libraryName] == "object") {
  365. userLibraries[libraryType][libraryName] = jQuery.extend({}, configLibraries[libraryType][libraryName], userLibraries[libraryType][libraryName]);
  366. }
  367. }
  368. });
  369. });
  370. }
  371. }).always(function(jqXHR, textStatus) {
  372. Object.keys(userLibraries).forEach(function(libraryType) {
  373. if(initializers[libraryType]) {
  374. Object.keys(userLibraries[libraryType]).forEach(function(libraryName) {
  375. if(requireArray[libraryName]) {
  376. requireArray[libraryName].active = true;
  377. initializers[libraryType][libraryName].active = true;
  378. if(userLibraries[libraryType][libraryName] && userLibraries[libraryType][libraryName] != "") {
  379. if(typeof initializers[libraryType][libraryName].parameters == "object") {
  380. initializers[libraryType][libraryName].parameters = jQuery.extend({}, initializers[libraryType][libraryName].parameters,
  381. userLibraries[libraryType][libraryName]);
  382. }
  383. else {
  384. initializers[libraryType][libraryName].parameters = userLibraries[libraryType][libraryName];
  385. }
  386. }
  387. if(requireArray[libraryName].linkedLibraries) {
  388. for(var i=0; i<requireArray[libraryName].linkedLibraries.length; i++) {
  389. requireArray[requireArray[libraryName].linkedLibraries[i]].active = true;
  390. }
  391. }
  392. }
  393. });
  394. }
  395. });
  396. // Load default renderer if no other librarys specified
  397. if(Object.keys(userLibraries["model"]).length == 0 && Object.keys(userLibraries["view"]).length == 0) {
  398. // requireArray["vwf/model/threejs"].active = true;
  399. // requireArray["vwf/view/threejs"].active = true;
  400. // requireArray["vwf/model/threejs/three"].active = true;
  401. // requireArray["vwf/model/threejs/js/loaders/ColladaLoader"].active = true;
  402. // requireArray["vwf/model/threejs/js/loaders/gltf/glTF-parser"].active = true;
  403. // requireArray["vwf/model/threejs/js/loaders/gltf/glTFLoader"].active = true;
  404. // requireArray["vwf/model/threejs/js/loaders/gltf/glTFAnimation"].active = true;
  405. // requireArray["vwf/model/threejs/js/loaders/gltf/glTFLoaderUtils"].active = true;
  406. // requireArray["vwf/model/threejs/js/stereo/DeviceOrientationControls"].active = true;
  407. // requireArray["vwf/model/threejs/js/stereo/OrbitControls"].active = true;
  408. // requireArray["vwf/model/threejs/js/stereo/StereoEffect"].active = true;
  409. // initializers["model"]["vwf/model/threejs"].active = true;
  410. // initializers["view"]["vwf/view/threejs"].active = true;
  411. }
  412. require( requireConfig, getActiveLibraries(requireArray, false), function( ready ) {
  413. ready( function() {
  414. // Merge any application configuration settings into the configuration
  415. // object.
  416. require( "vwf/configuration" ).instance = require( "vwf/utility" ).merge(
  417. {}, require( "vwf/configuration" ).instance, applicationConfig );
  418. // With the scripts loaded, we must initialize the framework. vwf.initialize()
  419. // accepts three parameters: a world specification, model configuration parameters,
  420. // and view configuration parameters.
  421. vwf.initialize(application, getActiveLibraries(initializers["model"], true), getActiveLibraries(initializers["view"], true), callback);
  422. } );
  423. } );
  424. });
  425. }
  426. // -- initialize ---------------------------------------------------------------------------
  427. /// The main page only needs to call vwf.initialize() to launch the application. Use
  428. /// require.ready() or jQuery(document).ready() to call initialize() once the page has
  429. /// loaded. initialize() accepts three parameters.
  430. ///
  431. /// A component specification identifies the application to be loaded. If a URI is provided,
  432. /// the specification is loaded from there [1]. Alternately, a JavaScript object literal
  433. /// containing the specfication may be provided [2]. Since a component can extend and
  434. /// specialize a prototype, using a simple object literal allows existing component to be
  435. /// configured for special uses [3].
  436. ///
  437. /// [1] vwf.initialize( "http://vwf.example.com/applications/sample12345", ... )
  438. ///
  439. /// [2] vwf.initialize( { source: "model.dae", type: "model/vnd.collada+xml",
  440. /// properties: { "p1": ... }, ... }, ... )
  441. ///
  442. /// [3] vwf.initialize( { extends: "http://vwf.example.com/applications/sample12345",
  443. /// source: "alternate-model.dae", type: "model/vnd.collada+xml" }, ... )
  444. ///
  445. /// modelInitializers and viewInitializers identify the model and view modules that should be
  446. /// attached to the simulation. Each is specified as an array of objects that map the name of
  447. /// a model or view to construct to the set of arguments to pass to its constructor. Modules
  448. /// without parameters may be specified as a string [4]. Arguments may be specified as an
  449. /// array [5], or as a single value if there is only one [6].
  450. ///
  451. /// [4] vwf.initialize( ..., [ "vwf/model/javascript" ], [ ... ] )
  452. /// [5] vwf.initialize( ..., [ { "vwf/model/glge": [ "#scene, "second param" ] } ], [ ... ] )
  453. /// [6] vwf.initialize( ..., [ { "vwf/model/glge": "#scene" } ], [ ... ] )
  454. ///
  455. /// @name module:vwf.initialize
  456. this.initialize = function( /* [ componentURI|componentObject ] [ modelInitializers ]
  457. [ viewInitializers ] */ ) {
  458. var args = Array.prototype.slice.call( arguments );
  459. var application;
  460. // Load the runtime configuration. We start with the factory defaults. The reflector may
  461. // provide additional settings when we connect.
  462. this.configuration = require( "vwf/configuration" ).active; // "active" updates in place and changes don't invalidate the reference
  463. // Load the kernel utilities.
  464. this.kutility = require( "vwf/kernel/utility" );
  465. // Create the logger.
  466. this.logger = require( "logger" ).for( "vwf", this ); // TODO: for( "vwf", ... ), and update existing calls
  467. // Get the jQuery reference. This also happens in `loadConfiguration`, but the tests
  468. // initialize using `initialize` and don't call `loadConfiguration` first.
  469. jQuery = require("jquery");
  470. // Parse the function parameters. If the first parameter is not an array, then treat it
  471. // as the application specification. Otherwise, fall back to the "application" parameter
  472. // in the query string.
  473. if ( typeof args[0] != "object" || ! ( args[0] instanceof Array ) ) {
  474. application = args.shift();
  475. }
  476. // Shift off the parameter containing the model list and initializer arguments.
  477. var modelInitializers = args.shift() || [];
  478. // Shift off the parameter containing the view list and initializer arguments.
  479. var viewInitializers = args.shift() || [];
  480. var callback = args.shift();
  481. var compatibilityStatus = { compatible: true, errors: {} };
  482. // Create the model interface to the kernel. Models can make direct calls that execute
  483. // immediately or future calls that are placed on the queue and executed when removed.
  484. this.models.kernel = require( "vwf/kernel/model" ).create( vwf );
  485. // Create and attach each configured model.
  486. modelInitializers.forEach( function( modelInitializer ) {
  487. // Skip falsy values to allow initializers to be conditionally included by the
  488. // loader.
  489. if ( modelInitializer ) {
  490. // Accept either { "vwf/model/name": [ arguments] } or "vwf/model/name".
  491. if ( typeof modelInitializer == "object" && modelInitializer != null ) {
  492. var modelName = Object.keys( modelInitializer )[0];
  493. var modelArguments = modelInitializer[modelName];
  494. } else {
  495. var modelName = modelInitializer;
  496. var modelArguments = undefined;
  497. }
  498. var model = require( modelName ).create(
  499. this.models.kernel, // model's kernel access
  500. [ require( "vwf/model/stage/log" ) ], // stages between the kernel and model
  501. {}, // state shared with a paired view
  502. [].concat( modelArguments || [] ) // arguments for initialize()
  503. );
  504. if ( model ) {
  505. this.models.push( model );
  506. this.models[modelName] = model; // also index by id // TODO: this won't work if multiple model instances are allowed
  507. if ( modelName == "vwf/model/javascript" ) { // TODO: need a formal way to follow prototype chain from vwf.js; this is peeking inside of vwf-model-javascript
  508. this.models.javascript = model;
  509. while ( this.models.javascript.model ) this.models.javascript = this.models.javascript.model;
  510. }
  511. if ( modelName == "vwf/model/object" ) { // TODO: this is peeking inside of vwf-model-object
  512. this.models.object = model;
  513. while ( this.models.object.model ) this.models.object = this.models.object.model;
  514. }
  515. if(model.model.compatibilityStatus) {
  516. if(!model.model.compatibilityStatus.compatible) {
  517. compatibilityStatus.compatible = false;
  518. jQuery.extend(compatibilityStatus.errors, model.model.compatibilityStatus.errors);
  519. }
  520. }
  521. }
  522. }
  523. }, this );
  524. // Create the view interface to the kernel. Views can only make replicated calls which
  525. // bounce off the reflection server, are placed on the queue when received, and executed
  526. // when removed.
  527. this.views.kernel = require( "vwf/kernel/view" ).create( vwf );
  528. // Create and attach each configured view.
  529. viewInitializers.forEach( function( viewInitializer ) {
  530. // Skip falsy values to allow initializers to be conditionally included by the
  531. // loader.
  532. if ( viewInitializer ) {
  533. // Accept either { "vwf/view/name": [ arguments] } or "vwf/view/name".
  534. if ( typeof viewInitializer == "object" && viewInitializer != null ) {
  535. var viewName = Object.keys( viewInitializer )[0];
  536. var viewArguments = viewInitializer[viewName];
  537. } else {
  538. var viewName = viewInitializer;
  539. var viewArguments = undefined;
  540. }
  541. if ( ! viewName.match( "^vwf/view/" ) ) { // old way
  542. var view = this.modules[viewName];
  543. if ( view ) {
  544. var instance = new view();
  545. instance.state = this.models.actual["vwf/model/"+viewName] && this.models.actual["vwf/model/"+viewName].state || {}; // state shared with a paired model
  546. view.apply( instance, [ vwf ].concat( viewArguments || [] ) );
  547. this.views.push( instance );
  548. this.views[viewName] = instance; // also index by id // TODO: this won't work if multiple view instances are allowed
  549. if(view.compatibilityStatus) {
  550. if(!view.compatibilityStatus.compatible) {
  551. compatibilityStatus.compatible = false;
  552. jQuery.extend(compatibilityStatus.errors, view.compatibilityStatus.errors);
  553. }
  554. }
  555. }
  556. } else { // new way
  557. var modelPeer = this.models.actual[ viewName.replace( "vwf/view/", "vwf/model/" ) ]; // TODO: this.model.actual() is kind of heavy, but it's probably OK to use just a few times here at start-up
  558. var view = require( viewName ).create(
  559. this.views.kernel, // view's kernel access
  560. [], // stages between the kernel and view
  561. modelPeer && modelPeer.state || {}, // state shared with a paired model
  562. [].concat( viewArguments || [] ) // arguments for initialize()
  563. );
  564. if ( view ) {
  565. this.views.push( view );
  566. this.views[viewName] = view; // also index by id // TODO: this won't work if multiple view instances are allowed
  567. if(view.compatibilityStatus) {
  568. if(!view.compatibilityStatus.compatible) {
  569. compatibilityStatus.compatible = false;
  570. jQuery.extend(compatibilityStatus.errors, view.compatibilityStatus.errors);
  571. }
  572. }
  573. }
  574. }
  575. }
  576. }, this );
  577. // Test for ECMAScript 5
  578. if(!(function() { return !this })()) {
  579. compatibilityStatus.compatible = false;
  580. jQuery.extend(compatibilityStatus.errors, {"ES5": "This browser is not compatible. VWF requires ECMAScript 5."});
  581. }
  582. // Test for WebSockets
  583. // if( window.io && !io.Transport.websocket.check() )
  584. // {
  585. // compatibilityStatus.compatible = false;
  586. // jQuery.extend(compatibilityStatus.errors, {"WS": "This browser is not compatible. VWF requires WebSockets."});
  587. // }
  588. if(callback) {
  589. callback(compatibilityStatus);
  590. }
  591. // Load the application.
  592. this.ready( application );
  593. };
  594. // -- ready --------------------------------------------------------------------------------
  595. /// @name module:vwf.ready
  596. this.ready = function( component_uri_or_json_or_object ) {
  597. // Connect to the reflector. This implementation uses the socket.io library, which
  598. // communicates using a channel back to the server that provided the client documents.
  599. try {
  600. var options = {
  601. // The socket is relative to the application path.
  602. // resource: window.location.pathname.slice( 1,
  603. // window.location.pathname.lastIndexOf("/") ),
  604. query: 'pathname=' + window.location.pathname.slice( 1,
  605. window.location.pathname.lastIndexOf("/") ),
  606. // Use a secure connection when the application comes from https.
  607. secure: window.location.protocol === "https:",
  608. // Don't attempt to reestablish lost connections. The client reloads after a
  609. // disconnection to recreate the application from scratch.
  610. //reconnect: false,
  611. reconnection: false,
  612. transports: ['websocket']
  613. };
  614. if ( isSocketIO07() ) {
  615. socket = io.connect( window.location.protocol + "//" + window.location.host,options );
  616. } else { // Ruby Server -- only supports socket.io 0.6
  617. io.util.merge( options, {
  618. // For socket.io 0.6, specify the port since the default isn't correct when
  619. // using https.
  620. port: window.location.port ||
  621. ( window.location.protocol === "https:" ? 443 : 80 ),
  622. // The ruby socket.io server only supports WebSockets. Don't try the others.
  623. transports: [
  624. 'websocket',
  625. ],
  626. // Increase the timeout because of starvation while loading the scene. The
  627. // server timeout must also be increased. (For socket.io 0.7+, the client
  628. // timeout is controlled by the server.)
  629. transportOptions: {
  630. "websocket": { timeout: 90000 },
  631. },
  632. } );
  633. socket = io.connect( undefined, options );
  634. }
  635. } catch ( e ) {
  636. // If a connection to the reflector is not available, then run in single-user mode.
  637. // Messages intended for the reflector will loop directly back to us in this case.
  638. // Start a timer to monitor the incoming queue and dispatch the messages as though
  639. // they were received from the server.
  640. this.dispatch();
  641. setInterval( function() {
  642. var fields = {
  643. time: vwf.now + 0.010, // TODO: there will be a slight skew here since the callback intervals won't be exactly 10 ms; increment using the actual delta time; also, support play/pause/stop and different playback rates as with connected mode.
  644. origin: "reflector",
  645. };
  646. queue.insert( fields, true ); // may invoke dispatch(), so call last before returning to the host
  647. }, 10 );
  648. }
  649. if ( socket ) {
  650. socket.on( "connect", function() {
  651. vwf.logger.infox( "-socket", "connected" );
  652. if ( isSocketIO07() ) {
  653. vwf.moniker_ = this.id;
  654. } else { //Ruby Server
  655. vwf.moniker_ = this.transport.sessionid;
  656. }
  657. } );
  658. // Configure a handler to receive messages from the server.
  659. // Note that this example code doesn't implement a robust parser capable of handling
  660. // arbitrary text and that the messages should be placed in a dedicated priority
  661. // queue for best performance rather than resorting the queue as each message
  662. // arrives. Additionally, overlapping messages may cause actions to be performed out
  663. // of order in some cases if messages are not processed on a single thread.
  664. socket.on( "message", function( message ) {
  665. // vwf.logger.debugx( "-socket", "message", message );
  666. try {
  667. if ( isSocketIO07() ) {
  668. var fields = message;
  669. } else { // Ruby Server - Unpack the arguements
  670. var fields = JSON.parse( message );
  671. }
  672. fields.time = Number( fields.time );
  673. // TODO: other message validation (check node id, others?)
  674. fields.origin = "reflector";
  675. // Update the queue. Messages in the queue are ordered by time, then by order of arrival.
  676. // Time is only advanced if the message has no action, meaning it is a tick.
  677. queue.insert( fields, !fields.action ); // may invoke dispatch(), so call last before returning to the host
  678. // Each message from the server allows us to move time forward. Parse the
  679. // timestamp from the message and call dispatch() to execute all queued
  680. // actions through that time, including the message just received.
  681. // The simulation may perform immediate actions at the current time or it
  682. // may post actions to the queue to be performed in the future. But we only
  683. // move time forward for items arriving in the queue from the reflector.
  684. } catch ( e ) {
  685. vwf.logger.warn( fields.action, fields.node, fields.member, fields.parameters,
  686. "exception performing action:", require( "vwf/utility" ).exceptionMessage( e ) );
  687. }
  688. } );
  689. socket.on( "disconnect", function() {
  690. vwf.logger.infox( "-socket", "disconnected" );
  691. // Reload to rejoin the application.
  692. window.location = window.location.href;
  693. } );
  694. socket.on( "error", function() {
  695. //Overcome by compatibility.js websockets check
  696. jQuery('body').html("<div class='vwf-err'>WebSockets connections are currently being blocked. Please check your proxy server settings.</div>");
  697. } );
  698. if ( !isSocketIO07() ) {
  699. // Start communication with the reflector.
  700. socket.connect(); // TODO: errors can occur here too, particularly if a local client contains the socket.io files but there is no server; do the loopback here instead of earlier in response to new io.Socket.
  701. }
  702. } else if ( component_uri_or_json_or_object ) {
  703. // Load the application. The application is rooted in a single node constructed here
  704. // as an instance of the component passed to initialize(). That component, its
  705. // prototype(s), and its children, and their prototypes and children, flesh out the
  706. // entire application.
  707. // TODO: add note that this is only for a self-determined application; with socket, wait for reflection server to tell us.
  708. // TODO: maybe depends on component_uri_or_json_or_object too; when to override and not connect to reflection server?
  709. this.createNode( component_uri_or_json_or_object, "application" );
  710. } else { // TODO: also do this if component_uri_or_json_or_object was invalid and createNode() failed
  711. // TODO: show a selection dialog
  712. }
  713. };
  714. // -- plan ---------------------------------------------------------------------------------
  715. /// @name module:vwf.plan
  716. this.plan = function( nodeID, actionName, memberName, parameters, when, callback_async /* ( result ) */ ) {
  717. this.logger.debuggx( "plan", nodeID, actionName, memberName,
  718. parameters && parameters.length, when, callback_async && "callback" );
  719. var time = when > 0 ? // absolute (+) or relative (-)
  720. Math.max( this.now, when ) :
  721. this.now + ( -when );
  722. var fields = {
  723. time: time,
  724. node: nodeID,
  725. action: actionName,
  726. member: memberName,
  727. parameters: parameters,
  728. client: this.client_, // propagate originating client
  729. origin: "future",
  730. // callback: callback_async, // TODO
  731. };
  732. queue.insert( fields );
  733. this.logger.debugu();
  734. };
  735. // -- send ---------------------------------------------------------------------------------
  736. /// Send a message to the reflector. The message will be reflected back to all participants
  737. /// in the instance.
  738. ///
  739. /// @name module:vwf.send
  740. this.send = function( nodeID, actionName, memberName, parameters, when, callback_async /* ( result ) */ ) {
  741. this.logger.debuggx( "send", nodeID, actionName, memberName,
  742. parameters && parameters.length, when, callback_async && "callback" ); // TODO: loggableParameters()
  743. var time = when > 0 ? // absolute (+) or relative (-)
  744. Math.max( this.now, when ) :
  745. this.now + ( -when );
  746. // Attach the current simulation time and pack the message as an array of the arguments.
  747. var fields = {
  748. time: time,
  749. node: nodeID,
  750. action: actionName,
  751. member: memberName,
  752. parameters: require( "vwf/utility" ).transform( parameters, require( "vwf/utility" ).transforms.transit ),
  753. // callback: callback_async, // TODO: provisionally add fields to queue (or a holding queue) then execute callback when received back from reflector
  754. };
  755. if ( socket ) {
  756. // Send the message.
  757. var message = JSON.stringify( fields );
  758. socket.send( message );
  759. } else {
  760. // In single-user mode, loop the message back to the incoming queue.
  761. fields.client = this.moniker_; // stamp with the originating client like the reflector does
  762. fields.origin = "reflector";
  763. queue.insert( fields );
  764. }
  765. this.logger.debugu();
  766. };
  767. // -- respond ------------------------------------------------------------------------------
  768. /// Return a result for a function invoked by the server.
  769. ///
  770. /// @name module:vwf.respond
  771. this.respond = function( nodeID, actionName, memberName, parameters, result ) {
  772. this.logger.debuggx( "respond", nodeID, actionName, memberName,
  773. parameters && parameters.length, "..." ); // TODO: loggableParameters(), loggableResult()
  774. // Attach the current simulation time and pack the message as an array of the arguments.
  775. var fields = {
  776. // sequence: undefined, // TODO: use to identify on return from reflector?
  777. time: this.now,
  778. node: nodeID,
  779. action: actionName,
  780. member: memberName,
  781. parameters: require( "vwf/utility" ).transform( parameters, require( "vwf/utility" ).transforms.transit ),
  782. result: require( "vwf/utility" ).transform( result, require( "vwf/utility" ).transforms.transit ),
  783. };
  784. if ( socket ) {
  785. // Send the message.
  786. var message = JSON.stringify( fields );
  787. socket.send( message );
  788. } else {
  789. // Nothing to do in single-user mode.
  790. }
  791. this.logger.debugu();
  792. };
  793. // -- receive ------------------------------------------------------------------------------
  794. /// Handle receipt of a message. Unpack the arguments and call the appropriate handler.
  795. ///
  796. /// @name module:vwf.receive
  797. this.receive = function( nodeID, actionName, memberName, parameters, respond, origin ) {
  798. // origin == "reflector" ?
  799. // this.logger.infogx( "receive", nodeID, actionName, memberName,
  800. // parameters && parameters.length, respond, origin ) :
  801. // this.logger.debuggx( "receive", nodeID, actionName, memberName,
  802. // parameters && parameters.length, respond, origin );
  803. // TODO: delegate parsing and validation to each action.
  804. // Look up the action handler and invoke it with the remaining parameters.
  805. // Note that the message should be validated before looking up and invoking an arbitrary
  806. // handler.
  807. var args = [], result;
  808. if ( nodeID || nodeID === 0 ) args.push( nodeID );
  809. if ( memberName ) args.push( memberName );
  810. if ( parameters ) args = args.concat( parameters ); // flatten
  811. if(actionName == 'createChild')
  812. {
  813. console.log("create child!");
  814. // args.push(function(childID)
  815. // {
  816. // //when creating over the reflector, call ready on heirarchy after create.
  817. // //nodes from setState are readied in createNode
  818. // // vwf.decendants(childID).forEach(function(i){
  819. // // vwf.callMethod(i,'ready',[]);
  820. // // });
  821. // // vwf.callMethod(childID,'ready',[]);
  822. // console.log("create child!");
  823. // });
  824. }
  825. // Invoke the action.
  826. if ( environment( actionName, parameters ) ) {
  827. require( "vwf/configuration" ).environment = environment( actionName, parameters );
  828. } else if ( origin !== "reflector" || ! nodeID || nodes.existing[ nodeID ] ) {
  829. result = this[ actionName ] && this[ actionName ].apply( this, args );
  830. } else {
  831. this.logger.debugx( "receive", "ignoring reflector action on non-existent node", nodeID );
  832. result = undefined;
  833. }
  834. // Return the result.
  835. respond && this.respond( nodeID, actionName, memberName, parameters, result );
  836. // origin == "reflector" ?
  837. // this.logger.infou() : this.logger.debugu();
  838. /// The reflector sends a `setState` action as part of the application launch to pass
  839. /// the server's execution environment to the client. A `setState` action isn't really
  840. /// appropriate though since `setState` should be the last part of the launch, whereas
  841. /// the environment ought to be set much earlier--ideally before the kernel loads.
  842. ///
  843. /// Executing the `setState` as received would overwrite any configuration settings
  844. /// already applied by the application. So instead, we detect this particular message
  845. /// and only use it to update the environment in the configuration object.
  846. ///
  847. /// `environment` determines if a message is the reflector's special pre-launch
  848. /// `setState` action, and if so, and if the application hasn't been created yet,
  849. /// returns the execution environment property.
  850. function environment( actionName, parameters ) {
  851. if ( actionName === "setState" && ! vwf.application() ) {
  852. var applicationState = parameters && parameters[0];
  853. if ( applicationState && Object.keys( applicationState ).length === 1 &&
  854. applicationState.configuration && Object.keys( applicationState.configuration ).length === 1 ) {
  855. return applicationState.configuration.environment;
  856. }
  857. }
  858. return undefined;
  859. }
  860. };
  861. // -- dispatch -----------------------------------------------------------------------------
  862. /// Dispatch incoming messages waiting in the queue. "currentTime" specifies the current
  863. /// simulation time that we should advance to and was taken from the time stamp of the last
  864. /// message received from the reflector.
  865. ///
  866. /// @name module:vwf.dispatch
  867. this.dispatch = function() {
  868. var fields;
  869. // Actions may use receive's ready function to suspend the queue for asynchronous
  870. // operations, and to resume it when the operation is complete.
  871. while ( fields = /* assignment! */ queue.pull() ) {
  872. // Advance time to the message time.
  873. if ( this.now != fields.time ) {
  874. this.sequence_ = undefined; // clear after the previous action
  875. this.client_ = undefined; // clear after the previous action
  876. this.now = fields.time;
  877. this.tock();
  878. }
  879. // Perform the action.
  880. if ( fields.action ) { // TODO: don't put ticks on the queue but just use them to fast-forward to the current time (requires removing support for passing ticks to the drivers and nodes)
  881. this.sequence_ = fields.sequence; // note the message's queue sequence number for the duration of the action
  882. this.client_ = fields.client; // ... and note the originating client
  883. this.receive( fields.node, fields.action, fields.member, fields.parameters, fields.respond, fields.origin );
  884. }
  885. else {
  886. this.tick();
  887. }
  888. }
  889. // Advance time to the most recent time received from the server. Tick if the time
  890. // changed.
  891. if ( queue.ready() && this.now != queue.time ) {
  892. this.sequence_ = undefined; // clear after the previous action
  893. this.client_ = undefined; // clear after the previous action
  894. this.now = queue.time;
  895. this.tock();
  896. }
  897. };
  898. // -- log ----------------------------------------------------------------------------------
  899. /// Send a log message to the reflector.
  900. ///
  901. /// @name module:vwf.log
  902. this.log = function() {
  903. this.respond( undefined, "log", undefined, undefined, arguments );
  904. }
  905. // -- tick ---------------------------------------------------------------------------------
  906. /// Tick each tickable model, view, and node. Ticks are sent on each reflector idle message.
  907. ///
  908. /// @name module:vwf.tick
  909. // TODO: remove, in favor of drivers and nodes exclusively using future scheduling;
  910. // TODO: otherwise, all clients must receive exactly the same ticks at the same times.
  911. this.tick = function() {
  912. // Call ticking() on each model.
  913. this.models.forEach( function( model ) {
  914. model.ticking && model.ticking( this.now ); // TODO: maintain a list of tickable models and only call those
  915. }, this );
  916. // Call ticked() on each view.
  917. this.views.forEach( function( view ) {
  918. view.ticked && view.ticked( this.now ); // TODO: maintain a list of tickable views and only call those
  919. }, this );
  920. // Call tick() on each tickable node.
  921. this.tickable.nodeIDs.forEach( function( nodeID ) {
  922. this.callMethod( nodeID, "tick", [ this.now ] );
  923. }, this );
  924. };
  925. // -- tock ---------------------------------------------------------------------------------
  926. /// Notify views of a kernel time change. Unlike `tick`, `tock` messages are sent each time
  927. /// that time moves forward. Only view drivers are notified since the model state should be
  928. /// independent of any particular sequence of idle messages.
  929. ///
  930. /// @name module:vwf.tock
  931. this.tock = function() {
  932. // Call tocked() on each view.
  933. this.views.forEach( function( view ) {
  934. view.tocked && view.tocked( this.now );
  935. }, this );
  936. };
  937. // -- setState -----------------------------------------------------------------------------
  938. /// setState may complete asynchronously due to its dependence on createNode. To prevent
  939. /// actions from executing out of order, queue processing must be suspended while setState is
  940. /// in progress. createNode suspends the queue when necessary, but additional calls to
  941. /// suspend and resume the queue may be needed if other async operations are added.
  942. ///
  943. /// @name module:vwf.setState
  944. ///
  945. /// @see {@link module:vwf/api/kernel.setState}
  946. this.setState = function( applicationState, callback_async /* () */ ) {
  947. this.logger.debuggx( "setState" ); // TODO: loggableState
  948. // Set the runtime configuration.
  949. if ( applicationState.configuration ) {
  950. require( "vwf/configuration" ).instance = applicationState.configuration;
  951. }
  952. // Update the internal kernel state.
  953. if ( applicationState.kernel ) {
  954. if ( applicationState.kernel.time !== undefined ) vwf.now = applicationState.kernel.time;
  955. }
  956. // Create or update global nodes and their descendants.
  957. var nodes = applicationState.nodes || [];
  958. var annotations = applicationState.annotations || {};
  959. var nodeIndex = 0;
  960. async.forEachSeries( nodes, function( nodeComponent, each_callback_async /* ( err ) */ ) {
  961. // Look up a possible annotation for this node. For backward compatibility, if the
  962. // state has exactly one node and doesn't contain an annotations object, assume the
  963. // node is the application.
  964. var nodeAnnotation = nodes.length > 1 || applicationState.annotations ?
  965. annotations[nodeIndex] : "application";
  966. vwf.createNode( nodeComponent, nodeAnnotation, function( nodeID ) /* async */ {
  967. each_callback_async( undefined );
  968. } );
  969. nodeIndex++;
  970. }, function( err ) /* async */ {
  971. // Clear the message queue, except for reflector messages that arrived after the
  972. // current action.
  973. queue.filter( function( fields ) {
  974. if ( fields.origin === "reflector" && fields.sequence > vwf.sequence_ ) {
  975. return true;
  976. } else {
  977. vwf.logger.debugx( "setState", function() {
  978. return [ "removing", JSON.stringify( loggableFields( fields ) ), "from queue" ];
  979. } );
  980. }
  981. } );
  982. // Set the queue time and add the incoming items to the queue.
  983. if ( applicationState.queue ) {
  984. queue.time = applicationState.queue.time;
  985. queue.insert( applicationState.queue.queue || [] );
  986. }
  987. callback_async && callback_async();
  988. } );
  989. this.logger.debugu();
  990. };
  991. // -- getState -----------------------------------------------------------------------------
  992. /// @name module:vwf.getState
  993. ///
  994. /// @see {@link module:vwf/api/kernel.getState}
  995. this.getState = function( full, normalize ) {
  996. this.logger.debuggx( "getState", full, normalize );
  997. // Get the application nodes and queue.
  998. var applicationState = {
  999. // Runtime configuration.
  1000. configuration:
  1001. require( "vwf/configuration" ).active,
  1002. // Internal kernel state.
  1003. kernel: {
  1004. time: vwf.now,
  1005. },
  1006. // Global node and descendant deltas.
  1007. nodes: [ // TODO: all global objects
  1008. this.getNode( "http://vwf.example.com/clients.vwf", full ),
  1009. this.getNode( this.application(), full ),
  1010. ],
  1011. // `createNode` annotations, keyed by `nodes` indexes.
  1012. annotations: {
  1013. 1: "application",
  1014. },
  1015. // Message queue.
  1016. queue: { // TODO: move to the queue object
  1017. time: queue.time,
  1018. queue: require( "vwf/utility" ).transform( queue.queue, queueTransitTransformation ),
  1019. },
  1020. };
  1021. // Normalize for consistency.
  1022. if ( normalize ) {
  1023. applicationState = require( "vwf/utility" ).transform(
  1024. applicationState, require( "vwf/utility" ).transforms.hash );
  1025. }
  1026. this.logger.debugu();
  1027. return applicationState;
  1028. };
  1029. // -- hashState ----------------------------------------------------------------------------
  1030. /// @name module:vwf.hashState
  1031. ///
  1032. /// @see {@link module:vwf/api/kernel.hashState}
  1033. this.hashState = function() {
  1034. this.logger.debuggx( "hashState" );
  1035. var applicationState = this.getState( true, true );
  1036. // Hash the nodes.
  1037. var hashn = this.hashNode( applicationState.nodes[0] ); // TODO: all global objects
  1038. // Hash the queue.
  1039. var hashq = "q" + Crypto.MD5( JSON.stringify( applicationState.queue ) ).toString().substring( 0, 16 );
  1040. // Hash the other kernel properties.
  1041. var hashk = "k" + Crypto.MD5( JSON.stringify( applicationState.kernel ) ).toString().substring( 0, 16 );
  1042. this.logger.debugu();
  1043. // Generate the combined hash.
  1044. return hashn + ":" + hashq + ":" + hashk;
  1045. }
  1046. // -- createNode ---------------------------------------------------------------------------
  1047. /// Create a node from a component specification. Construction may require loading data from
  1048. /// multiple remote documents. This function returns before construction is complete. A
  1049. /// callback is invoked once the node has fully loaded.
  1050. ///
  1051. /// A simple node consists of a set of properties, methods and events, but a node may
  1052. /// specialize a prototype component and may also contain multiple child nodes, any of which
  1053. /// may specialize a prototype component and contain child nodes, etc. So components cover a
  1054. /// vast range of complexity. The application definition for the overall simulation is a
  1055. /// single component instance.
  1056. ///
  1057. /// A node is a component instance--a single, anonymous specialization of its component.
  1058. /// Nodes specialize components in the same way that any component may specialize a prototype
  1059. /// component. The prototype component is made available as a base, then new or modified
  1060. /// properties, methods, events, child nodes and scripts are attached to modify the base
  1061. /// implemenation.
  1062. ///
  1063. /// To create a node, we first make the prototoype available by loading it (if it has not
  1064. /// already been loaded). This is a recursive call to createNode() with the prototype
  1065. /// specification. Then we add new, and modify existing, properties, methods, and events
  1066. /// according to the component specification. Then we load and add any children, again
  1067. /// recursively calling createNode() for each. Finally, we attach any new scripts and invoke
  1068. /// an initialization function.
  1069. ///
  1070. /// createNode may complete asynchronously due to its dependence on setNode, createChild and
  1071. /// loadComponent. To prevent actions from executing out of order, queue processing must be
  1072. /// suspended while createNode is in progress. setNode, createChild and loadComponent suspend
  1073. /// the queue when necessary, but additional calls to suspend and resume the queue may be
  1074. /// needed if other async operations are added.
  1075. ///
  1076. /// @name module:vwf.createNode
  1077. ///
  1078. /// @see {@link module:vwf/api/kernel.createNode}
  1079. this.createNode = function( nodeComponent, nodeAnnotation, baseURI, callback_async /* ( nodeID ) */ ) {
  1080. // Interpret `createNode( nodeComponent, callback )` as
  1081. // `createNode( nodeComponent, undefined, undefined, callback )` and
  1082. // `createNode( nodeComponent, nodeAnnotation, callback )` as
  1083. // `createNode( nodeComponent, nodeAnnotation, undefined, callback )`. `nodeAnnotation`
  1084. // was added in 0.6.12, and `baseURI` was added in 0.6.25.
  1085. if ( typeof nodeAnnotation == "function" || nodeAnnotation instanceof Function ) {
  1086. callback_async = nodeAnnotation;
  1087. baseURI = undefined;
  1088. nodeAnnotation = undefined;
  1089. } else if ( typeof baseURI == "function" || baseURI instanceof Function ) {
  1090. callback_async = baseURI;
  1091. baseURI = undefined;
  1092. }
  1093. this.logger.debuggx( "createNode", function() {
  1094. return [ JSON.stringify( loggableComponent( nodeComponent ) ), nodeAnnotation ];
  1095. } );
  1096. var nodePatch;
  1097. if ( componentIsDescriptor( nodeComponent ) && nodeComponent.patches ) {
  1098. nodePatch = nodeComponent;
  1099. nodeComponent = nodeComponent.patches; // TODO: possible sync errors if the patched node is a URI component and the kernel state (time, random) is different from when the node was created on the originating client
  1100. }
  1101. // nodeComponent may be a URI, a descriptor, or an ID. While being created, it will
  1102. // transform from a URI to a descriptor to an ID (depending on its starting state).
  1103. // nodeURI, nodeDescriptor, and nodeID capture the intermediate states.
  1104. var nodeURI, nodeDescriptor, nodeID;
  1105. async.series( [
  1106. // If `nodeComponent` is a URI, load the descriptor. `nodeComponent` may be a URI, a
  1107. // descriptor or an ID here.
  1108. function( series_callback_async /* ( err, results ) */ ) {
  1109. if ( componentIsURI( nodeComponent ) ) { // URI // TODO: allow non-vwf URIs (models, images, etc.) to pass through to stage 2 and pass directly to createChild()
  1110. // Resolve relative URIs, but leave host-relative, locally-absolute
  1111. // references intact.
  1112. nodeURI = nodeComponent[0] == "/" ?
  1113. nodeComponent : require( "vwf/utility" ).resolveURI( nodeComponent, baseURI );
  1114. // Load the document if we haven't seen this URI yet. Mark the components
  1115. // list to indicate that this component is loading.
  1116. if ( ! components[nodeURI] ) { // uri is not loading (Array) or is loaded (id)
  1117. components[nodeURI] = []; // [] => array of callbacks while loading => true
  1118. loadComponent( nodeURI, undefined, function( nodeDescriptor ) /* async */ {
  1119. nodeComponent = nodeDescriptor;
  1120. series_callback_async( undefined, undefined );
  1121. }, function( errorMessage ) {
  1122. nodeComponent = undefined;
  1123. series_callback_async( errorMessage, undefined );
  1124. } );
  1125. // If we've seen this URI, but it is still loading, just add our callback to
  1126. // the list. The original load's completion will call our callback too.
  1127. } else if ( components[nodeURI] instanceof Array ) { // uri is loading
  1128. callback_async && components[nodeURI].push( callback_async ); // TODO: is this leaving a series callback hanging if we don't call series_callback_async?
  1129. // If this URI has already loaded, skip to the end and call the callback
  1130. // with the ID.
  1131. } else { // uri is loaded
  1132. if ( nodePatch ) {
  1133. vwf.setNode( components[nodeURI], nodePatch, function( nodeID ) /* async */ {
  1134. callback_async && callback_async( components[nodeURI] ); // TODO: is this leaving a series callback hanging if we don't call series_callback_async?
  1135. } );
  1136. } else {
  1137. callback_async && callback_async( components[nodeURI] ); // TODO: is this leaving a series callback hanging if we don't call series_callback_async?
  1138. }
  1139. }
  1140. } else { // descriptor, ID or error
  1141. series_callback_async( undefined, undefined );
  1142. }
  1143. },
  1144. // Rudimentary support for `{ includes: prototype }`, which absorbs a prototype
  1145. // descriptor into the node descriptor before creating the node.
  1146. // Notes:
  1147. //
  1148. // - Only supports one level, so `{ includes: prototype }` won't work if the
  1149. // prototype also contains a `includes` directive).
  1150. // - Only works with prototype URIs, so `{ includes: { ... descriptor ... } }`
  1151. // won't work.
  1152. // - Loads the prototype on each reference, so unlike real prototypes, multiple
  1153. // references to the same prototype cause multiple network loads.
  1154. //
  1155. // Also see the `mergeDescriptors` limitations.
  1156. function( series_callback_async /* ( err, results ) */ ) {
  1157. if ( componentIsDescriptor( nodeComponent ) && nodeComponent.includes && componentIsURI( nodeComponent.includes ) ) { // TODO: for "includes:", accept an already-loaded component (which componentIsURI exludes) since the descriptor will be loaded again
  1158. var prototypeURI = require( "vwf/utility" ).resolveURI( nodeComponent.includes, nodeURI || baseURI );
  1159. loadComponent( prototypeURI, undefined, function( prototypeDescriptor ) /* async */ {
  1160. prototypeDescriptor = resolvedDescriptor( prototypeDescriptor, prototypeURI );
  1161. nodeComponent = mergeDescriptors( nodeComponent, prototypeDescriptor ); // modifies prototypeDescriptor
  1162. series_callback_async( undefined, undefined );
  1163. }, function( errorMessage ) {
  1164. nodeComponent = undefined;
  1165. series_callback_async( errorMessage, undefined );
  1166. } );
  1167. } else {
  1168. series_callback_async( undefined, undefined );
  1169. }
  1170. },
  1171. // If `nodeComponent` is a descriptor, construct and get the ID. `nodeComponent` may
  1172. // be a descriptor or an ID here.
  1173. function( series_callback_async /* ( err, results ) */ ) {
  1174. if ( componentIsDescriptor( nodeComponent ) ) { // descriptor // TODO: allow non-vwf URIs (models, images, etc.) to pass through to stage 2 and pass directly to createChild()
  1175. nodeDescriptor = nodeComponent;
  1176. // Create the node as an unnamed child global object.
  1177. vwf.createChild( 0, nodeAnnotation, nodeDescriptor, nodeURI, function( nodeID ) /* async */ {
  1178. nodeComponent = nodeID;
  1179. series_callback_async( undefined, undefined );
  1180. } );
  1181. } else { // ID or error
  1182. series_callback_async( undefined, undefined );
  1183. }
  1184. },
  1185. // nodeComponent is an ID here.
  1186. function( series_callback_async /* ( err, results ) */ ) {
  1187. if ( componentIsID( nodeComponent ) || components[ nodeComponent ] instanceof Array ) { // ID
  1188. nodeID = nodeComponent;
  1189. if ( nodePatch ) {
  1190. vwf.setNode( nodeID, nodePatch, function( nodeID ) /* async */ {
  1191. series_callback_async( undefined, undefined );
  1192. } );
  1193. } else {
  1194. series_callback_async( undefined, undefined );
  1195. }
  1196. } else { // error
  1197. series_callback_async( undefined, undefined ); // TODO: error
  1198. }
  1199. },
  1200. ], function( err, results ) /* async */ {
  1201. // If this node derived from a URI, save the list of callbacks waiting for
  1202. // completion and update the component list with the ID.
  1203. if ( nodeURI ) {
  1204. var callbacks_async = components[nodeURI];
  1205. components[nodeURI] = nodeID;
  1206. }
  1207. // Pass the ID to our callback.
  1208. callback_async && callback_async( nodeID ); // TODO: handle error if invalid id
  1209. // Call the other callbacks.
  1210. if ( nodeURI ) {
  1211. callbacks_async.forEach( function( callback_async ) {
  1212. callback_async && callback_async( nodeID );
  1213. } );
  1214. }
  1215. } );
  1216. this.logger.debugu();
  1217. };
  1218. // -- deleteNode ---------------------------------------------------------------------------
  1219. /// @name module:vwf.deleteNode
  1220. ///
  1221. /// @see {@link module:vwf/api/kernel.deleteNode}
  1222. this.deleteNode = function( nodeID ) {
  1223. this.logger.debuggx( "deleteNode", nodeID );
  1224. // Send the meta event into the application. We send it before deleting the child so
  1225. // that the child will still be available for review.
  1226. var parentID = this.parent( nodeID );
  1227. if ( parentID !== 0 ) {
  1228. var nodeIndex = this.children( parentID ).indexOf( nodeID );
  1229. if ( nodeIndex < 0 ) {
  1230. nodeIndex = undefined;
  1231. }
  1232. if ( this.models.kernel.enabled() ) {
  1233. this.fireEvent( parentID, [ "children", "removed" ],
  1234. [ nodeIndex, this.kutility.nodeReference( nodeID ) ] );
  1235. }
  1236. }
  1237. // Remove the entry in the components list if this was the root of a component loaded
  1238. // from a URI.
  1239. Object.keys( components ).some( function( nodeURI ) { // components: nodeURI => nodeID
  1240. if ( components[nodeURI] == nodeID ) {
  1241. delete components[nodeURI];
  1242. return true;
  1243. }
  1244. } );
  1245. // Call deletingNode() on each model. The node is considered deleted after all models
  1246. // have run.
  1247. this.models.forEach( function( model ) {
  1248. model.deletingNode && model.deletingNode( nodeID );
  1249. } );
  1250. // Unregister the node.
  1251. nodes.delete( nodeID );
  1252. // Call deletedNode() on each view. The view is being notified that a node has been
  1253. // deleted.
  1254. this.views.forEach( function( view ) {
  1255. view.deletedNode && view.deletedNode( nodeID );
  1256. } );
  1257. this.logger.debugu();
  1258. };
  1259. // -- setNode ------------------------------------------------------------------------------
  1260. /// setNode may complete asynchronously due to its dependence on createChild. To prevent
  1261. /// actions from executing out of order, queue processing must be suspended while setNode is
  1262. /// in progress. createChild suspends the queue when necessary, but additional calls to
  1263. /// suspend and resume the queue may be needed if other async operations are added.
  1264. ///
  1265. /// @name module:vwf.setNode
  1266. ///
  1267. /// @see {@link module:vwf/api/kernel.setNode}
  1268. this.setNode = function( nodeID, nodeComponent, callback_async /* ( nodeID ) */ ) { // TODO: merge with createChild?
  1269. this.logger.debuggx( "setNode", function() {
  1270. return [ nodeID, JSON.stringify( loggableComponent( nodeComponent ) ) ];
  1271. } );
  1272. var node = nodes.existing[nodeID];
  1273. // Set the internal state.
  1274. vwf.models.object.internals( nodeID, nodeComponent );
  1275. // Suppress kernel reentry so that we can write the state without coloring from
  1276. // any scripts.
  1277. vwf.models.kernel.disable();
  1278. // Create the properties, methods, and events. For each item in each set, invoke
  1279. // createProperty(), createMethod(), or createEvent() to create the field. Each
  1280. // delegates to the models and views as above.
  1281. // Properties.
  1282. nodeComponent.properties && Object.keys( nodeComponent.properties ).forEach( function( propertyName ) { // TODO: setProperties should be adapted like this to be used here
  1283. var propertyValue = nodeComponent.properties[ propertyName ];
  1284. // Is the property specification directing us to create a new property, or
  1285. // initialize a property already defined on a prototype?
  1286. // Create a new property if the property is not defined on a prototype.
  1287. // Otherwise, initialize the property.
  1288. var creating = ! node.properties.has( propertyName ); // not defined on node or prototype
  1289. // Translate node references in the descriptor's form `{ node: nodeID }` into kernel
  1290. // node references.
  1291. if ( valueHasAccessors( propertyValue ) && propertyValue.node ) {
  1292. propertyValue = vwf.kutility.nodeReference( propertyValue.node );
  1293. }
  1294. // Create or initialize the property.
  1295. if ( creating ) {
  1296. vwf.createProperty( nodeID, propertyName, propertyValue );
  1297. } else {
  1298. vwf.setProperty( nodeID, propertyName, propertyValue );
  1299. } // TODO: delete when propertyValue === null in patch
  1300. } );
  1301. // Methods.
  1302. nodeComponent.methods && Object.keys( nodeComponent.methods ).forEach( function( methodName ) {
  1303. var methodHandler = nodeComponent.methods[ methodName ];
  1304. var creating = ! node.methods.has( methodName ); // not defined on node or prototype
  1305. // Create or initialize the method.
  1306. if ( creating ) {
  1307. vwf.createMethod( nodeID, methodName, methodHandler.parameters, methodHandler.body );
  1308. } else {
  1309. vwf.setMethod( nodeID, methodName, methodHandler );
  1310. } // TODO: delete when methodHandler === null in patch
  1311. } );
  1312. // Events.
  1313. nodeComponent.events && Object.keys( nodeComponent.events ).forEach( function( eventName ) {
  1314. var eventDescriptor = nodeComponent.events[ eventName ];
  1315. var creating = ! node.events.has( eventName ); // not defined on node or prototype
  1316. // Create or initialize the event.
  1317. if ( creating ) {
  1318. vwf.createEvent( nodeID, eventName, eventDescriptor.parameters );
  1319. vwf.setEvent( nodeID, eventName, eventDescriptor ); // set the listeners since `createEvent` can't do it yet
  1320. } else {
  1321. vwf.setEvent( nodeID, eventName, eventDescriptor );
  1322. } // TODO: delete when eventDescriptor === null in patch
  1323. } );
  1324. // Restore kernel reentry.
  1325. vwf.models.kernel.enable();
  1326. async.series( [
  1327. function( series_callback_async /* ( err, results ) */ ) {
  1328. // Create and attach the children. For each child, call createChild() with the
  1329. // child's component specification. createChild() delegates to the models and
  1330. // views as before.
  1331. async.forEach( Object.keys( nodeComponent.children || {} ), function( childName, each_callback_async /* ( err ) */ ) {
  1332. var creating = ! nodeHasOwnChild.call( vwf, nodeID, childName );
  1333. if ( creating ) {
  1334. vwf.createChild( nodeID, childName, nodeComponent.children[childName], undefined, function( childID ) /* async */ { // TODO: add in original order from nodeComponent.children // TODO: ensure id matches nodeComponent.children[childName].id // TODO: propagate childURI + fragment identifier to children of a URI component?
  1335. each_callback_async( undefined );
  1336. } );
  1337. } else {
  1338. vwf.setNode( nodeComponent.children[childName].id || nodeComponent.children[childName].patches,
  1339. nodeComponent.children[childName], function( childID ) /* async */ {
  1340. each_callback_async( undefined );
  1341. } );
  1342. } // TODO: delete when nodeComponent.children[childName] === null in patch
  1343. }, function( err ) /* async */ {
  1344. series_callback_async( err, undefined );
  1345. } );
  1346. },
  1347. function( series_callback_async /* ( err, results ) */ ) {
  1348. // Attach the scripts. For each script, load the network resource if the script
  1349. // is specified as a URI, then once loaded, call execute() to direct any model
  1350. // that manages scripts of this script's type to evaluate the script where it
  1351. // will perform any immediate actions and retain any callbacks as appropriate
  1352. // for the script type.
  1353. var scripts = nodeComponent.scripts ?
  1354. [].concat( nodeComponent.scripts ) : []; // accept either an array or a single item
  1355. var baseURI = vwf.uri( nodeID, true );
  1356. async.map( scripts, function( script, map_callback_async /* ( err, result ) */ ) {
  1357. if ( valueHasType( script ) ) {
  1358. if ( script.source ) {
  1359. loadScript( script.source, baseURI, function( scriptText ) /* async */ { // TODO: this load would be better left to the driver, which may want to ignore it in certain cases, but that would require a completion callback from kernel.execute()
  1360. map_callback_async( undefined, { text: scriptText, type: script.type } );
  1361. }, function( errorMessage ) {
  1362. map_callback_async( errorMessage, undefined );
  1363. } );
  1364. } else {
  1365. map_callback_async( undefined, { text: script.text, type: script.type } );
  1366. }
  1367. } else {
  1368. map_callback_async( undefined, { text: script, type: undefined } );
  1369. }
  1370. }, function( err, scripts ) /* async */ {
  1371. // Suppress kernel reentry so that initialization functions don't make any
  1372. // changes during replication.
  1373. vwf.models.kernel.disable();
  1374. // Create each script.
  1375. scripts.forEach( function( script ) {
  1376. vwf.execute( nodeID, script.text, script.type ); // TODO: callback
  1377. } );
  1378. // Restore kernel reentry.
  1379. vwf.models.kernel.enable();
  1380. series_callback_async( err, undefined );
  1381. } );
  1382. },
  1383. ], function( err, results ) /* async */ {
  1384. callback_async && callback_async( nodeID );
  1385. } );
  1386. this.logger.debugu();
  1387. return nodeComponent;
  1388. };
  1389. // -- getNode ------------------------------------------------------------------------------
  1390. /// @name module:vwf.getNode
  1391. ///
  1392. /// @see {@link module:vwf/api/kernel.getNode}
  1393. this.getNode = function( nodeID, full, normalize ) { // TODO: options to include/exclude children, prototypes
  1394. this.logger.debuggx( "getNode", nodeID, full );
  1395. var node = nodes.existing[nodeID];
  1396. // Start the descriptor.
  1397. var nodeComponent = {};
  1398. // Arrange the component as a patch if the node originated in a URI component. We want
  1399. // to refer to the original URI but apply any changes that have been made to the node
  1400. // since it was loaded.
  1401. var patches = this.models.object.patches( nodeID ),
  1402. patched = false;
  1403. if ( node.patchable ) {
  1404. nodeComponent.patches = node.uri || nodeID;
  1405. } else {
  1406. nodeComponent.id = nodeID;
  1407. }
  1408. // Intrinsic state. These don't change once created, so they can be omitted if we're
  1409. // patching.
  1410. if ( full || ! node.patchable ) {
  1411. var intrinsics = this.intrinsics( nodeID ); // source, type
  1412. var prototypeID = this.prototype( nodeID );
  1413. if ( prototypeID === undefined ) {
  1414. nodeComponent.extends = null;
  1415. } else if ( prototypeID !== this.kutility.protoNodeURI ) {
  1416. nodeComponent.extends = this.getNode( prototypeID ); // TODO: move to vwf/model/object and get from intrinsics
  1417. }
  1418. nodeComponent.implements = this.behaviors( nodeID ).map( function( behaviorID ) {
  1419. return this.getNode( behaviorID ); // TODO: move to vwf/model/object and get from intrinsics
  1420. }, this );
  1421. nodeComponent.implements.length || delete nodeComponent.implements;
  1422. if ( intrinsics.source !== undefined ) nodeComponent.source = intrinsics.source;
  1423. if ( intrinsics.type !== undefined ) nodeComponent.type = intrinsics.type;
  1424. }
  1425. // Internal state.
  1426. if ( full || ! node.patchable || patches.internals ) {
  1427. var internals = this.models.object.internals( nodeID ); // sequence and random
  1428. nodeComponent.sequence = internals.sequence;
  1429. nodeComponent.random = internals.random;
  1430. }
  1431. // Suppress kernel reentry so that we can read the state without coloring from any
  1432. // scripts.
  1433. vwf.models.kernel.disable();
  1434. // Properties.
  1435. if ( full || ! node.patchable ) {
  1436. // Want everything, or only want patches but the node is not patchable.
  1437. nodeComponent.properties = this.getProperties( nodeID );
  1438. for ( var propertyName in nodeComponent.properties ) {
  1439. var propertyValue = nodeComponent.properties[propertyName];
  1440. if ( propertyValue === undefined ) {
  1441. delete nodeComponent.properties[propertyName];
  1442. } else if ( this.kutility.valueIsNodeReference( propertyValue ) ) {
  1443. // Translate kernel node references into descriptor node references.
  1444. nodeComponent.properties[propertyName] = { node: propertyValue.id };
  1445. }
  1446. }
  1447. } else if ( node.properties.changes ) {
  1448. // The node is patchable and properties have changed.
  1449. nodeComponent.properties = {};
  1450. Object.keys( node.properties.changes ).forEach( function( propertyName ) {
  1451. if ( node.properties.changes[ propertyName ] !== "removed" ) { // TODO: handle delete
  1452. var propertyValue = this.getProperty( nodeID, propertyName );
  1453. if ( this.kutility.valueIsNodeReference( propertyValue ) ) {
  1454. // Translate kernel node references into descriptor node references.
  1455. nodeComponent.properties[propertyName] = { node: propertyValue.id };
  1456. } else {
  1457. nodeComponent.properties[propertyName] = propertyValue;
  1458. }
  1459. }
  1460. }, this );
  1461. }
  1462. if ( Object.keys( nodeComponent.properties ).length == 0 ) {
  1463. delete nodeComponent.properties;
  1464. } else {
  1465. patched = true;
  1466. }
  1467. // Methods.
  1468. if ( full || ! node.patchable ) {
  1469. Object.keys( node.methods.existing ).forEach( function( methodName ) {
  1470. nodeComponent.methods = nodeComponent.methods || {};
  1471. nodeComponent.methods[ methodName ] = this.getMethod( nodeID, methodName );
  1472. patched = true;
  1473. }, this );
  1474. } else if ( node.methods.changes ) {
  1475. Object.keys( node.methods.changes ).forEach( function( methodName ) {
  1476. if ( node.methods.changes[ methodName ] !== "removed" ) { // TODO: handle delete
  1477. nodeComponent.methods = nodeComponent.methods || {};
  1478. nodeComponent.methods[ methodName ] = this.getMethod( nodeID, methodName );
  1479. patched = true;
  1480. }
  1481. }, this );
  1482. }
  1483. // Events.
  1484. var events = full || ! node.patchable ?
  1485. node.events.existing : node.events.changes;
  1486. if ( events ) {
  1487. Object.keys( events ).forEach( function( eventName ) {
  1488. nodeComponent.events = nodeComponent.events || {};
  1489. nodeComponent.events[ eventName ] = this.getEvent( nodeID, eventName );
  1490. patched = true;
  1491. }, this );
  1492. }
  1493. // Restore kernel reentry.
  1494. vwf.models.kernel.enable();
  1495. // Children.
  1496. nodeComponent.children = {};
  1497. this.children( nodeID ).forEach( function( childID ) {
  1498. nodeComponent.children[ this.name( childID ) ] = this.getNode( childID, full );
  1499. }, this );
  1500. for ( var childName in nodeComponent.children ) { // TODO: distinguish add, change, remove
  1501. if ( nodeComponent.children[childName] === undefined ) {
  1502. delete nodeComponent.children[childName];
  1503. }
  1504. }
  1505. if ( Object.keys( nodeComponent.children ).length == 0 ) {
  1506. delete nodeComponent.children;
  1507. } else {
  1508. patched = true;
  1509. }
  1510. // Scripts.
  1511. // TODO: scripts
  1512. // Normalize for consistency.
  1513. if ( normalize ) {
  1514. nodeComponent = require( "vwf/utility" ).transform(
  1515. nodeComponent, require( "vwf/utility" ).transforms.hash );
  1516. }
  1517. this.logger.debugu();
  1518. // Return the descriptor created, unless it was arranged as a patch and there were no
  1519. // changes. Otherwise, return the URI if this is the root of a URI component.
  1520. if ( full || ! node.patchable || patched ) {
  1521. return nodeComponent;
  1522. } else if ( node.uri ) {
  1523. return node.uri;
  1524. } else {
  1525. return undefined;
  1526. }
  1527. };
  1528. // -- hashNode -----------------------------------------------------------------------------
  1529. /// @name module:vwf.hashNode
  1530. ///
  1531. /// @see {@link module:vwf/api/kernel.hashNode}
  1532. this.hashNode = function( nodeID ) { // TODO: works with patches? // TODO: only for nodes from getNode( , , true )
  1533. this.logger.debuggx( "hashNode", typeof nodeID == "object" ? nodeID.id : nodeID );
  1534. var nodeComponent = typeof nodeID == "object" ? nodeID : this.getNode( nodeID, true, true );
  1535. // Hash the intrinsic state.
  1536. var internal = { id: nodeComponent.id, source: nodeComponent.source, type: nodeComponent.type }; // TODO: get subset same way as getNode() puts them in without calling out specific field names
  1537. internal.source === undefined && delete internal.source;
  1538. internal.type === undefined && delete internal.type;
  1539. var hashi = "i" + Crypto.MD5( JSON.stringify( internal ) ).toString().substring( 0, 16 );
  1540. // Hash the properties.
  1541. var properties = nodeComponent.properties || {};
  1542. var hashp = Object.keys( properties ).length ?
  1543. "p" + Crypto.MD5( JSON.stringify( properties ) ).toString().substring( 0, 16 ) : undefined;
  1544. // Hash the children.
  1545. var children = nodeComponent.children || {};
  1546. var hashc = Object.keys( children ).length ?
  1547. "c" + Crypto.MD5( JSON.stringify( children ) ).toString().substring( 0, 16 ) : undefined;
  1548. this.logger.debugu();
  1549. // Generate the combined hash.
  1550. return hashi + ( hashp ? "." + hashp : "" ) + ( hashc ? "/" + hashc : "" );
  1551. };
  1552. // -- createChild --------------------------------------------------------------------------
  1553. /// When we arrive here, we have a prototype node in hand (by way of its ID) and an object
  1554. /// containing a component specification. We now need to create and assemble the new node.
  1555. ///
  1556. /// The VWF manager doesn't directly manipulate any node. The various models act in
  1557. /// federation to create the greater model. The manager simply routes messages within the
  1558. /// system to allow the models to maintain the necessary data. Additionally, the views
  1559. /// receive similar messages that allow them to keep their interfaces current.
  1560. ///
  1561. /// To create a node, we simply assign a new ID, then invoke a notification on each model and
  1562. /// a notification on each view.
  1563. ///
  1564. /// createChild may complete asynchronously due to its dependence on createNode and the
  1565. /// creatingNode and createdNode driver calls. To prevent actions from executing out of
  1566. /// order, queue processing must be suspended while createChild is in progress. createNode
  1567. /// and the driver callbacks suspend the queue when necessary, but additional calls to
  1568. /// suspend and resume the queue may be needed if other async operations are added.
  1569. ///
  1570. /// @name module:vwf.createChild
  1571. ///
  1572. /// @see {@link module:vwf/api/kernel.createChild}
  1573. this.createChild = function( nodeID, childName, childComponent, childURI, callback_async /* ( childID ) */ ) {
  1574. this.logger.debuggx( "createChild", function() {
  1575. return [ nodeID, childName, JSON.stringify( loggableComponent( childComponent ) ), childURI ];
  1576. } );
  1577. childComponent = normalizedComponent( childComponent );
  1578. var child, childID, childIndex, childPrototypeID, childBehaviorIDs = [], deferredInitializations = {};
  1579. var resolvedSource; // resolved `childComponent.source` for the drivers.
  1580. // Determine if we're replicating previously-saved state, or creating a fresh object.
  1581. var replicating = !! childComponent.id;
  1582. // Allocate an ID for the node. IDs must be unique and consistent across all clients
  1583. // sharing the same instance regardless of the component load order. Each node maintains
  1584. // a sequence counter, and we allocate the ID based on the parent's sequence counter and
  1585. // ID. Top-level nodes take the ID from their origin URI when available or from a hash
  1586. // of the descriptor. An existing ID is used when synchronizing to state drawn from
  1587. // another client or to a previously-saved state.
  1588. if ( childComponent.id ) { // incoming replication: pre-calculated id
  1589. childID = childComponent.id;
  1590. childIndex = this.children( nodeID ).length;
  1591. } else if ( nodeID === 0 ) { // global: component's URI or hash of its descriptor
  1592. childID = childURI ||
  1593. Crypto.MD5( JSON.stringify( childComponent ) ).toString(); // TODO: MD5 may be too slow here
  1594. childIndex = childURI;
  1595. } else { // descendant: parent id + next from parent's sequence
  1596. childID = nodeID + ":" + this.sequence( nodeID ) +
  1597. ( this.configuration["randomize-ids"] ? "-" + ( "0" + Math.floor( this.random( nodeID ) * 100 ) ).slice( -2 ) : "" ) +
  1598. ( this.configuration["humanize-ids"] ? "-" + childName.replace( /[^0-9A-Za-z_-]+/g, "-" ) : "" );
  1599. childIndex = this.children( nodeID ).length;
  1600. }
  1601. // Register the node.
  1602. child = nodes.create( childID, childPrototypeID, childBehaviorIDs, childURI, childName, nodeID );
  1603. // Register the node in vwf/model/object. Since the kernel delegates many node
  1604. // information functions to vwf/model/object, this serves to register it with the
  1605. // kernel. The node must be registered before any async operations occur to ensure that
  1606. // the parent's child list is correct when following siblings calculate their index
  1607. // numbers.
  1608. vwf.models.object.creatingNode( nodeID, childID, childPrototypeID, childBehaviorIDs,
  1609. childComponent.source, childComponent.type, childIndex, childName ); // TODO: move node metadata back to the kernel and only use vwf/model/object just as a property store?
  1610. // The base URI for relative references is the URI of this node or the closest ancestor.
  1611. var baseURI = vwf.uri( childID, true );
  1612. // Construct the node.
  1613. async.series( [
  1614. function( series_callback_async /* ( err, results ) */ ) {
  1615. // Rudimentary support for `{ includes: prototype }`, which absorbs a prototype
  1616. // descriptor into the child descriptor before creating the child. See the notes
  1617. // in `createNode` and the `mergeDescriptors` limitations.
  1618. // This first task always completes asynchronously (even if it doesn't perform
  1619. // an async operation) so that the stack doesn't grow from node to node while
  1620. // createChild() recursively traverses a component. If this task is moved,
  1621. // replace it with an async stub, or make the next task exclusively async.
  1622. if ( componentIsDescriptor( childComponent ) && childComponent.includes && componentIsURI( childComponent.includes ) ) { // TODO: for "includes:", accept an already-loaded component (which componentIsURI exludes) since the descriptor will be loaded again
  1623. var prototypeURI = require( "vwf/utility" ).resolveURI( childComponent.includes, baseURI );
  1624. var sync = true; // will loadComponent() complete synchronously?
  1625. loadComponent( prototypeURI, undefined, function( prototypeDescriptor ) /* async */ {
  1626. // Resolve relative references with respect to the included component.
  1627. prototypeDescriptor = resolvedDescriptor( prototypeDescriptor, prototypeURI );
  1628. // Merge the child descriptor onto the `includes` descriptor.
  1629. childComponent = mergeDescriptors( childComponent, prototypeDescriptor ); // modifies prototypeDescriptor
  1630. if ( sync ) {
  1631. queue.suspend( "before beginning " + childID ); // suspend the queue
  1632. async.nextTick( function() {
  1633. series_callback_async( undefined, undefined );
  1634. queue.resume( "after beginning " + childID ); // resume the queue; may invoke dispatch(), so call last before returning to the host
  1635. } );
  1636. } else {
  1637. series_callback_async( undefined, undefined );
  1638. }
  1639. }, function( errorMessage ) {
  1640. childComponent = undefined;
  1641. series_callback_async( errorMessage, undefined );
  1642. } );
  1643. sync = false; // not if we got here first
  1644. } else {
  1645. queue.suspend( "before beginning " + childID ); // suspend the queue
  1646. async.nextTick( function() {
  1647. series_callback_async( undefined, undefined );
  1648. queue.resume( "after beginning " + childID ); // resume the queue; may invoke dispatch(), so call last before returning to the host
  1649. } );
  1650. }
  1651. },
  1652. function( series_callback_async /* ( err, results ) */ ) {
  1653. // Create the prototype and behavior nodes (or locate previously created
  1654. // instances).
  1655. async.parallel( [
  1656. function( parallel_callback_async /* ( err, results ) */ ) {
  1657. // Create or find the prototype and save the ID in childPrototypeID.
  1658. if ( childComponent.extends !== null ) { // TODO: any way to prevent node loading node as a prototype without having an explicit null prototype attribute in node?
  1659. var prototypeComponent = childComponent.extends || vwf.kutility.protoNodeURI;
  1660. vwf.createNode( prototypeComponent, undefined, baseURI, function( prototypeID ) /* async */ {
  1661. childPrototypeID = prototypeID;
  1662. // TODO: the GLGE driver doesn't handle source/type or properties in prototypes properly; as a work-around pull those up into the component when not already defined
  1663. if ( ! childComponent.source ) {
  1664. var prototype_intrinsics = vwf.intrinsics( prototypeID );
  1665. if ( prototype_intrinsics.source ) {
  1666. var prototype_uri = vwf.uri( prototypeID );
  1667. var prototype_properties = vwf.getProperties( prototypeID );
  1668. childComponent.source = require( "vwf/utility" ).resolveURI( prototype_intrinsics.source, prototype_uri );
  1669. childComponent.type = prototype_intrinsics.type;
  1670. childComponent.properties = childComponent.properties || {};
  1671. Object.keys( prototype_properties ).forEach( function( prototype_property_name ) {
  1672. if ( childComponent.properties[prototype_property_name] === undefined && prototype_property_name != "transform" ) {
  1673. childComponent.properties[prototype_property_name] = prototype_properties[prototype_property_name];
  1674. }
  1675. } );
  1676. }
  1677. }
  1678. parallel_callback_async( undefined, undefined );
  1679. } );
  1680. } else {
  1681. childPrototypeID = undefined;
  1682. parallel_callback_async( undefined, undefined );
  1683. }
  1684. },
  1685. function( parallel_callback_async /* ( err, results ) */ ) {
  1686. // Create or find the behaviors and save the IDs in childBehaviorIDs.
  1687. var behaviorComponents = childComponent.implements ?
  1688. [].concat( childComponent.implements ) : []; // accept either an array or a single item
  1689. async.map( behaviorComponents, function( behaviorComponent, map_callback_async /* ( err, result ) */ ) {
  1690. vwf.createNode( behaviorComponent, undefined, baseURI, function( behaviorID ) /* async */ {
  1691. map_callback_async( undefined, behaviorID );
  1692. } );
  1693. }, function( err, behaviorIDs ) /* async */ {
  1694. childBehaviorIDs = behaviorIDs;
  1695. parallel_callback_async( err, undefined );
  1696. } );
  1697. },
  1698. ], function( err, results ) /* async */ {
  1699. series_callback_async( err, undefined );
  1700. } );
  1701. },
  1702. function( series_callback_async /* ( err, results ) */ ) {
  1703. // Re-register the node now that we have the prototypes and behaviors.
  1704. child = nodes.create( childID, childPrototypeID, childBehaviorIDs, childURI, childName, nodeID );
  1705. // For the proto-prototype node `node.vwf`, register the meta events.
  1706. if ( childID === vwf.kutility.protoNodeURI ) {
  1707. child.events.create( namespaceEncodedName( [ "properties", "created" ] ) );
  1708. child.events.create( namespaceEncodedName( [ "properties", "initialized" ] ) );
  1709. child.events.create( namespaceEncodedName( [ "properties", "deleted" ] ) );
  1710. child.events.create( namespaceEncodedName( [ "methods", "created" ] ) );
  1711. child.events.create( namespaceEncodedName( [ "methods", "deleted" ] ) );
  1712. child.events.create( namespaceEncodedName( [ "events", "created" ] ) );
  1713. child.events.create( namespaceEncodedName( [ "events", "deleted" ] ) );
  1714. child.events.create( namespaceEncodedName( [ "children", "added" ] ) );
  1715. child.events.create( namespaceEncodedName( [ "children", "removed" ] ) );
  1716. }
  1717. // Re-register the node in vwf/model/object now that we have the prototypes and
  1718. // behaviors. vwf/model/object knows that we call it more than once and only
  1719. // updates the new information.
  1720. vwf.models.object.creatingNode( nodeID, childID, childPrototypeID, childBehaviorIDs,
  1721. childComponent.source, childComponent.type, childIndex, childName ); // TODO: move node metadata back to the kernel and only use vwf/model/object just as a property store?
  1722. // Resolve the asset source URL for the drivers.
  1723. resolvedSource = childComponent.source &&
  1724. require( "vwf/utility" ).resolveURI( childComponent.source, baseURI );
  1725. // Call creatingNode() on each model. The node is considered to be constructed
  1726. // after all models have run.
  1727. async.forEachSeries( vwf.models, function( model, each_callback_async /* ( err ) */ ) {
  1728. var driver_ready = true;
  1729. var timeoutID;
  1730. // TODO: suppress kernel reentry here (just for childID?) with kernel/model showing a warning when breached; no actions are allowed until all drivers have seen creatingNode()
  1731. model.creatingNode && model.creatingNode( nodeID, childID, childPrototypeID, childBehaviorIDs,
  1732. resolvedSource, childComponent.type, childIndex, childName, function( ready ) /* async */ {
  1733. if ( driver_ready && ! ready ) {
  1734. suspend();
  1735. } else if ( ! driver_ready && ready ) {
  1736. resume();
  1737. }
  1738. function suspend() {
  1739. queue.suspend( "while loading " + childComponent.source + " for " + childID + " in creatingNode" ); // suspend the queue
  1740. timeoutID = window.setTimeout( function() { resume( "timeout loading " + childComponent.source ) }, vwf.configuration[ "load-timeout" ] * 1000 );
  1741. driver_ready = false;
  1742. }
  1743. function resume( err ) {
  1744. window.clearTimeout( timeoutID );
  1745. driver_ready = true;
  1746. err && vwf.logger.warnx( "createChild", nodeID, childName + ":", err );
  1747. each_callback_async( err ); // resume createChild()
  1748. queue.resume( "after loading " + childComponent.source + " for " + childID + " in creatingNode" ); // resume the queue; may invoke dispatch(), so call last before returning to the host
  1749. }
  1750. } );
  1751. // TODO: restore kernel reentry here
  1752. driver_ready && each_callback_async( undefined );
  1753. }, function( err ) /* async */ {
  1754. series_callback_async( err, undefined );
  1755. } );
  1756. },
  1757. function( series_callback_async /* ( err, results ) */ ) {
  1758. // Call createdNode() on each view. The view is being notified of a node that has
  1759. // been constructed.
  1760. async.forEach( vwf.views, function( view, each_callback_async /* ( err ) */ ) {
  1761. var driver_ready = true;
  1762. var timeoutID;
  1763. view.createdNode && view.createdNode( nodeID, childID, childPrototypeID, childBehaviorIDs,
  1764. resolvedSource, childComponent.type, childIndex, childName, function( ready ) /* async */ {
  1765. if ( driver_ready && ! ready ) {
  1766. suspend();
  1767. } else if ( ! driver_ready && ready ) {
  1768. resume();
  1769. }
  1770. function suspend() {
  1771. queue.suspend( "while loading " + childComponent.source + " for " + childID + " in createdNode" ); // suspend the queue
  1772. timeoutID = window.setTimeout( function() { resume( "timeout loading " + childComponent.source ) }, vwf.configuration[ "load-timeout" ] * 1000 );
  1773. driver_ready = false;
  1774. }
  1775. function resume( err ) {
  1776. window.clearTimeout( timeoutID );
  1777. driver_ready = true;
  1778. err && vwf.logger.warnx( "createChild", nodeID, childName + ":", err );
  1779. each_callback_async( err ); // resume createChild()
  1780. queue.resume( "after loading " + childComponent.source + " for " + childID + " in createdNode" ); // resume the queue; may invoke dispatch(), so call last before returning to the host
  1781. }
  1782. } );
  1783. driver_ready && each_callback_async( undefined );
  1784. }, function( err ) /* async */ {
  1785. series_callback_async( err, undefined );
  1786. } );
  1787. },
  1788. function( series_callback_async /* ( err, results ) */ ) {
  1789. // Set the internal state.
  1790. vwf.models.object.internals( childID, childComponent );
  1791. // Suppress kernel reentry so that we can read the state without coloring from
  1792. // any scripts.
  1793. replicating && vwf.models.kernel.disable();
  1794. // Create the properties, methods, and events. For each item in each set, invoke
  1795. // createProperty(), createMethod(), or createEvent() to create the field. Each
  1796. // delegates to the models and views as above.
  1797. childComponent.properties && Object.keys( childComponent.properties ).forEach( function( propertyName ) {
  1798. var propertyValue = childComponent.properties[ propertyName ];
  1799. var value = propertyValue, get, set, create;
  1800. if ( valueHasAccessors( propertyValue ) ) {
  1801. value = propertyValue.node ? vwf.kutility.nodeReference( propertyValue.node ) : propertyValue.value;
  1802. get = propertyValue.get;
  1803. set = propertyValue.set;
  1804. create = propertyValue.create;
  1805. }
  1806. // Is the property specification directing us to create a new property, or
  1807. // initialize a property already defined on a prototype?
  1808. // Create a new property if an explicit getter or setter are provided or if
  1809. // the property is not defined on a prototype. Initialize the property when
  1810. // the property is already defined on a prototype and no explicit getter or
  1811. // setter are provided.
  1812. var creating = create || // explicit create directive, or
  1813. get !== undefined || set !== undefined || // explicit accessor, or
  1814. ! child.properties.has( propertyName ); // not defined on prototype
  1815. // Are we assigning the value here, or deferring assignment until the node
  1816. // is constructed because setters will run?
  1817. var assigning = value === undefined || // no value, or
  1818. set === undefined && ( creating || ! nodePropertyHasSetter.call( vwf, childID, propertyName ) ) || // no setter, or
  1819. replicating; // replicating previously-saved state (setters never run during replication)
  1820. if ( ! assigning ) {
  1821. deferredInitializations[propertyName] = value;
  1822. value = undefined;
  1823. }
  1824. // Create or initialize the property.
  1825. if ( creating ) {
  1826. vwf.createProperty( childID, propertyName, value, get, set );
  1827. } else {
  1828. vwf.setProperty( childID, propertyName, value );
  1829. }
  1830. } );
  1831. childComponent.methods && Object.keys( childComponent.methods ).forEach( function( methodName ) {
  1832. var methodValue = childComponent.methods[ methodName ];
  1833. if ( valueHasBody( methodValue ) ) {
  1834. vwf.createMethod( childID, methodName, methodValue.parameters, methodValue.body );
  1835. } else {
  1836. vwf.createMethod( childID, methodName, undefined, methodValue );
  1837. }
  1838. } );
  1839. childComponent.events && Object.keys( childComponent.events ).forEach( function( eventName ) {
  1840. var eventValue = childComponent.events[ eventName ];
  1841. if ( valueHasBody( eventValue ) ) {
  1842. vwf.createEvent( childID, eventName, eventValue.parameters );
  1843. vwf.setEvent( childID, eventName, eventValue ); // set the listeners since `createEvent` can't do it yet
  1844. } else {
  1845. vwf.createEvent( childID, eventName, undefined );
  1846. }
  1847. } );
  1848. // Restore kernel reentry.
  1849. replicating && vwf.models.kernel.enable();
  1850. // Create and attach the children. For each child, call createChild() with the
  1851. // child's component specification. createChild() delegates to the models and
  1852. // views as before.
  1853. async.forEach( Object.keys( childComponent.children || {} ), function( childName, each_callback_async /* ( err ) */ ) {
  1854. var childValue = childComponent.children[childName];
  1855. vwf.createChild( childID, childName, childValue, undefined, function( childID ) /* async */ { // TODO: add in original order from childComponent.children // TODO: propagate childURI + fragment identifier to children of a URI component?
  1856. each_callback_async( undefined );
  1857. } );
  1858. }, function( err ) /* async */ {
  1859. series_callback_async( err, undefined );
  1860. } );
  1861. },
  1862. function( series_callback_async /* ( err, results ) */ ) {
  1863. // Attach the scripts. For each script, load the network resource if the script is
  1864. // specified as a URI, then once loaded, call execute() to direct any model that
  1865. // manages scripts of this script's type to evaluate the script where it will
  1866. // perform any immediate actions and retain any callbacks as appropriate for the
  1867. // script type.
  1868. var scripts = childComponent.scripts ?
  1869. [].concat( childComponent.scripts ) : []; // accept either an array or a single item
  1870. async.map( scripts, function( script, map_callback_async /* ( err, result ) */ ) {
  1871. if ( valueHasType( script ) ) {
  1872. if ( script.source ) {
  1873. loadScript( script.source, baseURI, function( scriptText ) /* async */ { // TODO: this load would be better left to the driver, which may want to ignore it in certain cases, but that would require a completion callback from kernel.execute()
  1874. map_callback_async( undefined, { text: scriptText, type: script.type } );
  1875. }, function( errorMessage ) {
  1876. map_callback_async( errorMessage, undefined );
  1877. } );
  1878. } else {
  1879. map_callback_async( undefined, { text: script.text, type: script.type } );
  1880. }
  1881. } else {
  1882. map_callback_async( undefined, { text: script, type: undefined } );
  1883. }
  1884. }, function( err, scripts ) /* async */ {
  1885. // Watch for any async kernel calls generated as we run the scripts and wait
  1886. // for them complete before completing the node.
  1887. vwf.models.kernel.capturingAsyncs( function() {
  1888. // Suppress kernel reentry so that initialization functions don't make
  1889. // any changes during replication.
  1890. replicating && vwf.models.kernel.disable();
  1891. // Create each script.
  1892. scripts.forEach( function( script ) {
  1893. vwf.execute( childID, script.text, script.type ); // TODO: callback
  1894. } );
  1895. // Perform initializations for properties with setter functions. These
  1896. // are assigned here so that the setters run on a fully-constructed node.
  1897. Object.keys( deferredInitializations ).forEach( function( propertyName ) {
  1898. vwf.setProperty( childID, propertyName, deferredInitializations[propertyName] );
  1899. } );
  1900. // TODO: Adding the node to the tickable list here if it contains a tick() function in JavaScript at initialization time. Replace with better control of ticks on/off and the interval by the node.
  1901. if ( vwf.execute( childID, "Boolean( this.tick )" ) ) {
  1902. vwf.tickable.nodeIDs.push( childID );
  1903. }
  1904. // Restore kernel reentry.
  1905. replicating && vwf.models.kernel.enable();
  1906. }, function() {
  1907. // This function is called when all asynchronous calls from the previous
  1908. // function have returned.
  1909. // Call initializingNode() on each model and initializedNode() on each
  1910. // view to indicate that the node is fully constructed.
  1911. // Since nodes don't (currently) inherit their prototypes' children,
  1912. // for each prototype also call initializingNodeFromPrototype() to allow
  1913. // model drivers to apply the prototypes' initializers to the node.
  1914. async.forEachSeries( vwf.prototypes( childID, true ).reverse().concat( childID ),
  1915. function( childInitializingNodeID, each_callback_async /* err */ ) {
  1916. // Call initializingNode() on each model.
  1917. vwf.models.kernel.capturingAsyncs( function() {
  1918. vwf.models.forEach( function( model ) {
  1919. // Suppress kernel reentry so that initialization functions
  1920. // don't make any changes during replication.
  1921. replicating && vwf.models.kernel.disable();
  1922. // For a prototype, call `initializingNodeFromPrototype` to
  1923. // run the prototype's initializer on the node. For the
  1924. // node, call `initializingNode` to run its own initializer.
  1925. //
  1926. // `initializingNodeFromPrototype` is separate from
  1927. // `initializingNode` so that `initializingNode` remains a
  1928. // single call that indicates that the node is fully
  1929. // constructed. Existing drivers, and any drivers that don't
  1930. // care about prototype initializers will by default ignore
  1931. // the intermediate initializations.
  1932. // (`initializingNodeFromPrototype` was added in 0.6.23.)
  1933. if ( childInitializingNodeID !== childID ) {
  1934. model.initializingNodeFromPrototype &&
  1935. model.initializingNodeFromPrototype( nodeID, childID, childInitializingNodeID );
  1936. } else {
  1937. model.initializingNode &&
  1938. model.initializingNode( nodeID, childID, childPrototypeID, childBehaviorIDs,
  1939. resolvedSource, childComponent.type, childIndex, childName );
  1940. }
  1941. // Restore kernel reentry.
  1942. replicating && vwf.models.kernel.enable();
  1943. } );
  1944. }, function() {
  1945. each_callback_async( undefined );
  1946. } );
  1947. }, function( err ) /* async */ {
  1948. // Call initializedNode() on each view.
  1949. vwf.views.forEach( function( view ) {
  1950. view.initializedNode && view.initializedNode( nodeID, childID, childPrototypeID, childBehaviorIDs,
  1951. resolvedSource, childComponent.type, childIndex, childName );
  1952. } );
  1953. // Mark the node as initialized.
  1954. nodes.initialize( childID );
  1955. // Send the meta event into the application.
  1956. if ( ! replicating && nodeID !== 0 ) {
  1957. vwf.fireEvent( nodeID, [ "children", "added" ],
  1958. [ childIndex, vwf.kutility.nodeReference( childID ) ] );
  1959. }
  1960. // Dismiss the loading spinner
  1961. if ( childID === vwf.application() ) {
  1962. var spinner = document.getElementById( "vwf-loading-spinner" );
  1963. spinner && spinner.classList.remove( "pace-active" );
  1964. }
  1965. series_callback_async( err, undefined );
  1966. } );
  1967. } );
  1968. } );
  1969. },
  1970. ], function( err, results ) /* async */ {
  1971. // The node is complete. Invoke the callback method and pass the new node ID and the
  1972. // ID of its prototype. If this was the root node for the application, the
  1973. // application is now fully initialized.
  1974. // Always complete asynchronously so that the stack doesn't grow from node to node
  1975. // while createChild() recursively traverses a component.
  1976. if ( callback_async ) {
  1977. queue.suspend( "before completing " + childID ); // suspend the queue
  1978. async.nextTick( function() {
  1979. callback_async( childID );
  1980. queue.resume( "after completing " + childID ); // resume the queue; may invoke dispatch(), so call last before returning to the host
  1981. } );
  1982. }
  1983. } );
  1984. this.logger.debugu();
  1985. };
  1986. // -- deleteChild --------------------------------------------------------------------------
  1987. /// @name module:vwf.deleteChild
  1988. ///
  1989. /// @see {@link module:vwf/api/kernel.deleteChild}
  1990. this.deleteChild = function( nodeID, childName ) {
  1991. var childID = this.children( nodeID ).filter( function( childID ) {
  1992. return this.name( childID ) === childName;
  1993. }, this )[0];
  1994. if ( childID !== undefined ) {
  1995. return this.deleteNode( childID );
  1996. }
  1997. }
  1998. // -- addChild -----------------------------------------------------------------------------
  1999. /// @name module:vwf.addChild
  2000. ///
  2001. /// @see {@link module:vwf/api/kernel.addChild}
  2002. this.addChild = function( nodeID, childID, childName ) {
  2003. this.logger.debuggx( "addChild", nodeID, childID, childName );
  2004. // Call addingChild() on each model. The child is considered added after all models have
  2005. // run.
  2006. this.models.forEach( function( model ) {
  2007. model.addingChild && model.addingChild( nodeID, childID, childName );
  2008. } );
  2009. // Call addedChild() on each view. The view is being notified that a child has been
  2010. // added.
  2011. this.views.forEach( function( view ) {
  2012. view.addedChild && view.addedChild( nodeID, childID, childName );
  2013. } );
  2014. this.logger.debugu();
  2015. };
  2016. // -- removeChild --------------------------------------------------------------------------
  2017. /// @name module:vwf.removeChild
  2018. ///
  2019. /// @see {@link module:vwf/api/kernel.removeChild}
  2020. this.removeChild = function( nodeID, childID ) {
  2021. this.logger.debuggx( "removeChild", nodeID, childID );
  2022. // Call removingChild() on each model. The child is considered removed after all models
  2023. // have run.
  2024. this.models.forEach( function( model ) {
  2025. model.removingChild && model.removingChild( nodeID, childID );
  2026. } );
  2027. // Call removedChild() on each view. The view is being notified that a child has been
  2028. // removed.
  2029. this.views.forEach( function( view ) {
  2030. view.removedChild && view.removedChild( nodeID, childID );
  2031. } );
  2032. this.logger.debugu();
  2033. };
  2034. // -- setProperties ------------------------------------------------------------------------
  2035. /// Set all of the properties for a node.
  2036. ///
  2037. /// @name module:vwf.setProperties
  2038. ///
  2039. /// @see {@link module:vwf/api/kernel.setProperties}
  2040. this.setProperties = function( nodeID, properties ) { // TODO: rework as a cover for setProperty(), or remove; passing all properties to each driver is impractical since initializing and setting are different, and reentry can't be controlled when multiple sets are in progress.
  2041. this.logger.debuggx( "setProperties", nodeID, properties );
  2042. var node = nodes.existing[nodeID];
  2043. var entrants = this.setProperty.entrants;
  2044. // Call settingProperties() on each model.
  2045. properties = this.models.reduceRight( function( intermediate_properties, model, index ) { // TODO: note that we can't go left to right and stop after the first that accepts the set since we are setting all of the properties as a batch; verify that this creates the same result as calling setProperty individually on each property and that there are no side effects from setting through a driver after the one that handles the set.
  2046. var model_properties = {};
  2047. if ( model.settingProperties ) {
  2048. model_properties = model.settingProperties( nodeID, properties );
  2049. } else if ( model.settingProperty ) {
  2050. Object.keys( node.properties.existing ).forEach( function( propertyName ) {
  2051. if ( properties[propertyName] !== undefined ) {
  2052. var reentry = entrants[nodeID+'-'+propertyName] = { index: index }; // the active model number from this call // TODO: need unique nodeID+propertyName hash
  2053. model_properties[propertyName] =
  2054. model.settingProperty( nodeID, propertyName, properties[propertyName] );
  2055. if ( vwf.models.kernel.blocked() ) {
  2056. model_properties[propertyName] = undefined; // ignore result from a blocked setter
  2057. }
  2058. delete entrants[nodeID+'-'+propertyName];
  2059. }
  2060. } );
  2061. }
  2062. Object.keys( node.properties.existing ).forEach( function( propertyName ) {
  2063. if ( model_properties[propertyName] !== undefined ) { // copy values from this model
  2064. intermediate_properties[propertyName] = model_properties[propertyName];
  2065. } else if ( intermediate_properties[propertyName] === undefined ) { // as well as recording any new keys
  2066. intermediate_properties[propertyName] = undefined;
  2067. }
  2068. } );
  2069. return intermediate_properties;
  2070. }, {} );
  2071. // Record the change.
  2072. if ( node.initialized && node.patchable ) {
  2073. Object.keys( properties ).forEach( function( propertyName ) {
  2074. node.properties.change( propertyName );
  2075. } );
  2076. }
  2077. // Call satProperties() on each view.
  2078. this.views.forEach( function( view ) {
  2079. if ( view.satProperties ) {
  2080. view.satProperties( nodeID, properties );
  2081. } else if ( view.satProperty ) {
  2082. for ( var propertyName in properties ) {
  2083. view.satProperty( nodeID, propertyName, properties[propertyName] ); // TODO: be sure this is the value actually set, not the incoming value
  2084. }
  2085. }
  2086. } );
  2087. this.logger.debugu();
  2088. return properties;
  2089. };
  2090. // -- getProperties ------------------------------------------------------------------------
  2091. /// Get all of the properties for a node.
  2092. ///
  2093. /// @name module:vwf.getProperties
  2094. ///
  2095. /// @see {@link module:vwf/api/kernel.getProperties}
  2096. this.getProperties = function( nodeID ) { // TODO: rework as a cover for getProperty(), or remove; passing all properties to each driver is impractical since reentry can't be controlled when multiple gets are in progress.
  2097. this.logger.debuggx( "getProperties", nodeID );
  2098. var node = nodes.existing[nodeID];
  2099. var entrants = this.getProperty.entrants;
  2100. // Call gettingProperties() on each model.
  2101. var properties = this.models.reduceRight( function( intermediate_properties, model, index ) { // TODO: note that we can't go left to right and take the first result since we are getting all of the properties as a batch; verify that this creates the same result as calling getProperty individually on each property and that there are no side effects from getting through a driver after the one that handles the get.
  2102. var model_properties = {};
  2103. if ( model.gettingProperties ) {
  2104. model_properties = model.gettingProperties( nodeID, properties );
  2105. } else if ( model.gettingProperty ) {
  2106. Object.keys( node.properties.existing ).forEach( function( propertyName ) {
  2107. var reentry = entrants[nodeID+'-'+propertyName] = { index: index }; // the active model number from this call // TODO: need unique nodeID+propertyName hash
  2108. model_properties[propertyName] =
  2109. model.gettingProperty( nodeID, propertyName, intermediate_properties[propertyName] );
  2110. if ( vwf.models.kernel.blocked() ) {
  2111. model_properties[propertyName] = undefined; // ignore result from a blocked getter
  2112. }
  2113. delete entrants[nodeID+'-'+propertyName];
  2114. } );
  2115. }
  2116. Object.keys( node.properties.existing ).forEach( function( propertyName ) {
  2117. if ( model_properties[propertyName] !== undefined ) { // copy values from this model
  2118. intermediate_properties[propertyName] = model_properties[propertyName];
  2119. } else if ( intermediate_properties[propertyName] === undefined ) { // as well as recording any new keys
  2120. intermediate_properties[propertyName] = undefined;
  2121. }
  2122. } );
  2123. return intermediate_properties;
  2124. }, {} );
  2125. // Call gotProperties() on each view.
  2126. this.views.forEach( function( view ) {
  2127. if ( view.gotProperties ) {
  2128. view.gotProperties( nodeID, properties );
  2129. } else if ( view.gotProperty ) {
  2130. for ( var propertyName in properties ) {
  2131. view.gotProperty( nodeID, propertyName, properties[propertyName] ); // TODO: be sure this is the value actually gotten and not an intermediate value from above
  2132. }
  2133. }
  2134. } );
  2135. this.logger.debugu();
  2136. return properties;
  2137. };
  2138. // -- createProperty -----------------------------------------------------------------------
  2139. /// Create a property on a node and assign an initial value.
  2140. ///
  2141. /// @name module:vwf.createProperty
  2142. ///
  2143. /// @see {@link module:vwf/api/kernel.createProperty}
  2144. this.createProperty = function( nodeID, propertyName, propertyValue, propertyGet, propertySet ) {
  2145. this.logger.debuggx( "createProperty", function() {
  2146. return [ nodeID, propertyName, JSON.stringify( loggableValue( propertyValue ) ),
  2147. loggableScript( propertyGet ), loggableScript( propertySet ) ];
  2148. } );
  2149. var node = nodes.existing[nodeID];
  2150. // Register the property.
  2151. node.properties.create( propertyName, node.initialized && node.patchable );
  2152. // Call creatingProperty() on each model. The property is considered created after all
  2153. // models have run.
  2154. this.models.forEach( function( model ) {
  2155. model.creatingProperty && model.creatingProperty( nodeID, propertyName, propertyValue,
  2156. propertyGet, propertySet );
  2157. } );
  2158. // Call createdProperty() on each view. The view is being notified that a property has
  2159. // been created.
  2160. this.views.forEach( function( view ) {
  2161. view.createdProperty && view.createdProperty( nodeID, propertyName, propertyValue,
  2162. propertyGet, propertySet );
  2163. } );
  2164. // Send the meta event into the application.
  2165. if ( this.models.kernel.enabled() ) {
  2166. this.fireEvent( nodeID, [ "properties", "created" ], [ propertyName ] );
  2167. }
  2168. this.logger.debugu();
  2169. return propertyValue;
  2170. };
  2171. // -- setProperty --------------------------------------------------------------------------
  2172. /// Set a property value on a node.
  2173. ///
  2174. /// @name module:vwf.setProperty
  2175. ///
  2176. /// @see {@link module:vwf/api/kernel.setProperty}
  2177. this.setProperty = function( nodeID, propertyName, propertyValue ) {
  2178. this.logger.debuggx( "setProperty", function() {
  2179. return [ nodeID, propertyName, JSON.stringify( loggableValue( propertyValue ) ) ];
  2180. } );
  2181. var node = nodes.existing[nodeID];
  2182. // Record calls into this function by nodeID and propertyName so that models may call
  2183. // back here (directly or indirectly) to delegate responses further down the chain
  2184. // without causing infinite recursion.
  2185. var entrants = this.setProperty.entrants;
  2186. var entry = entrants[nodeID+'-'+propertyName] || {}; // the most recent call, if any // TODO: need unique nodeID+propertyName hash
  2187. var reentry = entrants[nodeID+'-'+propertyName] = {}; // this call
  2188. // Select the actual driver calls. Create the property if it doesn't exist on this node
  2189. // or its prototypes. Initialize it if it exists on a prototype but not on this node.
  2190. // Set it if it already exists on this node.
  2191. if ( ! node.properties.has( propertyName ) || entry.creating ) {
  2192. reentry.creating = true;
  2193. var settingPropertyEtc = "creatingProperty";
  2194. var satPropertyEtc = "createdProperty";
  2195. node.properties.create( propertyName, node.initialized && node.patchable );
  2196. } else if ( ! node.properties.hasOwn( propertyName ) || entry.initializing ) {
  2197. reentry.initializing = true;
  2198. var settingPropertyEtc = "initializingProperty";
  2199. var satPropertyEtc = "initializedProperty";
  2200. node.properties.create( propertyName, node.initialized && node.patchable );
  2201. } else {
  2202. var settingPropertyEtc = "settingProperty";
  2203. var satPropertyEtc = "satProperty";
  2204. }
  2205. // Keep track of the number of assignments made by this `setProperty` call and others
  2206. // invoked indirectly by it, starting with the outermost call.
  2207. var outermost = entrants.assignments === undefined;
  2208. if ( outermost ) {
  2209. entrants.assignments = 0;
  2210. }
  2211. // Have we been called for the same property on the same node for a property still being
  2212. // assigned (such as when a setter function assigns the property to itself)? If so, then
  2213. // the inner call should skip drivers that the outer call has already invoked, and the
  2214. // outer call should complete without invoking drivers that the inner call will have
  2215. // already called.
  2216. var reentered = ( entry.index !== undefined );
  2217. // We'll need to know if the set was delegated to other properties or actually assigned
  2218. // here.
  2219. var delegated = false, assigned = false;
  2220. // Call settingProperty() on each model. The first model to return a non-undefined value
  2221. // has performed the set and dictates the return value. The property is considered set
  2222. // after all models have run.
  2223. this.models.some( function( model, index ) {
  2224. // Skip initial models that an outer call has already invoked for this node and
  2225. // property (if any). If an inner call completed for this node and property, skip
  2226. // the remaining models.
  2227. if ( ( ! reentered || index > entry.index ) && ! reentry.completed ) {
  2228. // Record the active model number.
  2229. reentry.index = index;
  2230. // Record the number of assignments made since the outermost call. When
  2231. // `entrants.assignments` increases, a driver has called `setProperty` to make
  2232. // an assignment elsewhere.
  2233. var assignments = entrants.assignments;
  2234. // Make the call.
  2235. if ( ! delegated && ! assigned ) {
  2236. var value = model[settingPropertyEtc] && model[settingPropertyEtc]( nodeID, propertyName, propertyValue );
  2237. } else {
  2238. model[settingPropertyEtc] && model[settingPropertyEtc]( nodeID, propertyName, undefined );
  2239. }
  2240. // Ignore the result if reentry is disabled and the driver attempted to call
  2241. // back into the kernel. Kernel reentry is disabled during replication to
  2242. // prevent coloring from accessor scripts.
  2243. if ( this.models.kernel.blocked() ) { // TODO: this might be better handled wholly in vwf/kernel/model by converting to a stage and clearing blocked results on the return
  2244. value = undefined;
  2245. }
  2246. // The property was delegated if the call made any assignments.
  2247. if ( entrants.assignments !== assignments ) {
  2248. delegated = true;
  2249. }
  2250. // Otherwise if the call returned a value, the property was assigned here.
  2251. else if ( value !== undefined ) {
  2252. entrants.assignments++;
  2253. assigned = true;
  2254. }
  2255. // Record the value actually assigned. This may differ from the incoming value
  2256. // if it was range limited, quantized, etc. by the model. This is the value
  2257. // passed to the views.
  2258. if ( value !== undefined ) {
  2259. propertyValue = value;
  2260. }
  2261. // If we are setting, exit from the this.models.some() iterator once the value
  2262. // has been set. Don't exit early if we are creating or initializing since every
  2263. // model needs the opportunity to register the property.
  2264. return settingPropertyEtc == "settingProperty" && ( delegated || assigned );
  2265. }
  2266. }, this );
  2267. // Record the change if the property was assigned here.
  2268. if ( assigned && node.initialized && node.patchable ) {
  2269. node.properties.change( propertyName );
  2270. }
  2271. // Call satProperty() on each view. The view is being notified that a property has
  2272. // been set. Only call for value properties as they are actually assigned. Don't call
  2273. // for accessor properties that have delegated to other properties. Notifying when
  2274. // setting an accessor property would be useful, but since that information is
  2275. // ephemeral, and views on late-joining clients would never see it, it's best to never
  2276. // send those notifications.
  2277. if ( assigned ) {
  2278. this.views.forEach( function( view ) {
  2279. view[satPropertyEtc] && view[satPropertyEtc]( nodeID, propertyName, propertyValue );
  2280. } );
  2281. }
  2282. if ( reentered ) {
  2283. // For a reentrant call, restore the previous state and move the index forward to
  2284. // cover the models we called.
  2285. entrants[nodeID+'-'+propertyName] = entry;
  2286. entry.completed = true;
  2287. } else {
  2288. // Delete the call record if this is the first, non-reentrant call here (the normal
  2289. // case).
  2290. delete entrants[nodeID+'-'+propertyName];
  2291. // If the property was created or initialized, send the corresponding meta event
  2292. // into the application.
  2293. if ( this.models.kernel.enabled() ) {
  2294. if ( settingPropertyEtc === "creatingProperty" ) {
  2295. this.fireEvent( nodeID, [ "properties", "created" ], [ propertyName ] );
  2296. } else if ( settingPropertyEtc === "initializingProperty" ) {
  2297. this.fireEvent( nodeID, [ "properties", "initialized" ], [ propertyName ] );
  2298. }
  2299. }
  2300. }
  2301. // Clear the assignment counter when the outermost `setProperty` completes.
  2302. if ( outermost ) {
  2303. delete entrants.assignments;
  2304. }
  2305. this.logger.debugu();
  2306. return propertyValue;
  2307. };
  2308. this.setProperty.entrants = {}; // maps ( nodeID + '-' + propertyName ) => { index: i, value: v }
  2309. // -- getProperty --------------------------------------------------------------------------
  2310. /// Get a property value for a node.
  2311. ///
  2312. /// @name module:vwf.getProperty
  2313. ///
  2314. /// @see {@link module:vwf/api/kernel.getProperty}
  2315. this.getProperty = function( nodeID, propertyName, ignorePrototype ) {
  2316. this.logger.debuggx( "getProperty", nodeID, propertyName );
  2317. var propertyValue = undefined;
  2318. // Record calls into this function by nodeID and propertyName so that models may call
  2319. // back here (directly or indirectly) to delegate responses further down the chain
  2320. // without causing infinite recursion.
  2321. var entrants = this.getProperty.entrants;
  2322. var entry = entrants[nodeID+'-'+propertyName] || {}; // the most recent call, if any // TODO: need unique nodeID+propertyName hash
  2323. var reentry = entrants[nodeID+'-'+propertyName] = {}; // this call
  2324. // Keep track of the number of retrievals made by this `getProperty` call and others
  2325. // invoked indirectly by it, starting with the outermost call.
  2326. var outermost = entrants.retrievals === undefined;
  2327. if ( outermost ) {
  2328. entrants.retrievals = 0;
  2329. }
  2330. // Have we been called for the same property on the same node for a property still being
  2331. // retrieved (such as when a getter function retrieves the property from itself)? If so,
  2332. // then the inner call should skip drivers that the outer call has already invoked, and
  2333. // the outer call should complete without invoking drivers that the inner call will have
  2334. // already called.
  2335. var reentered = ( entry.index !== undefined );
  2336. // We'll need to know if the get was delegated to other properties or actually retrieved
  2337. // here.
  2338. var delegated = false, retrieved = false;
  2339. // Call gettingProperty() on each model. The first model to return a non-undefined value
  2340. // dictates the return value.
  2341. this.models.some( function( model, index ) {
  2342. // Skip initial models that an outer call has already invoked for this node and
  2343. // property (if any). If an inner call completed for this node and property, skip
  2344. // the remaining models.
  2345. if ( ( ! reentered || index > entry.index ) && ! reentry.completed ) {
  2346. // Record the active model number.
  2347. reentry.index = index;
  2348. // Record the number of retrievals made since the outermost call. When
  2349. // `entrants.retrievals` increases, a driver has called `getProperty` to make
  2350. // a retrieval elsewhere.
  2351. var retrievals = entrants.retrievals;
  2352. // Make the call.
  2353. var value = model.gettingProperty &&
  2354. model.gettingProperty( nodeID, propertyName, propertyValue ); // TODO: probably don't need propertyValue here
  2355. // Ignore the result if reentry is disabled and the driver attempted to call
  2356. // back into the kernel. Kernel reentry is disabled during replication to
  2357. // prevent coloring from accessor scripts.
  2358. if ( this.models.kernel.blocked() ) { // TODO: this might be better handled wholly in vwf/kernel/model by converting to a stage and clearing blocked results on the return
  2359. value = undefined;
  2360. }
  2361. // The property was delegated if the call made any retrievals.
  2362. if ( entrants.retrievals !== retrievals ) {
  2363. delegated = true;
  2364. }
  2365. // Otherwise if the call returned a value, the property was retrieved here.
  2366. else if ( value !== undefined ) {
  2367. entrants.retrievals++;
  2368. retrieved = true;
  2369. }
  2370. // Record the value retrieved.
  2371. if ( value !== undefined ) {
  2372. propertyValue = value;
  2373. }
  2374. // Exit from the this.models.some() iterator once we have a return value.
  2375. return delegated || retrieved;
  2376. }
  2377. }, this );
  2378. if ( reentered ) {
  2379. // For a reentrant call, restore the previous state, move the index forward to cover
  2380. // the models we called.
  2381. entrants[nodeID+'-'+propertyName] = entry;
  2382. entry.completed = true;
  2383. } else {
  2384. // Delete the call record if this is the first, non-reentrant call here (the normal
  2385. // case).
  2386. delete entrants[nodeID+'-'+propertyName];
  2387. // Delegate to the behaviors and prototype if we didn't get a result from the
  2388. // current node.
  2389. if ( propertyValue === undefined && ! ignorePrototype ) {
  2390. this.behaviors( nodeID ).reverse().concat( this.prototype( nodeID ) ).
  2391. some( function( prototypeID, prototypeIndex, prototypeArray ) {
  2392. if ( prototypeIndex < prototypeArray.length - 1 ) {
  2393. propertyValue = this.getProperty( prototypeID, propertyName, true ); // behavior node only, not its prototypes
  2394. } else if ( prototypeID !== this.kutility.protoNodeURI ) {
  2395. propertyValue = this.getProperty( prototypeID, propertyName ); // prototype node, recursively
  2396. }
  2397. return propertyValue !== undefined;
  2398. }, this );
  2399. }
  2400. // Call gotProperty() on each view.
  2401. this.views.forEach( function( view ) {
  2402. view.gotProperty && view.gotProperty( nodeID, propertyName, propertyValue ); // TODO: be sure this is the value actually gotten and not an intermediate value from above
  2403. } );
  2404. }
  2405. // Clear the retrieval counter when the outermost `getProperty` completes.
  2406. if ( outermost ) {
  2407. delete entrants.retrievals;
  2408. }
  2409. this.logger.debugu();
  2410. return propertyValue;
  2411. };
  2412. this.getProperty.entrants = {}; // maps ( nodeID + '-' + propertyName ) => { index: i, value: v }
  2413. // -- createMethod -------------------------------------------------------------------------
  2414. /// @name module:vwf.createMethod
  2415. ///
  2416. /// @see {@link module:vwf/api/kernel.createMethod}
  2417. this.createMethod = function( nodeID, methodName, methodParameters, methodBody ) {
  2418. this.logger.debuggx( "createMethod", function() {
  2419. return [ nodeID, methodName, methodParameters, loggableScript( methodBody ) ];
  2420. } );
  2421. var node = nodes.existing[nodeID];
  2422. // Register the method.
  2423. node.methods.create( methodName, node.initialized && node.patchable );
  2424. // Call `creatingMethod` on each model. The method is considered created after all
  2425. // models have run.
  2426. this.models.forEach( function( model ) {
  2427. model.creatingMethod && model.creatingMethod( nodeID, methodName, methodParameters,
  2428. methodBody );
  2429. } );
  2430. // Call `createdMethod` on each view. The view is being notified that a method has been
  2431. // created.
  2432. this.views.forEach( function( view ) {
  2433. view.createdMethod && view.createdMethod( nodeID, methodName, methodParameters,
  2434. methodBody );
  2435. } );
  2436. // Send the meta event into the application.
  2437. if ( this.models.kernel.enabled() ) {
  2438. this.fireEvent( nodeID, [ "methods", "created" ], [ methodName ] );
  2439. }
  2440. this.logger.debugu();
  2441. };
  2442. // -- setMethod ----------------------------------------------------------------------------
  2443. /// @name module:vwf.setMethod
  2444. ///
  2445. /// @see {@link module:vwf/api/kernel.setMethod}
  2446. this.setMethod = function( nodeID, methodName, methodHandler ) {
  2447. this.logger.debuggx( "setMethod", function() {
  2448. return [ nodeID, methodName ]; // TODO loggable methodHandler
  2449. } );
  2450. var node = nodes.existing[nodeID];
  2451. methodHandler = normalizedHandler( methodHandler );
  2452. if ( ! node.methods.hasOwn( methodName ) ) {
  2453. // If the method doesn't exist on this node, delegate to `kernel.createMethod` to
  2454. // create and assign the method.
  2455. this.createMethod( nodeID, methodName, methodHandler.parameters, methodHandler.body ); // TODO: result
  2456. } else {
  2457. // Call `settingMethod` on each model. The first model to return a non-undefined
  2458. // value dictates the return value.
  2459. this.models.some( function( model ) {
  2460. // Call the driver.
  2461. var handler = model.settingMethod && model.settingMethod( nodeID, methodName, methodHandler );
  2462. // Update the value to the value assigned if the driver handled it.
  2463. if ( handler !== undefined ) {
  2464. methodHandler = require( "vwf/utility" ).merge( {}, handler ); // omit `undefined` values
  2465. }
  2466. // Exit the iterator once a driver has handled the assignment.
  2467. return handler !== undefined;
  2468. } );
  2469. // Record the change.
  2470. if ( node.initialized && node.patchable ) {
  2471. node.methods.change( methodName );
  2472. }
  2473. // Call `satMethod` on each view.
  2474. this.views.forEach( function( view ) {
  2475. view.satMethod && view.satMethod( nodeID, methodName, methodHandler );
  2476. } );
  2477. }
  2478. this.logger.debugu();
  2479. return methodHandler;
  2480. };
  2481. // -- getMethod ----------------------------------------------------------------------------
  2482. /// @name module:vwf.getMethod
  2483. ///
  2484. /// @see {@link module:vwf/api/kernel.getMethod}
  2485. this.getMethod = function( nodeID, methodName ) {
  2486. this.logger.debuggx( "getMethod", function() {
  2487. return [ nodeID, methodName ];
  2488. } );
  2489. var node = nodes.existing[nodeID];
  2490. // Call `gettingMethod` on each model. The first model to return a non-undefined value
  2491. // dictates the return value.
  2492. var methodHandler = {};
  2493. this.models.some( function( model ) {
  2494. // Call the driver.
  2495. var handler = model.gettingMethod && model.gettingMethod( nodeID, methodName );
  2496. // Update the value to the value assigned if the driver handled it.
  2497. if ( handler !== undefined ) {
  2498. methodHandler = require( "vwf/utility" ).merge( {}, handler ); // omit `undefined` values
  2499. }
  2500. // Exit the iterator once a driver has handled the retrieval.
  2501. return handler !== undefined;
  2502. } );
  2503. // Call `gotMethod` on each view.
  2504. this.views.forEach( function( view ) {
  2505. view.gotMethod && view.gotMethod( nodeID, methodName, methodHandler );
  2506. } );
  2507. this.logger.debugu();
  2508. return methodHandler;
  2509. };
  2510. // -- callMethod ---------------------------------------------------------------------------
  2511. /// @name module:vwf.callMethod
  2512. ///
  2513. /// @see {@link module:vwf/api/kernel.callMethod}
  2514. this.callMethod = function( nodeID, methodName, methodParameters ) {
  2515. this.logger.debuggx( "callMethod", function() {
  2516. return [ nodeID, methodName, JSON.stringify( loggableValues( methodParameters ) ) ];
  2517. } );
  2518. // Call callingMethod() on each model. The first model to return a non-undefined value
  2519. // dictates the return value.
  2520. var methodValue = undefined;
  2521. this.models.some( function( model ) {
  2522. methodValue = model.callingMethod && model.callingMethod( nodeID, methodName, methodParameters );
  2523. return methodValue !== undefined;
  2524. } );
  2525. // Call calledMethod() on each view.
  2526. this.views.forEach( function( view ) {
  2527. view.calledMethod && view.calledMethod( nodeID, methodName, methodParameters, methodValue );
  2528. } );
  2529. this.logger.debugu();
  2530. return methodValue;
  2531. };
  2532. // -- createEvent --------------------------------------------------------------------------
  2533. /// @name module:vwf.createEvent
  2534. ///
  2535. /// @see {@link module:vwf/api/kernel.createEvent}
  2536. this.createEvent = function( nodeID, eventName, eventParameters ) { // TODO: parameters (used? or just for annotation?) // TODO: allow a handler body here and treat as this.*event* = function() {} (a self-targeted handler); will help with ui event handlers
  2537. this.logger.debuggx( "createEvent", nodeID, eventName, eventParameters );
  2538. var node = nodes.existing[nodeID];
  2539. // Encode any namespacing into the name. (Namespaced names were added in 0.6.21.)
  2540. var encodedEventName = namespaceEncodedName( eventName );
  2541. // Register the event.
  2542. node.events.create( encodedEventName, node.initialized && node.patchable, eventParameters );
  2543. // Call `creatingEvent` on each model. The event is considered created after all models
  2544. // have run.
  2545. this.models.forEach( function( model ) {
  2546. model.creatingEvent && model.creatingEvent( nodeID, encodedEventName, eventParameters );
  2547. } );
  2548. // Call `createdEvent` on each view. The view is being notified that a event has been
  2549. // created.
  2550. this.views.forEach( function( view ) {
  2551. view.createdEvent && view.createdEvent( nodeID, encodedEventName, eventParameters );
  2552. } );
  2553. // Send the meta event into the application.
  2554. if ( this.models.kernel.enabled() ) {
  2555. this.fireEvent( nodeID, [ "events", "created" ], [ eventName ] );
  2556. }
  2557. this.logger.debugu();
  2558. };
  2559. // -- setEvent -----------------------------------------------------------------------------
  2560. /// @name module:vwf.setEvent
  2561. ///
  2562. /// @see {@link module:vwf/api/kernel.setEvent}
  2563. this.setEvent = function( nodeID, eventName, eventDescriptor ) {
  2564. this.logger.debuggx( "setEvent", function() {
  2565. return [ nodeID, eventName ]; // TODO: loggable eventDescriptor
  2566. } );
  2567. var node = nodes.existing[nodeID];
  2568. // eventDescriptor = normalizedHandler( eventDescriptor ); // TODO
  2569. // Encode any namespacing into the name.
  2570. var encodedEventName = namespaceEncodedName( eventName );
  2571. if ( ! node.events.hasOwn( encodedEventName ) ) {
  2572. // If the event doesn't exist on this node, delegate to `kernel.createEvent` to
  2573. // create and assign the event.
  2574. this.createEvent( nodeID, eventName, eventDescriptor.parameters ); // TODO: result
  2575. ( eventDescriptor.listeners || [] ).forEach( function( listener ) {
  2576. return this.addEventListener( nodeID, eventName, listener, listener.context, listener.phases );
  2577. }, this );
  2578. } else {
  2579. // Locate the event in the registry.
  2580. var event = node.events.existing[ encodedEventName ];
  2581. // xxx
  2582. eventDescriptor = {
  2583. parameters: event.parameters ?
  2584. event.parameters.slice() : [], // TODO: note: we're ignoring eventDescriptor.parameters in the set
  2585. listeners: ( eventDescriptor.listeners || [] ).map( function( listener ) {
  2586. if ( event.listeners.hasOwn( listener.id ) ) {
  2587. return this.setEventListener( nodeID, eventName, listener.id, listener );
  2588. } else {
  2589. return this.addEventListener( nodeID, eventName, listener, listener.context, listener.phases );
  2590. }
  2591. }, this ),
  2592. };
  2593. }
  2594. this.logger.debugu();
  2595. return eventDescriptor;
  2596. };
  2597. // -- getEvent -----------------------------------------------------------------------------
  2598. /// @name module:vwf.getEvent
  2599. ///
  2600. /// @see {@link module:vwf/api/kernel.getEvent}
  2601. this.getEvent = function( nodeID, eventName ) {
  2602. this.logger.debuggx( "getEvent", function() {
  2603. return [ nodeID, eventName ];
  2604. } );
  2605. var node = nodes.existing[nodeID];
  2606. // Encode any namespacing into the name.
  2607. var encodedEventName = namespaceEncodedName( eventName );
  2608. // Locate the event in the registry.
  2609. var event = node.events.existing[ encodedEventName ];
  2610. // Build the result descriptor. Omit the `parameters` and `listeners` fields when the
  2611. // parameters or listeners are missing or empty, respectively.
  2612. var eventDescriptor = {};
  2613. if ( event.parameters ) {
  2614. eventDescriptor.parameters = event.parameters.slice();
  2615. }
  2616. if ( event.listeners.existing.length ) {
  2617. eventDescriptor.listeners = event.listeners.existing.map( function( eventListenerID ) {
  2618. var listener = this.getEventListener( nodeID, eventName, eventListenerID );
  2619. listener.id = eventListenerID;
  2620. return listener;
  2621. }, this );
  2622. }
  2623. this.logger.debugu();
  2624. return eventDescriptor;
  2625. };
  2626. // -- addEventListener ---------------------------------------------------------------------
  2627. /// @name module:vwf.addEventListener
  2628. ///
  2629. /// @see {@link module:vwf/api/kernel.addEventListener}
  2630. this.addEventListener = function( nodeID, eventName, eventHandler, eventContextID, eventPhases ) {
  2631. this.logger.debuggx( "addEventListener", function() {
  2632. return [ nodeID, eventName, loggableScript( eventHandler ),
  2633. eventContextID, eventPhases ];
  2634. } );
  2635. var node = nodes.existing[nodeID];
  2636. // Encode any namespacing into the name.
  2637. var encodedEventName = namespaceEncodedName( eventName );
  2638. // Register the event if this is the first listener added to an event on a prototype.
  2639. if ( ! node.events.hasOwn( encodedEventName ) ) {
  2640. node.events.create( encodedEventName, node.initialized && node.patchable );
  2641. }
  2642. // Locate the event in the registry.
  2643. var event = node.events.existing[ encodedEventName ];
  2644. // Normalize the descriptor.
  2645. eventHandler = normalizedHandler( eventHandler, event.parameters );
  2646. // Register the listener.
  2647. var eventListenerID = eventHandler.id || this.sequence( nodeID );
  2648. event.listeners.create( eventListenerID, node.initialized && node.patchable );
  2649. // Call `addingEventListener` on each model.
  2650. this.models.forEach( function( model ) {
  2651. model.addingEventListener &&
  2652. model.addingEventListener( nodeID, encodedEventName, eventListenerID,
  2653. eventHandler, eventContextID, eventPhases );
  2654. } );
  2655. // Call `addedEventListener` on each view.
  2656. this.views.forEach( function( view ) {
  2657. view.addedEventListener &&
  2658. view.addedEventListener( nodeID, encodedEventName, eventListenerID,
  2659. eventHandler, eventContextID, eventPhases );
  2660. } );
  2661. this.logger.debugu();
  2662. return eventListenerID;
  2663. };
  2664. // -- removeEventListener ------------------------------------------------------------------
  2665. /// @name module:vwf.removeEventListener
  2666. ///
  2667. /// @see {@link module:vwf/api/kernel.removeEventListener}
  2668. this.removeEventListener = function( nodeID, eventName, eventListenerID ) {
  2669. this.logger.debuggx( "removeEventListener", function() {
  2670. return [ nodeID, eventName, loggableScript( eventListenerID ) ];
  2671. } );
  2672. var node = nodes.existing[nodeID];
  2673. // Encode any namespacing into the name.
  2674. var encodedEventName = namespaceEncodedName( eventName );
  2675. // Locate the event in the registry.
  2676. var event = node.events.existing[ encodedEventName ];
  2677. // Unregister the listener.
  2678. event.listeners.delete( eventListenerID, node.initialized && node.patchable );
  2679. // Call `removingEventListener` on each model.
  2680. this.models.forEach( function( model ) {
  2681. model.removingEventListener &&
  2682. model.removingEventListener( nodeID, encodedEventName, eventListenerID );
  2683. } );
  2684. // Call `removedEventListener` on each view.
  2685. this.views.forEach( function( view ) {
  2686. view.removedEventListener &&
  2687. view.removedEventListener( nodeID, encodedEventName, eventListenerID );
  2688. } );
  2689. this.logger.debugu();
  2690. return eventListenerID;
  2691. };
  2692. // -- setEventListener ---------------------------------------------------------------------
  2693. /// @name module:vwf.setEventListener
  2694. ///
  2695. /// @see {@link module:vwf/api/kernel.setEventListener}
  2696. this.setEventListener = function( nodeID, eventName, eventListenerID, eventListener ) {
  2697. this.logger.debuggx( "setEventListener", function() {
  2698. return [ nodeID, eventName, eventListenerID ]; // TODO: loggable eventListener
  2699. } );
  2700. var node = nodes.existing[nodeID];
  2701. // Encode any namespacing into the name.
  2702. var encodedEventName = namespaceEncodedName( eventName );
  2703. // Locate the event in the registry.
  2704. var event = node.events.existing[ encodedEventName ];
  2705. // Normalize the descriptor.
  2706. eventListener = normalizedHandler( eventListener, event.parameters );
  2707. // Record the change.
  2708. if ( node.initialized && node.patchable ) {
  2709. event.listeners.change( eventListenerID );
  2710. }
  2711. // Call `settingEventListener` on each model. The first model to return a non-undefined
  2712. // value dictates the return value.
  2713. this.models.some( function( model ) {
  2714. // Call the driver.
  2715. var listener = model.settingEventListener &&
  2716. model.settingEventListener( nodeID, encodedEventName, eventListenerID, eventListener );
  2717. // Update the value to the value assigned if the driver handled it.
  2718. if ( listener !== undefined ) {
  2719. eventListener = require( "vwf/utility" ).merge( {}, listener ); // omit `undefined` values
  2720. }
  2721. // Exit the iterator once a driver has handled the assignment.
  2722. return listener !== undefined;
  2723. } );
  2724. // Call `satEventListener` on each view.
  2725. this.views.forEach( function( view ) {
  2726. view.satEventListener &&
  2727. view.satEventListener( nodeID, encodedEventName, eventListenerID, eventListener );
  2728. } );
  2729. this.logger.debugu();
  2730. return eventListener;
  2731. };
  2732. // -- getEventListener ---------------------------------------------------------------------
  2733. /// @name module:vwf.getEventListener
  2734. ///
  2735. /// @see {@link module:vwf/api/kernel.getEventListener}
  2736. this.getEventListener = function( nodeID, eventName, eventListenerID ) {
  2737. this.logger.debuggx( "getEventListener", function() {
  2738. return [ nodeID, eventName, eventListenerID ];
  2739. } );
  2740. // Encode any namespacing into the name.
  2741. var encodedEventName = namespaceEncodedName( eventName );
  2742. // Call `gettingEventListener` on each model. The first model to return a non-undefined
  2743. // value dictates the return value.
  2744. var eventListener = {};
  2745. this.models.some( function( model ) {
  2746. // Call the driver.
  2747. var listener = model.gettingEventListener &&
  2748. model.gettingEventListener( nodeID, encodedEventName, eventListenerID );
  2749. // Update the value to the value assigned if the driver handled it.
  2750. if ( listener !== undefined ) {
  2751. eventListener = require( "vwf/utility" ).merge( {}, listener ); // omit `undefined` values
  2752. }
  2753. // Exit the iterator once a driver has handled the assignment.
  2754. return listener !== undefined;
  2755. } );
  2756. // Call `gotEventListener` on each view.
  2757. this.views.forEach( function( view ) {
  2758. view.gotEventListener &&
  2759. view.gotEventListener( nodeID, encodedEventName, eventListenerID, eventListener );
  2760. } );
  2761. this.logger.debugu();
  2762. return eventListener;
  2763. };
  2764. // -- flushEventListeners ------------------------------------------------------------------
  2765. /// @name module:vwf.flushEventListeners
  2766. ///
  2767. /// @see {@link module:vwf/api/kernel.flushEventListeners}
  2768. this.flushEventListeners = function( nodeID, eventName, eventContextID ) {
  2769. this.logger.debuggx( "flushEventListeners", nodeID, eventName, eventContextID );
  2770. // Encode any namespacing into the name.
  2771. var encodedEventName = namespaceEncodedName( eventName );
  2772. // Retrieve the event in case we need to remove listeners from it
  2773. var node = nodes.existing[ nodeID ];
  2774. var event = node.events.existing[ encodedEventName ];
  2775. // Call `flushingEventListeners` on each model.
  2776. this.models.forEach( function( model ) {
  2777. var removedIds = model.flushingEventListeners &&
  2778. model.flushingEventListeners( nodeID, encodedEventName, eventContextID );
  2779. // If the model driver returned an array of the ids of event listeners that it
  2780. // removed, remove their references in the kernel
  2781. if ( removedIds && removedIds.length ) {
  2782. // Unregister the listeners that were flushed
  2783. removedIds.forEach( function( removedId ) {
  2784. event.listeners.delete( removedId, node.initialized && node.patchable );
  2785. } );
  2786. }
  2787. } );
  2788. // Call `flushedEventListeners` on each view.
  2789. this.views.forEach( function( view ) {
  2790. view.flushedEventListeners &&
  2791. view.flushedEventListeners( nodeID, encodedEventName, eventContextID );
  2792. } );
  2793. // TODO: `flushEventListeners` can be interpreted by the kernel now and handled with a
  2794. // `removeEventListener` call instead of separate `flushingEventListeners` and
  2795. // `flushedEventListeners` calls to the drivers.
  2796. this.logger.debugu();
  2797. };
  2798. // -- fireEvent ----------------------------------------------------------------------------
  2799. /// @name module:vwf.fireEvent
  2800. ///
  2801. /// @see {@link module:vwf/api/kernel.fireEvent}
  2802. this.fireEvent = function( nodeID, eventName, eventParameters ) {
  2803. this.logger.debuggx( "fireEvent", function() {
  2804. return [ nodeID, eventName, JSON.stringify( loggableValues( eventParameters ) ) ];
  2805. } );
  2806. // Encode any namespacing into the name. (Namespaced names were added in 0.6.21.)
  2807. var encodedEventName = namespaceEncodedName( eventName );
  2808. // Call `firingEvent` on each model.
  2809. var handled = this.models.reduce( function( handled, model ) {
  2810. return model.firingEvent && model.firingEvent( nodeID, encodedEventName, eventParameters ) || handled;
  2811. }, false );
  2812. // Call `firedEvent` on each view.
  2813. this.views.forEach( function( view ) {
  2814. view.firedEvent && view.firedEvent( nodeID, encodedEventName, eventParameters );
  2815. } );
  2816. this.logger.debugu();
  2817. // TODO: `fireEvent` needs to tell the drivers to invoke each listener individually
  2818. // now that listeners can be spread across multiple drivers.
  2819. return handled;
  2820. };
  2821. // -- dispatchEvent ------------------------------------------------------------------------
  2822. /// Dispatch an event toward a node. Using fireEvent(), capture (down) and bubble (up) along
  2823. /// the path from the global root to the node. Cancel when one of the handlers returns a
  2824. /// truthy value to indicate that it has handled the event.
  2825. ///
  2826. /// @name module:vwf.dispatchEvent
  2827. ///
  2828. /// @see {@link module:vwf/api/kernel.dispatchEvent}
  2829. this.dispatchEvent = function( nodeID, eventName, eventParameters, eventNodeParameters ) {
  2830. this.logger.debuggx( "dispatchEvent", function() {
  2831. return [ nodeID, eventName, JSON.stringify( loggableValues( eventParameters ) ),
  2832. JSON.stringify( loggableIndexedValues( eventNodeParameters ) ) ];
  2833. } );
  2834. // Defaults for the parameters to send with the events. Values from `eventParameters`
  2835. // are sent to each node. `eventNodeParameters` contains additional values to send to
  2836. // specific nodes.
  2837. eventParameters = eventParameters || [];
  2838. eventNodeParameters = eventNodeParameters || {};
  2839. // Find the inheritance path from the node to the root.
  2840. var ancestorIDs = this.ancestors( nodeID );
  2841. var lastAncestorID = "";
  2842. // Make space to record the parameters sent to each node. Parameters provided for upper
  2843. // nodes cascade down until another definition is found for a lower node. We'll remember
  2844. // these on the way down and replay them on the way back up.
  2845. var cascadedEventNodeParameters = {
  2846. "": eventNodeParameters[""] || [] // defaults come from the "" key in eventNodeParameters
  2847. };
  2848. // Parameters passed to the handlers are the concatention of the eventParameters array,
  2849. // the eventNodeParameters for the node (cascaded), and the phase.
  2850. var targetEventParameters = undefined;
  2851. var phase = undefined;
  2852. var handled = false;
  2853. // Capturing phase.
  2854. phase = "capture"; // only handlers tagged "capture" will be invoked
  2855. handled = handled || ancestorIDs.reverse().some( function( ancestorID ) { // TODO: reverse updates the array in place every time and we'd rather not
  2856. cascadedEventNodeParameters[ancestorID] = eventNodeParameters[ancestorID] ||
  2857. cascadedEventNodeParameters[lastAncestorID];
  2858. lastAncestorID = ancestorID;
  2859. targetEventParameters =
  2860. eventParameters.concat( cascadedEventNodeParameters[ancestorID], phase );
  2861. targetEventParameters.phase = phase; // smuggle the phase across on the parameters array // TODO: add "phase" as a fireEvent() parameter? it isn't currently needed in the kernel public API (not queueable, not called by the drivers), so avoid if possible
  2862. return this.fireEvent( ancestorID, eventName, targetEventParameters );
  2863. }, this );
  2864. // At target.
  2865. phase = undefined; // invoke all handlers
  2866. cascadedEventNodeParameters[nodeID] = eventNodeParameters[nodeID] ||
  2867. cascadedEventNodeParameters[lastAncestorID];
  2868. targetEventParameters =
  2869. eventParameters.concat( cascadedEventNodeParameters[nodeID], phase );
  2870. handled = handled || this.fireEvent( nodeID, eventName, targetEventParameters );
  2871. // Bubbling phase.
  2872. phase = undefined; // invoke all handlers
  2873. handled = handled || ancestorIDs.reverse().some( function( ancestorID ) { // TODO: reverse updates the array in place every time and we'd rather not
  2874. targetEventParameters =
  2875. eventParameters.concat( cascadedEventNodeParameters[ancestorID], phase );
  2876. return this.fireEvent( ancestorID, eventName, targetEventParameters );
  2877. }, this );
  2878. this.logger.debugu();
  2879. };
  2880. // -- execute ------------------------------------------------------------------------------
  2881. /// @name module:vwf.execute
  2882. ///
  2883. /// @see {@link module:vwf/api/kernel.execute}
  2884. this.execute = function( nodeID, scriptText, scriptType, callback_async /* result */ ) {
  2885. this.logger.debuggx( "execute", function() {
  2886. return [ nodeID, loggableScript( scriptText ), scriptType ];
  2887. } );
  2888. // Assume JavaScript if the type is not specified and the text is a string.
  2889. if ( ! scriptType && ( typeof scriptText == "string" || scriptText instanceof String ) ) {
  2890. scriptType = "application/javascript";
  2891. }
  2892. // Call executing() on each model. The script is considered executed after all models
  2893. // have run.
  2894. var scriptValue = undefined;
  2895. // Watch for any async kernel calls generated as we execute the scriptText and wait for
  2896. // them to complete before calling the callback.
  2897. vwf.models.kernel.capturingAsyncs( function() {
  2898. vwf.models.some( function( model ) {
  2899. scriptValue = model.executing &&
  2900. model.executing( nodeID, scriptText, scriptType );
  2901. return scriptValue !== undefined;
  2902. } );
  2903. // Call executed() on each view to notify view that a script has been executed.
  2904. vwf.views.forEach( function( view ) {
  2905. view.executed && view.executed( nodeID, scriptText, scriptType );
  2906. } );
  2907. }, function() {
  2908. callback_async && callback_async( scriptValue );
  2909. } );
  2910. this.logger.debugu();
  2911. return scriptValue;
  2912. };
  2913. // -- random -------------------------------------------------------------------------------
  2914. /// @name module:vwf.random
  2915. ///
  2916. /// @see {@link module:vwf/api/kernel.random}
  2917. this.random = function( nodeID ) {
  2918. return this.models.object.random( nodeID );
  2919. };
  2920. // -- seed ---------------------------------------------------------------------------------
  2921. /// @name module:vwf.seed
  2922. ///
  2923. /// @see {@link module:vwf/api/kernel.seed}
  2924. this.seed = function( nodeID, seed ) {
  2925. return this.models.object.seed( nodeID, seed );
  2926. };
  2927. // -- time ---------------------------------------------------------------------------------
  2928. /// The current simulation time.
  2929. ///
  2930. /// @name module:vwf.time
  2931. ///
  2932. /// @see {@link module:vwf/api/kernel.time}
  2933. this.time = function() {
  2934. return this.now;
  2935. };
  2936. // -- client -------------------------------------------------------------------------------
  2937. /// The moniker of the client responsible for the current action. Will be falsy for actions
  2938. /// originating in the server, such as time ticks.
  2939. ///
  2940. /// @name module:vwf.client
  2941. ///
  2942. /// @see {@link module:vwf/api/kernel.client}
  2943. this.client = function() {
  2944. return this.client_;
  2945. };
  2946. // -- moniker ------------------------------------------------------------------------------
  2947. /// The identifer the server assigned to this client.
  2948. ///
  2949. /// @name module:vwf.moniker
  2950. ///
  2951. /// @see {@link module:vwf/api/kernel.moniker}
  2952. this.moniker = function() {
  2953. return this.moniker_;
  2954. };
  2955. // -- application --------------------------------------------------------------------------
  2956. /// @name module:vwf.application
  2957. ///
  2958. /// @see {@link module:vwf/api/kernel.application}
  2959. this.application = function( initializedOnly ) {
  2960. var applicationID;
  2961. Object.keys( nodes.globals ).forEach( function( globalID ) {
  2962. var global = nodes.existing[ globalID ];
  2963. if ( ( ! initializedOnly || global.initialized ) && global.name === "application" ) {
  2964. applicationID = globalID;
  2965. }
  2966. }, this );
  2967. return applicationID;
  2968. };
  2969. // -- intrinsics ---------------------------------------------------------------------------
  2970. /// @name module:vwf.intrinsics
  2971. ///
  2972. /// @see {@link module:vwf/api/kernel.intrinsics}
  2973. this.intrinsics = function( nodeID, result ) {
  2974. return this.models.object.intrinsics( nodeID, result );
  2975. };
  2976. // -- uri ----------------------------------------------------------------------------------
  2977. /// @name module:vwf.uri
  2978. ///
  2979. /// @see {@link module:vwf/api/kernel.uri}
  2980. this.uri = function( nodeID, searchAncestors, initializedOnly ) {
  2981. var uri = this.models.object.uri( nodeID );
  2982. if ( searchAncestors ) {
  2983. while ( ! uri && ( nodeID = this.parent( nodeID, initializedOnly ) ) ) {
  2984. uri = this.models.object.uri( nodeID );
  2985. }
  2986. }
  2987. return uri;
  2988. };
  2989. // -- name ---------------------------------------------------------------------------------
  2990. /// @name module:vwf.name
  2991. ///
  2992. /// @see {@link module:vwf/api/kernel.name}
  2993. this.name = function( nodeID ) {
  2994. return this.models.object.name( nodeID );
  2995. };
  2996. // -- prototype ----------------------------------------------------------------------------
  2997. /// @name module:vwf.prototype
  2998. ///
  2999. /// @see {@link module:vwf/api/kernel.prototype}
  3000. this.prototype = function( nodeID ) {
  3001. return this.models.object.prototype( nodeID );
  3002. };
  3003. // -- prototypes ---------------------------------------------------------------------------
  3004. /// @name module:vwf.prototypes
  3005. ///
  3006. /// @see {@link module:vwf/api/kernel.prototypes}
  3007. this.prototypes = function( nodeID, includeBehaviors ) {
  3008. var prototypes = [];
  3009. do {
  3010. // Add the current node's behaviors.
  3011. if ( includeBehaviors ) {
  3012. var b = [].concat( this.behaviors( nodeID ) );
  3013. Array.prototype.push.apply( prototypes, b.reverse() );
  3014. }
  3015. // Get the next prototype.
  3016. nodeID = this.prototype( nodeID );
  3017. // Add the prototype.
  3018. if ( nodeID ) {
  3019. prototypes.push( nodeID );
  3020. }
  3021. } while ( nodeID );
  3022. return prototypes;
  3023. };
  3024. // -- behaviors ----------------------------------------------------------------------------
  3025. /// @name module:vwf.behaviors
  3026. ///
  3027. /// @see {@link module:vwf/api/kernel.behaviors}
  3028. this.behaviors = function( nodeID ) {
  3029. return this.models.object.behaviors( nodeID );
  3030. };
  3031. // -- globals ------------------------------------------------------------------------------
  3032. /// @name module:vwf.globals
  3033. ///
  3034. /// @see {@link module:vwf/api/kernel.globals}
  3035. this.globals = function( initializedOnly ) {
  3036. var globals = {};
  3037. Object.keys( nodes.globals ).forEach( function( globalID ) {
  3038. if ( ! initializedOnly || nodes.existing[ globalID ].initialized ) {
  3039. globals[ globalID ] = undefined;
  3040. }
  3041. }, this );
  3042. return globals;
  3043. };
  3044. // -- global -------------------------------------------------------------------------------
  3045. /// @name module:vwf.global
  3046. ///
  3047. /// @see {@link module:vwf/api/kernel.global}
  3048. this.global = function( globalReference, initializedOnly ) {
  3049. var globals = this.globals( initializedOnly );
  3050. // Look for a global node whose URI matches `globalReference`. If there is no match by
  3051. // URI, then search again by name.
  3052. return matches( "uri" ) || matches( "name" );
  3053. // Look for a global node where the field named by `field` matches `globalReference`.
  3054. function matches( field ) {
  3055. var matchingID;
  3056. Object.keys( globals ).some( function( globalID ) {
  3057. if ( nodes.existing[ globalID ][ field ] === globalReference ) {
  3058. matchingID = globalID;
  3059. return true;
  3060. }
  3061. } );
  3062. return matchingID;
  3063. }
  3064. };
  3065. // -- root ---------------------------------------------------------------------------------
  3066. /// @name module:vwf.root
  3067. ///
  3068. /// @see {@link module:vwf/api/kernel.root}
  3069. this.root = function( nodeID, initializedOnly ) {
  3070. var rootID;
  3071. // Walk the ancestors to the top of the tree. Stop when we reach the pseudo-node at the
  3072. // global root, which unlike all other nodes has a falsy ID, or `undefined` if we could
  3073. // not reach the top because `initializedOnly` is set and we attempted to cross between
  3074. // nodes that have and have not completed initialization.
  3075. do {
  3076. rootID = nodeID;
  3077. nodeID = this.parent( nodeID, initializedOnly );
  3078. } while ( nodeID );
  3079. // Return the root ID, or `undefined` when `initializedOnly` is set and the node can't
  3080. // see the root.
  3081. return nodeID === undefined ? undefined : rootID;
  3082. };
  3083. // -- ancestors ----------------------------------------------------------------------------
  3084. /// @name module:vwf.ancestors
  3085. ///
  3086. /// @see {@link module:vwf/api/kernel.ancestors}
  3087. this.ancestors = function( nodeID, initializedOnly ) {
  3088. var ancestors = [];
  3089. nodeID = this.parent( nodeID, initializedOnly );
  3090. while ( nodeID ) {
  3091. ancestors.push( nodeID );
  3092. nodeID = this.parent( nodeID, initializedOnly );
  3093. }
  3094. return ancestors;
  3095. };
  3096. // -- parent -------------------------------------------------------------------------------
  3097. /// @name module:vwf.parent
  3098. ///
  3099. /// @see {@link module:vwf/api/kernel.parent}
  3100. this.parent = function( nodeID, initializedOnly ) {
  3101. return this.models.object.parent( nodeID, initializedOnly );
  3102. };
  3103. // -- children -----------------------------------------------------------------------------
  3104. /// @name module:vwf.children
  3105. ///
  3106. /// @see {@link module:vwf/api/kernel.children}
  3107. this.children = function( nodeID, initializedOnly ) {
  3108. if ( nodeID === undefined ) {
  3109. this.logger.errorx( "children", "cannot retrieve children of nonexistent node" );
  3110. return;
  3111. }
  3112. return this.models.object.children( nodeID, initializedOnly );
  3113. };
  3114. // -- child --------------------------------------------------------------------------------
  3115. /// @name module:vwf.child
  3116. ///
  3117. /// @see {@link module:vwf/api/kernel.child}
  3118. this.child = function( nodeID, childReference, initializedOnly ) {
  3119. var children = this.children( nodeID, initializedOnly );
  3120. if ( typeof childReference === "number" || childReference instanceof Number ) {
  3121. return children[ childReference ];
  3122. } else {
  3123. return children.filter( function( childID ) {
  3124. return childID && this.name( childID ) === childReference;
  3125. }, this )[ 0 ];
  3126. }
  3127. };
  3128. // -- descendants --------------------------------------------------------------------------
  3129. /// @name module:vwf.descendants
  3130. ///
  3131. /// @see {@link module:vwf/api/kernel.descendants}
  3132. this.descendants = function( nodeID, initializedOnly ) {
  3133. if ( nodeID === undefined ) {
  3134. this.logger.errorx( "descendants", "cannot retrieve children of nonexistent node" );
  3135. return;
  3136. }
  3137. var descendants = [];
  3138. this.children( nodeID, initializedOnly ).forEach( function( childID ) {
  3139. descendants.push( childID );
  3140. childID && Array.prototype.push.apply( descendants, this.descendants( childID, initializedOnly ) );
  3141. }, this );
  3142. return descendants;
  3143. };
  3144. // -- sequence -----------------------------------------------------------------------------
  3145. /// @name module:vwf.sequence
  3146. ///
  3147. /// @see {@link module:vwf/api/kernel.sequence}
  3148. this.sequence = function( nodeID ) {
  3149. return this.models.object.sequence( nodeID );
  3150. };
  3151. /// Locate nodes matching a search pattern. See vwf.api.kernel#find for details.
  3152. ///
  3153. /// @name module:vwf.find
  3154. ///
  3155. /// @param {ID} nodeID
  3156. /// The reference node. Relative patterns are resolved with respect to this node. `nodeID`
  3157. /// is ignored for absolute patterns.
  3158. /// @param {String} matchPattern
  3159. /// The search pattern.
  3160. /// @param {Boolean} [initializedOnly]
  3161. /// Interpret nodes that haven't completed initialization as though they don't have
  3162. /// ancestors. Drivers that manage application code should set `initializedOnly` since
  3163. /// applications should never have access to uninitialized parts of the application graph.
  3164. /// @param {Function} [callback]
  3165. /// A callback to receive the search results. If callback is provided, find invokes
  3166. /// callback( matchID ) for each match. Otherwise the result is returned as an array.
  3167. ///
  3168. /// @returns {ID[]|undefined}
  3169. /// If callback is provided, undefined; otherwise an array of the node ids of the result.
  3170. ///
  3171. /// @see {@link module:vwf/api/kernel.find}
  3172. this.find = function( nodeID, matchPattern, initializedOnly, callback /* ( matchID ) */ ) {
  3173. // Interpret `find( nodeID, matchPattern, callback )` as
  3174. // `find( nodeID, matchPattern, undefined, callback )`. (`initializedOnly` was added in
  3175. // 0.6.8.)
  3176. if ( typeof initializedOnly == "function" || initializedOnly instanceof Function ) {
  3177. callback = initializedOnly;
  3178. initializedOnly = undefined;
  3179. }
  3180. // Run the query.
  3181. var matchIDs = find.call( this, nodeID, matchPattern, initializedOnly );
  3182. // Return the result. Invoke the callback if one was provided. Otherwise, return the
  3183. // array directly.
  3184. if ( callback ) {
  3185. matchIDs.forEach( function( matchID ) {
  3186. callback( matchID );
  3187. } );
  3188. } else { // TODO: future iterator proxy
  3189. return matchIDs;
  3190. }
  3191. };
  3192. // -- findClients ------------------------------------------------------------------------------
  3193. /// Locate client nodes matching a search pattern.
  3194. ///
  3195. /// @name module:vwf.findClients
  3196. ///
  3197. /// @param {ID} nodeID
  3198. /// The reference node. Relative patterns are resolved with respect to this node. `nodeID`
  3199. /// is ignored for absolute patterns.
  3200. /// @param {String} matchPattern
  3201. /// The search pattern.
  3202. /// @param {Function} [callback]
  3203. /// A callback to receive the search results. If callback is provided, find invokes
  3204. /// callback( matchID ) for each match. Otherwise the result is returned as an array.
  3205. ///
  3206. /// @returns {ID[]|undefined}
  3207. /// If callback is provided, undefined; otherwise an array of the node ids of the result.
  3208. ///
  3209. /// @deprecated in version 0.6.21. Instead of `kernel.findClients( reference, "/pattern" )`,
  3210. /// use `kernel.find( reference, "doc('http://vwf.example.com/clients.vwf')/pattern" )`.
  3211. ///
  3212. /// @see {@link module:vwf/api/kernel.findClients}
  3213. this.findClients = function( nodeID, matchPattern, callback /* ( matchID ) */ ) {
  3214. this.logger.warn( "`kernel.findClients` is deprecated. Use " +
  3215. "`kernel.find( nodeID, \"doc('http://vwf.example.com/clients.vwf')/pattern\" )`" +
  3216. " instead." );
  3217. var clientsMatchPattern = "doc('http://vwf.example.com/clients.vwf')" +
  3218. ( matchPattern[0] === "/" ? "" : "/" ) + matchPattern;
  3219. return this.find( nodeID || this.application(), clientsMatchPattern, callback );
  3220. };
  3221. /// Test a node against a search pattern. See vwf.api.kernel#test for details.
  3222. ///
  3223. /// @name module:vwf.test
  3224. ///
  3225. /// @param {ID} nodeID
  3226. /// The reference node. Relative patterns are resolved with respect to this node. `nodeID`
  3227. /// is ignored for absolute patterns.
  3228. /// @param {String} matchPattern
  3229. /// The search pattern.
  3230. /// @param {ID} testID
  3231. /// A node to test against the pattern.
  3232. /// @param {Boolean} [initializedOnly]
  3233. /// Interpret nodes that haven't completed initialization as though they don't have
  3234. /// ancestors. Drivers that manage application code should set `initializedOnly` since
  3235. /// applications should never have access to uninitialized parts of the application graph.
  3236. ///
  3237. /// @returns {Boolean}
  3238. /// true when testID matches the pattern.
  3239. ///
  3240. /// @see {@link module:vwf/api/kernel.test}
  3241. this.test = function( nodeID, matchPattern, testID, initializedOnly ) {
  3242. // Run the query.
  3243. var matchIDs = find.call( this, nodeID, matchPattern, initializedOnly );
  3244. // Search for the test node in the result.
  3245. return matchIDs.some( function( matchID ) {
  3246. return matchID == testID;
  3247. } );
  3248. };
  3249. // == Private functions ====================================================================
  3250. var isSocketIO07 = function() {
  3251. //return ( parseFloat( io.version ) >= 0.7 );
  3252. return true
  3253. }
  3254. // -- loadComponent ------------------------------------------------------------------------
  3255. /// @name module:vwf~loadComponent
  3256. var loadComponent = function( nodeURI, baseURI, callback_async /* nodeDescriptor */, errback_async /* errorMessage */ ) { // TODO: turn this into a generic xhr loader exposed as a kernel function?
  3257. if ( nodeURI == vwf.kutility.protoNodeURI ) {
  3258. callback_async( vwf.kutility.protoNodeDescriptor );
  3259. } else if ( nodeURI.match( RegExp( "^data:application/json;base64," ) ) ) {
  3260. // Primarly for testing, parse one specific form of data URIs. We need to parse
  3261. // these ourselves since Chrome can't load data URIs due to cross origin
  3262. // restrictions.
  3263. callback_async( JSON.parse( atob( nodeURI.substring( 29 ) ) ) ); // TODO: support all data URIs
  3264. } else {
  3265. queue.suspend( "while loading " + nodeURI ); // suspend the queue
  3266. jQuery.ajax( {
  3267. url: remappedURI( require( "vwf/utility" ).resolveURI( nodeURI, baseURI ) ),
  3268. dataType: "jsonp",
  3269. timeout: vwf.configuration["load-timeout"] * 1000,
  3270. success: function( nodeDescriptor ) /* async */ {
  3271. callback_async( nodeDescriptor );
  3272. queue.resume( "after loading " + nodeURI ); // resume the queue; may invoke dispatch(), so call last before returning to the host
  3273. },
  3274. error: function( xhr, status, error ) /* async */ {
  3275. vwf.logger.warnx( "loadComponent", "error loading", nodeURI + ":", error );
  3276. errback_async( error );
  3277. queue.resume( "after loading " + nodeURI ); // resume the queue; may invoke dispatch(), so call last before returning to the host
  3278. },
  3279. } );
  3280. }
  3281. };
  3282. // -- loadScript ---------------------------------------------------------------------------
  3283. /// @name module:vwf~loadScript
  3284. var loadScript = function( scriptURI, baseURI, callback_async /* scriptText */, errback_async /* errorMessage */ ) {
  3285. if ( scriptURI.match( RegExp( "^data:application/javascript;base64," ) ) ) {
  3286. // Primarly for testing, parse one specific form of data URIs. We need to parse
  3287. // these ourselves since Chrome can't load data URIs due to cross origin
  3288. // restrictions.
  3289. callback_async( atob( scriptURI.substring( 35 ) ) ); // TODO: support all data URIs
  3290. } else {
  3291. queue.suspend( "while loading " + scriptURI ); // suspend the queue
  3292. jQuery.ajax( {
  3293. url: remappedURI( require( "vwf/utility" ).resolveURI( scriptURI, baseURI ) ),
  3294. dataType: "text",
  3295. timeout: vwf.configuration["load-timeout"] * 1000,
  3296. success: function( scriptText ) /* async */ {
  3297. callback_async( scriptText );
  3298. queue.resume( "after loading " + scriptURI ); // resume the queue; may invoke dispatch(), so call last before returning to the host
  3299. },
  3300. error: function( xhr, status, error ) /* async */ {
  3301. vwf.logger.warnx( "loadScript", "error loading", scriptURI + ":", error );
  3302. errback_async( error );
  3303. queue.resume( "after loading " + scriptURI ); // resume the queue; may invoke dispatch(), so call last before returning to the host
  3304. },
  3305. } );
  3306. }
  3307. };
  3308. /// Determine if a given property of a node has a setter function, either directly on the
  3309. /// node or inherited from a prototype.
  3310. ///
  3311. /// This function must run as a method of the kernel. Invoke as: nodePropertyHasSetter.call(
  3312. /// kernel, nodeID, propertyName ).
  3313. ///
  3314. /// @name module:vwf~nodePropertyHasSetter
  3315. ///
  3316. /// @param {ID} nodeID
  3317. /// @param {String} propertyName
  3318. ///
  3319. /// @returns {Boolean}
  3320. var nodePropertyHasSetter = function( nodeID, propertyName ) { // invoke with the kernel as "this" // TODO: this is peeking inside of vwf-model-javascript; need to delegate to all script drivers
  3321. var node = this.models.javascript.nodes[nodeID];
  3322. var setter = node.private.setters && node.private.setters[propertyName];
  3323. return typeof setter == "function" || setter instanceof Function;
  3324. };
  3325. /// Determine if a given property of a node has a setter function. The node's prototypes are
  3326. /// not considered.
  3327. ///
  3328. /// This function must run as a method of the kernel. Invoke as:
  3329. /// nodePropertyHasOwnSetter.call( kernel, nodeID, propertyName ).
  3330. ///
  3331. /// @name module:vwf~nodePropertyHasOwnSetter
  3332. ///
  3333. /// @param {ID} nodeID
  3334. /// @param {String} propertyName
  3335. ///
  3336. /// @returns {Boolean}
  3337. var nodePropertyHasOwnSetter = function( nodeID, propertyName ) { // invoke with the kernel as "this" // TODO: this is peeking inside of vwf-model-javascript; need to delegate to all script drivers
  3338. var node = this.models.javascript.nodes[nodeID];
  3339. var setter = node.private.setters && node.private.setters.hasOwnProperty( propertyName ) && node.private.setters[propertyName];
  3340. return typeof setter == "function" || setter instanceof Function;
  3341. };
  3342. /// Determine if a node has a child with the given name, either directly on the node or
  3343. /// inherited from a prototype.
  3344. ///
  3345. /// This function must run as a method of the kernel. Invoke as: nodeHasChild.call(
  3346. /// kernel, nodeID, childName ).
  3347. ///
  3348. /// @name module:vwf~nodeHasChild
  3349. ///
  3350. /// @param {ID} nodeID
  3351. /// @param {String} childName
  3352. ///
  3353. /// @returns {Boolean}
  3354. var nodeHasChild = function( nodeID, childName ) { // invoke with the kernel as "this" // TODO: this is peeking inside of vwf-model-javascript
  3355. var node = this.models.javascript.nodes[nodeID];
  3356. return childName in node.children;
  3357. };
  3358. /// Determine if a node has a child with the given name. The node's prototypes are not
  3359. /// considered.
  3360. ///
  3361. /// This function must run as a method of the kernel. Invoke as: nodeHasOwnChild.call(
  3362. /// kernel, nodeID, childName ).
  3363. ///
  3364. /// @name module:vwf~nodeHasOwnChild
  3365. ///
  3366. /// @param {ID} nodeID
  3367. /// @param {String} childName
  3368. ///
  3369. /// @returns {Boolean}
  3370. var nodeHasOwnChild = function( nodeID, childName ) { // invoke with the kernel as "this" // TODO: this is peeking inside of vwf-model-javascript
  3371. var node = this.models.javascript.nodes[nodeID];
  3372. var hasChild = false;
  3373. if ( parseInt( childName ).toString() !== childName ) {
  3374. hasChild = node.children.hasOwnProperty( childName ); // TODO: this is peeking inside of vwf-model-javascript
  3375. }
  3376. else {
  3377. // Children with numeric names do not get added as properties of the children array, so loop over the children
  3378. // to check manually
  3379. for(var i=0, il=node.children.length; i<il;i++) {
  3380. if(childName === node.children[i].name) {
  3381. hasChild = true;
  3382. }
  3383. }
  3384. }
  3385. return hasChild;
  3386. };
  3387. /// Determine if a component specifier is a URI.
  3388. ///
  3389. /// A component may be specified as the URI of a resource containing a descriptor (string),
  3390. /// a descriptor (object), or the ID of a previously-created node (primitive).
  3391. ///
  3392. /// @name module:vwf~componentIsURI
  3393. ///
  3394. /// @param {String|Object} candidate
  3395. ///
  3396. /// @returns {Boolean}
  3397. var componentIsURI = function( candidate ) {
  3398. return ( typeof candidate == "string" || candidate instanceof String ) && ! componentIsID( candidate );
  3399. };
  3400. /// Determine if a component specifier is a descriptor.
  3401. ///
  3402. /// A component may be specified as the URI of a resource containing a descriptor (string),
  3403. /// a descriptor (object), or the ID of a previously-created node (primitive).
  3404. ///
  3405. /// @name module:vwf~componentIsDescriptor
  3406. ///
  3407. /// @param {String|Object} candidate
  3408. ///
  3409. /// @returns {Boolean}
  3410. var componentIsDescriptor = function( candidate ) {
  3411. return typeof candidate == "object" && candidate != null && ! isPrimitive( candidate );
  3412. };
  3413. /// Determine if a component specifier is an ID.
  3414. ///
  3415. /// A component may be specified as the URI of a resource containing a descriptor (string),
  3416. /// a descriptor (object), or the ID of a previously-created node (primitive).
  3417. ///
  3418. /// @name module:vwf~componentIsID
  3419. ///
  3420. /// @param {String|Object} candidate
  3421. ///
  3422. /// @returns {Boolean}
  3423. var componentIsID = function( candidate ) {
  3424. return isPrimitive( candidate ) && vwf.models.object.exists( candidate ) &&
  3425. ! ( components[candidate] instanceof Array );
  3426. };
  3427. /// Determine if a value is a JavaScript primitive, or the boxed version of a JavaScript
  3428. /// primitive.
  3429. ///
  3430. /// Node IDs are JavaScript primitives. This function may be used to determine if a value
  3431. /// has the correct type to be a node ID.
  3432. ///
  3433. /// @name module:vwf~isPrimitive
  3434. ///
  3435. /// @param candidate
  3436. ///
  3437. /// @returns {Boolean}
  3438. var isPrimitive = function( candidate ) {
  3439. switch ( typeof candidate ) {
  3440. case "string":
  3441. case "number":
  3442. case "boolean":
  3443. return true;
  3444. case "object":
  3445. return candidate instanceof String || candidate instanceof Number ||
  3446. candidate instanceof Boolean;
  3447. default:
  3448. return false;
  3449. }
  3450. };
  3451. /// Determine if an object is a component descriptor. Detect the type by searching for
  3452. /// descriptor keys in the candidate object.
  3453. ///
  3454. /// @name module:vwf~objectIsComponent
  3455. ///
  3456. /// @param {Object} candidate
  3457. ///
  3458. /// @returns {Boolean}
  3459. var objectIsComponent = function( candidate ) {
  3460. var componentAttributes = [
  3461. "extends",
  3462. "implements",
  3463. "source",
  3464. "type",
  3465. "properties",
  3466. "methods",
  3467. "events",
  3468. "children",
  3469. "scripts",
  3470. ];
  3471. var isComponent = false;
  3472. if ( typeof candidate == "object" && candidate != null ) {
  3473. isComponent = componentAttributes.some( function( attributeName ) {
  3474. return candidate.hasOwnProperty( attributeName );
  3475. } );
  3476. }
  3477. return isComponent;
  3478. };
  3479. /// Determine if a property initializer is a detailed initializer containing explicit
  3480. /// accessor and value parameters (rather than a simple value specification). Detect the
  3481. /// type by searching for property initializer keys in the candidate object.
  3482. ///
  3483. /// @name module:vwf~valueHasAccessors
  3484. ///
  3485. /// @param {Object} candidate
  3486. ///
  3487. /// @returns {Boolean}
  3488. var valueHasAccessors = function( candidate ) {
  3489. var accessorAttributes = [
  3490. "get",
  3491. "set",
  3492. "value",
  3493. "node",
  3494. "create",
  3495. "undefined",
  3496. ];
  3497. var hasAccessors = false;
  3498. if ( typeof candidate == "object" && candidate != null ) {
  3499. hasAccessors = accessorAttributes.some( function( attributeName ) {
  3500. return candidate.hasOwnProperty( attributeName );
  3501. } );
  3502. }
  3503. return hasAccessors;
  3504. };
  3505. /// Determine if a method or event initializer is a detailed initializer containing a
  3506. /// parameter list along with the body text (method initializers only). Detect the type by
  3507. /// searching for method and event initializer keys in the candidate object.
  3508. ///
  3509. /// @name module:vwf~valueHasBody
  3510. ///
  3511. /// @param {Object} candidate
  3512. ///
  3513. /// @returns {Boolean}
  3514. var valueHasBody = function( candidate ) { // TODO: refactor and share with valueHasAccessors and possibly objectIsComponent // TODO: unlike a property initializer, we really only care if it's an object vs. text; text == use as body; object == presume o.parameters and o.body // TODO: except that a script in the unnamed-list format would appear as an object but should be used as the body
  3515. var bodyAttributes = [
  3516. "parameters",
  3517. "body",
  3518. "listeners",
  3519. ];
  3520. var hasBody = false; // TODO: "body" term is confusing, but that's the current terminology used in vwf/model/javascript
  3521. if ( typeof candidate == "object" && candidate != null ) {
  3522. hasBody = bodyAttributes.some( function( attributeName ) {
  3523. return candidate.hasOwnProperty( attributeName );
  3524. } );
  3525. }
  3526. return hasBody;
  3527. };
  3528. /// Determine if a script initializer is a detailed initializer containing explicit text and
  3529. /// type parameters (rather than being a simple text specification). Detect the type by
  3530. /// searching for the script initializer keys in the candidate object.
  3531. ///
  3532. /// @name module:vwf~valueHasType
  3533. ///
  3534. /// @param {Object} candidate
  3535. ///
  3536. /// @returns {Boolean}
  3537. var valueHasType = function( candidate ) { // TODO: refactor and share with valueHasBody, valueHasAccessors and possibly objectIsComponent
  3538. var typeAttributes = [
  3539. "source",
  3540. "text",
  3541. "type",
  3542. ];
  3543. var hasType = false;
  3544. if ( typeof candidate == "object" && candidate != null ) {
  3545. hasType = typeAttributes.some( function( attributeName ) {
  3546. return candidate.hasOwnProperty( attributeName );
  3547. } );
  3548. }
  3549. return hasType;
  3550. };
  3551. /// Convert a potentially-namespaced member name into a string such that a namespaced name
  3552. /// will be distinct from an encoded name in any other namespace, or from any simple name
  3553. /// not having a namespace.
  3554. ///
  3555. /// Simple names are strings such as `"name"`. Namespaced names are arrays of strings, such
  3556. /// as `[ "ns", "name" ]` or `[ "outer", "inner", "name" ]`. An array containing a single
  3557. /// string, such as `[ "name" ]`, is not namespaced and is the same name as `"name"`.
  3558. ///
  3559. /// Each of the following encodes into a distinct value:
  3560. ///
  3561. /// `"name"` or `[ "name" ]`
  3562. /// `[ "a", "name" ]`
  3563. /// `[ "b", "name" ]`
  3564. /// `[ "a", "a", "name" ]`
  3565. /// `[ "a", "b", "name" ]`
  3566. /// `[ "b", "b", "name" ]`
  3567. /// *etc.*
  3568. ///
  3569. /// @name module:vwf~namespaceEncodedName
  3570. ///
  3571. /// @param {String|String[]} memberName
  3572. /// A string, or an array of strings containing a name preceded by any number of namespace
  3573. /// names. In an array, each element defines a unique space for the member name and for
  3574. /// any intermediate namespaces.
  3575. ///
  3576. /// @returns {String}
  3577. var namespaceEncodedName = function( memberName ) {
  3578. if ( typeof memberName === "object" && memberName instanceof Array ) {
  3579. return ( memberName.length !== 1 ) ? "vwf$" + memberName.join( "$" ) : memberName[0];
  3580. } else {
  3581. return memberName;
  3582. }
  3583. };
  3584. /// Convert a (potentially-abbreviated) component specification to a descriptor parsable by
  3585. /// vwf.createChild. The following forms are accepted:
  3586. ///
  3587. /// - Descriptor: { extends: component, source: ..., type: ..., ... }
  3588. /// - Component URI: http://host/path/to/component.vwf
  3589. /// - Asset URI: http://host/ath/to/asset.type
  3590. /// - Node ID
  3591. ///
  3592. /// They are converted as follows:
  3593. ///
  3594. /// - Descriptor: unchanged [1]
  3595. /// - Component URI: a component that extends the component identified by the URI
  3596. /// - Asset URI: a component having the asset identified by the URI as its source
  3597. /// - Node ID: a component that extends the previously-created node identified by the ID
  3598. ///
  3599. /// [1] As a special case, missing MIME types are filled in for assets matcching the
  3600. /// patterns *.unity3d and *.dae, and components having assets of those types but no
  3601. /// prototype declared will be upgraded to extend scene.vwf and navscene.vwf, respectively.
  3602. ///
  3603. /// @name module:vwf~normalizedComponent
  3604. ///
  3605. /// @param {String|Object} component
  3606. ///
  3607. /// @returns {Object}
  3608. var normalizedComponent = function( component ) {
  3609. // Convert a component URI to an instance of that type or an asset reference to an
  3610. // untyped reference to that asset. Convert a component ID to an instance of that
  3611. // prototype.
  3612. if ( componentIsURI( component ) ) {
  3613. if ( component.match( /\.vwf$/ ) ) { // TODO: detect component from mime-type instead of extension?
  3614. component = { extends: component };
  3615. } else {
  3616. component = { source: component };
  3617. }
  3618. } else if ( componentIsID( component ) ) {
  3619. component = { extends: component };
  3620. }
  3621. // Fill in the mime type from the source specification if not provided.
  3622. if ( component.source && ! component.type ) { // TODO: validate component
  3623. var match = component.source.match( /\.([^.]*)$/ ); // TODO: get type from mime-type (from server if remote, from os if local, or (?) from this internal table otherwise)
  3624. if ( match ) {
  3625. switch ( match[1] ) {
  3626. case "unity3d":
  3627. component.type = "application/vnd.unity";
  3628. break;
  3629. case "dae":
  3630. component.type = "model/vnd.collada+xml";
  3631. break;
  3632. }
  3633. }
  3634. }
  3635. // Fill in the component type from the mime type if not provided.
  3636. if ( component.type && ! component.extends ) { // TODO: load from a server configuration file
  3637. switch ( component.type ) {
  3638. case "application/vnd.unity":
  3639. component.extends = "http://vwf.example.com/scene.vwf";
  3640. break;
  3641. case "model/vnd.collada+xml":
  3642. component.extends = "http://vwf.example.com/navscene.vwf";
  3643. break;
  3644. }
  3645. }
  3646. return component;
  3647. };
  3648. /// Convert a `Handler` specification into the standard form of an object containing
  3649. /// `parameters`, `body` and `type` fields.
  3650. ///
  3651. /// @name module:vwf~normalizedHandler
  3652. ///
  3653. /// @param {Handler|string}
  3654. /// @param {string[]} [defaultParameters]
  3655. ///
  3656. /// @returns {Handler}
  3657. var normalizedHandler = function( handler, defaultParameters ) {
  3658. // Convert abbreviated forms to the explict `Handler` form.
  3659. if ( typeof handler !== "object" || handler instanceof Array ) {
  3660. handler = { body: handler };
  3661. } else if ( require( "vwf/configuration" ).active[ "preserve-script-closures" ] && ( typeof handler == "function" || handler instanceof Function ) ) {
  3662. handler = { body: handler };
  3663. }
  3664. // Use a default parameter list if the handler doesn't provide its own and if defaults
  3665. // were provided.
  3666. if ( ! handler.parameters && defaultParameters ) {
  3667. handler.parameters = defaultParameters;
  3668. }
  3669. // Fill in a default media type if `type` is not provided. A `body` of type `string` is
  3670. // taken to be `application/javascript`.
  3671. if ( handler.type === undefined ) {
  3672. if ( typeof handler.body === "string" || handler.body instanceof String ) {
  3673. handler.type = "application/javascript";
  3674. }
  3675. }
  3676. return handler;
  3677. };
  3678. /// Convert a `fields` object as passed between the client and reflector and stored in the
  3679. /// message queue into a form suitable for writing to a log.
  3680. ///
  3681. /// @name module:vwf~loggableFields
  3682. ///
  3683. /// @param {Object} fields
  3684. ///
  3685. /// @returns {Object}
  3686. var loggableFields = function( fields ) {
  3687. return require( "vwf/utility" ).transform( fields, require( "vwf/utility" ).transforms.transit );
  3688. };
  3689. /// Convert a component URI, descriptor or ID into a form suitable for writing to a log.
  3690. ///
  3691. /// @name module:vwf~loggableComponent
  3692. ///
  3693. /// @param {String|Object} component
  3694. ///
  3695. /// @returns {String|Object}
  3696. var loggableComponent = function( component ) {
  3697. return require( "vwf/utility" ).transform( component, loggableComponentTransformation );
  3698. };
  3699. /// Convert an arbitrary JavaScript value into a form suitable for writing to a log.
  3700. ///
  3701. /// @name module:vwf~loggableValue
  3702. ///
  3703. /// @param {Object} value
  3704. ///
  3705. /// @returns {Object}
  3706. var loggableValue = function( value ) {
  3707. return require( "vwf/utility" ).transform( value, function( object, names, depth ) {
  3708. object = require( "vwf/utility" ).transforms.transit( object, names, depth );
  3709. return typeof object == "number" ? Number( object.toPrecision(5) ) : object; // reduce numeric precision to remove visual noise
  3710. } );
  3711. };
  3712. /// Convert an array of arbitrary JavaScript values into a form suitable for writing to a
  3713. /// log.
  3714. ///
  3715. /// @name module:vwf~loggableValues
  3716. ///
  3717. /// @param {Object[]|undefined} values
  3718. ///
  3719. /// @returns {Object[]|undefined}
  3720. var loggableValues = function( values ) {
  3721. return loggableValue( values );
  3722. };
  3723. /// Convert an object indexing arrays of arbitrary JavaScript values into a form suitable
  3724. /// for writing to a log.
  3725. ///
  3726. /// @name module:vwf~loggableIndexedValues
  3727. ///
  3728. /// @param {Object|undefined} values
  3729. ///
  3730. /// @returns {Object|undefined}
  3731. var loggableIndexedValues = function( values ) {
  3732. return loggableValue( values );
  3733. };
  3734. /// Convert script text into a form suitable for writing to a log.
  3735. ///
  3736. /// @name module:vwf~loggableScript
  3737. ///
  3738. /// @param {String|undefined} script
  3739. ///
  3740. /// @returns {String}
  3741. var loggableScript = function( script ) {
  3742. return ( script || "" ).replace( /\s+/g, " " ).substring( 0, 100 );
  3743. };
  3744. // -- remappedURI --------------------------------------------------------------------------
  3745. /// Remap a component URI to its location in a local cache.
  3746. ///
  3747. /// http://vwf.example.com/component.vwf => http://localhost/proxy/vwf.example.com/component.vwf
  3748. ///
  3749. /// @name module:vwf~remappedURI
  3750. var remappedURI = function( uri ) {
  3751. var match = uri.match( RegExp( "http://(vwf.example.com)/(.*)" ) );
  3752. if ( match ) {
  3753. uri = window.location.protocol + "//" + window.location.host +
  3754. "/proxy/" + match[1] + "/" + match[2];
  3755. }
  3756. return uri;
  3757. };
  3758. // -- resolvedDescriptor -------------------------------------------------------------------
  3759. /// Resolve relative URIs in a component descriptor.
  3760. ///
  3761. /// @name module:vwf~resolvedDescriptor
  3762. var resolvedDescriptor = function( component, baseURI ) {
  3763. return require( "vwf/utility" ).transform( component, resolvedDescriptorTransformationWithBaseURI );
  3764. function resolvedDescriptorTransformationWithBaseURI( object, names, depth ) {
  3765. return resolvedDescriptorTransformation.call( this, object, names, depth, baseURI );
  3766. }
  3767. };
  3768. // -- queueTransitTransformation -----------------------------------------------------------
  3769. /// vwf/utility/transform() transformation function to convert the message queue for proper
  3770. /// JSON serialization.
  3771. ///
  3772. /// queue: [ { ..., parameters: [ [ arguments ] ], ... }, { ... }, ... ]
  3773. ///
  3774. /// @name module:vwf~queueTransitTransformation
  3775. var queueTransitTransformation = function( object, names, depth ) {
  3776. if ( depth == 0 ) {
  3777. // Omit any private direct messages for this client, then sort by arrival order
  3778. // (rather than by time) so that messages will retain the same arrival order when
  3779. // reinserted.
  3780. return object.filter( function( fields ) {
  3781. return ! ( fields.origin === "reflector" && fields.sequence > vwf.sequence_ ) && fields.action; // TODO: fields.action is here to filter out tick messages // TODO: don't put ticks on the queue but just use them to fast-forward to the current time (requires removing support for passing ticks to the drivers and nodes)
  3782. } ).sort( function( fieldsA, fieldsB ) {
  3783. return fieldsA.sequence - fieldsB.sequence;
  3784. } );
  3785. } else if ( depth == 1 ) {
  3786. // Remove the sequence fields since they're just local annotations used to keep
  3787. // messages ordered by insertion order and aren't directly meaniful outside of this
  3788. // client.
  3789. var filtered = {};
  3790. Object.keys( object ).filter( function( key ) {
  3791. return key != "sequence";
  3792. } ).forEach( function( key ) {
  3793. filtered[key] = object[key];
  3794. } );
  3795. return filtered;
  3796. }
  3797. return object;
  3798. };
  3799. // -- loggableComponentTransformation ------------------------------------------------------
  3800. /// vwf/utility/transform() transformation function to truncate the verbose bits of a
  3801. /// component so that it may be written to a log.
  3802. ///
  3803. /// @name module:vwf~loggableComponentTransformation
  3804. var loggableComponentTransformation = function( object, names, depth ) {
  3805. // Get our bearings at the current recusion level.
  3806. var markers = descriptorMarkers( object, names, depth );
  3807. // Transform the object here.
  3808. switch ( markers.containerName ) {
  3809. case "extends":
  3810. // Omit a component descriptor for the prototype.
  3811. if ( markers.memberIndex == 0 && componentIsDescriptor( object ) ) {
  3812. return {};
  3813. }
  3814. break;
  3815. case "implements":
  3816. // Omit component descriptors for the behaviors.
  3817. if ( markers.memberIndex == 0 && componentIsDescriptor( object ) ) {
  3818. return {};
  3819. }
  3820. break;
  3821. case "properties":
  3822. // Convert property values to a loggable version, and omit getter and setter
  3823. // text.
  3824. if ( markers.memberIndex == 0 && ! valueHasAccessors( object ) ||
  3825. markers.memberIndex == 1 && names[0] == "value" ) {
  3826. return loggableValue( object );
  3827. } else if ( markers.memberIndex == 1 && ( names[0] == "get" || names[0] == "set" ) ) {
  3828. return "...";
  3829. }
  3830. break;
  3831. case "methods":
  3832. // Omit method body text.
  3833. if ( markers.memberIndex == 0 && ! valueHasBody( object ) ||
  3834. markers.memberIndex == 1 && names[0] == "body" ) {
  3835. return "...";
  3836. }
  3837. break;
  3838. case "events":
  3839. // Nothing for events.
  3840. break;
  3841. case "children":
  3842. // Omit child component descriptors.
  3843. if ( markers.memberIndex == 0 && componentIsDescriptor( object ) ) {
  3844. return {};
  3845. }
  3846. break;
  3847. case "scripts":
  3848. // Shorten script text.
  3849. if ( markers.memberIndex == 0 && ! valueHasType( object ) ||
  3850. markers.memberIndex == 1 && names[0] == "text" ) {
  3851. return "...";
  3852. }
  3853. break;
  3854. }
  3855. return object;
  3856. };
  3857. // -- resolvedDescriptorTransformation -----------------------------------------------------
  3858. /// vwf/utility/transform() transformation function to resolve relative URIs in a component
  3859. /// descriptor.
  3860. ///
  3861. /// @name module:vwf~resolvedDescriptorTransformation
  3862. var resolvedDescriptorTransformation = function( object, names, depth, baseURI ) {
  3863. // Get our bearings at the current recusion level.
  3864. var markers = descriptorMarkers( object, names, depth );
  3865. // Resolve all the URIs.
  3866. switch ( markers.containerName ) {
  3867. case "extends":
  3868. case "implements":
  3869. case "source":
  3870. case "children":
  3871. if ( markers.memberIndex == 0 && componentIsURI( object ) ) {
  3872. return require( "vwf/utility" ).resolveURI( object, baseURI );
  3873. }
  3874. break;
  3875. case "scripts":
  3876. if ( markers.memberIndex == 1 && names[0] == "source" ) {
  3877. return require( "vwf/utility" ).resolveURI( object, baseURI );
  3878. }
  3879. break;
  3880. }
  3881. return object;
  3882. };
  3883. // -- descriptorMarkers --------------------------------------------------------------------
  3884. /// Locate the closest container (`properties`, `methods`, `events`, `children`) and
  3885. /// contained member in a `vwf/utility/transform` iterator call on a component descriptor.
  3886. ///
  3887. /// @name module:vwf~descriptorMarkers
  3888. var descriptorMarkers = function( object, names, depth ) {
  3889. // Find the index of the lowest nested component in the names list.
  3890. var componentIndex = names.length;
  3891. while ( componentIndex > 2 && names[componentIndex-1] == "children" ) {
  3892. componentIndex -= 2;
  3893. }
  3894. // depth names notes
  3895. // ----- ----- -----
  3896. // 0: [] the component
  3897. // 1: [ "properties" ] its properties object
  3898. // 2: [ "propertyName", "properties" ] one property
  3899. // 1: [ "children" ] the children object
  3900. // 2: [ "childName", "children" ] one child
  3901. // 3: [ "properties", "childName", "children" ] the child's properties
  3902. // 4: [ "propertyName", "properties", "childName", "children" ] one child property
  3903. if ( componentIndex > 0 ) {
  3904. // Locate the container ("properties", "methods", "events", etc.) below the
  3905. // component in the names list.
  3906. var containerIndex = componentIndex - 1;
  3907. var containerName = names[containerIndex];
  3908. // Locate the member as appropriate for the container.
  3909. if ( containerName == "extends" ) {
  3910. var memberIndex = containerIndex;
  3911. var memberName = names[memberIndex];
  3912. } else if ( containerName == "implements" ) {
  3913. if ( containerIndex > 0 ) {
  3914. if ( typeof names[containerIndex-1] == "number" ) {
  3915. var memberIndex = containerIndex - 1;
  3916. var memberName = names[memberIndex];
  3917. } else {
  3918. var memberIndex = containerIndex;
  3919. var memberName = undefined;
  3920. }
  3921. } else if ( typeof object != "object" || ! ( object instanceof Array ) ) {
  3922. var memberIndex = containerIndex;
  3923. var memberName = undefined;
  3924. }
  3925. } else if ( containerName == "source" || containerName == "type" ) {
  3926. var memberIndex = containerIndex;
  3927. var memberName = names[memberIndex];
  3928. } else if ( containerName == "properties" || containerName == "methods" || containerName == "events" ||
  3929. containerName == "children" ) {
  3930. if ( containerIndex > 0 ) {
  3931. var memberIndex = containerIndex - 1;
  3932. var memberName = names[memberIndex];
  3933. }
  3934. } else if ( containerName == "scripts" ) {
  3935. if ( containerIndex > 0 ) {
  3936. if ( typeof names[containerIndex-1] == "number" ) {
  3937. var memberIndex = containerIndex - 1;
  3938. var memberName = names[memberIndex];
  3939. } else {
  3940. var memberIndex = containerIndex;
  3941. var memberName = undefined;
  3942. }
  3943. } else if ( typeof object != "object" || ! ( object instanceof Array ) ) {
  3944. var memberIndex = containerIndex;
  3945. var memberName = undefined;
  3946. }
  3947. } else {
  3948. containerIndex = undefined;
  3949. containerName = undefined;
  3950. }
  3951. }
  3952. return {
  3953. containerIndex: containerIndex,
  3954. containerName: containerName,
  3955. memberIndex: memberIndex,
  3956. memberName: memberName,
  3957. };
  3958. };
  3959. /// Locate nodes matching a search pattern. {@link module:vwf/api/kernel.find} describes the
  3960. /// supported patterns.
  3961. ///
  3962. /// This is the internal implementation used by {@link module:vwf.find} and
  3963. /// {@link module:vwf.test}.
  3964. ///
  3965. /// This function must run as a method of the kernel. Invoke it as:
  3966. /// `find.call( kernel, nodeID, matchPattern, initializedOnly )`.
  3967. ///
  3968. /// @name module:vwf~find
  3969. ///
  3970. /// @param {ID} nodeID
  3971. /// The reference node. Relative patterns are resolved with respect to this node. `nodeID`
  3972. /// is ignored for absolute patterns.
  3973. /// @param {String} matchPattern
  3974. /// The search pattern.
  3975. /// @param {Boolean} [initializedOnly]
  3976. /// Interpret nodes that haven't completed initialization as though they don't have
  3977. /// ancestors. Drivers that manage application code should set `initializedOnly` since
  3978. /// applications should never have access to uninitialized parts of the application graph.
  3979. ///
  3980. /// @returns {ID[]|undefined}
  3981. /// An array of the node ids of the result.
  3982. var find = function( nodeID, matchPattern, initializedOnly ) {
  3983. // Evaluate the expression using the provided node as the reference. Take the root node
  3984. // to be the root of the reference node's tree. If a reference node is not provided, use
  3985. // the application as the root.
  3986. var rootID = nodeID ? this.root( nodeID, initializedOnly ) :
  3987. this.application( initializedOnly );
  3988. return require( "vwf/utility" ).xpath.resolve( matchPattern, rootID, nodeID,
  3989. resolverWithInitializedOnly, this );
  3990. // Wrap `xpathResolver` to pass `initializedOnly` through.
  3991. function resolverWithInitializedOnly( step, contextID, resolveAttributes ) {
  3992. return xpathResolver.call( this, step, contextID, resolveAttributes, initializedOnly );
  3993. }
  3994. }
  3995. // -- xpathResolver ------------------------------------------------------------------------
  3996. /// Interpret the steps of an XPath expression being resolved. Use with
  3997. /// vwf.utility.xpath#resolve.
  3998. ///
  3999. /// @name module:vwf~xpathResolver
  4000. ///
  4001. /// @param {Object} step
  4002. /// @param {ID} contextID
  4003. /// @param {Boolean} [resolveAttributes]
  4004. /// @param {Boolean} [initializedOnly]
  4005. /// Interpret nodes that haven't completed initialization as though they don't have
  4006. /// ancestors. Drivers that manage application code should set `initializedOnly` since
  4007. /// applications should never have access to uninitialized parts of the application graph.
  4008. ///
  4009. /// @returns {ID[]}
  4010. var xpathResolver = function( step, contextID, resolveAttributes, initializedOnly ) {
  4011. var resultIDs = [];
  4012. switch ( step.axis ) {
  4013. // case "preceding": // TODO
  4014. // case "preceding-sibling": // TODO
  4015. case "ancestor-or-self":
  4016. resultIDs.push( contextID );
  4017. Array.prototype.push.apply( resultIDs, this.ancestors( contextID, initializedOnly ) );
  4018. break;
  4019. case "ancestor":
  4020. Array.prototype.push.apply( resultIDs, this.ancestors( contextID, initializedOnly ) );
  4021. break;
  4022. case "parent":
  4023. var parentID = this.parent( contextID, initializedOnly );
  4024. parentID && resultIDs.push( parentID );
  4025. break;
  4026. case "self":
  4027. resultIDs.push( contextID );
  4028. break;
  4029. case "child":
  4030. Array.prototype.push.apply( resultIDs,
  4031. this.children( contextID, initializedOnly ).filter( function( childID ) {
  4032. return childID;
  4033. }, this )
  4034. );
  4035. break;
  4036. case "descendant":
  4037. Array.prototype.push.apply( resultIDs,
  4038. this.descendants( contextID, initializedOnly ).filter( function( descendantID ) {
  4039. return descendantID;
  4040. }, this )
  4041. );
  4042. break;
  4043. case "descendant-or-self":
  4044. resultIDs.push( contextID );
  4045. Array.prototype.push.apply( resultIDs,
  4046. this.descendants( contextID, initializedOnly ).filter( function( descendantID ) {
  4047. return descendantID;
  4048. }, this )
  4049. );
  4050. break;
  4051. // case "following-sibling": // TODO
  4052. // case "following": // TODO
  4053. case "attribute":
  4054. if ( resolveAttributes ) {
  4055. resultIDs.push( "@" + contextID ); // TODO: @?
  4056. }
  4057. break;
  4058. // n/a: case "namespace":
  4059. // n/a: break;
  4060. }
  4061. switch ( step.kind ) {
  4062. // Name test.
  4063. case undefined:
  4064. resultIDs = resultIDs.filter( function( resultID ) {
  4065. if ( resultID[0] != "@" ) { // TODO: @?
  4066. return xpathNodeMatchesStep.call( this, resultID, step.name );
  4067. } else {
  4068. return xpathPropertyMatchesStep.call( this, resultID.slice( 1 ), step.name ); // TODO: @?
  4069. }
  4070. }, this );
  4071. break;
  4072. // Element test.
  4073. case "element":
  4074. // Cases: kind(node,type)
  4075. // element()
  4076. // element(name)
  4077. // element(,type)
  4078. // element(name,type)
  4079. resultIDs = resultIDs.filter( function( resultID ) {
  4080. return resultID[0] != "@" && xpathNodeMatchesStep.call( this, resultID, step.name, step.type ); // TODO: @?
  4081. }, this );
  4082. break;
  4083. // Attribute test.
  4084. case "attribute":
  4085. resultIDs = resultIDs.filter( function( resultID ) {
  4086. return resultID[0] == "@" && xpathPropertyMatchesStep.call( this, resultID.slice( 1 ), step.name ); // TODO: @?
  4087. }, this );
  4088. break;
  4089. // The `doc()` function for referencing globals outside the current tree.
  4090. // http://www.w3.org/TR/xpath-functions/#func-doc.
  4091. case "doc":
  4092. if ( this.root( contextID, initializedOnly ) ) {
  4093. var globalID = this.global( step.name, initializedOnly );
  4094. resultIDs = globalID ? [ globalID ] : [];
  4095. } else {
  4096. resultIDs = [];
  4097. }
  4098. break;
  4099. // Any-kind test.
  4100. case "node":
  4101. break;
  4102. // Unimplemented test.
  4103. default:
  4104. resultIDs = [];
  4105. break;
  4106. }
  4107. return resultIDs;
  4108. }
  4109. // -- xpathNodeMatchesStep -----------------------------------------------------------------
  4110. /// Determine if a node matches a step of an XPath expression being resolved.
  4111. ///
  4112. /// @name module:vwf~xpathNodeMatchesStep
  4113. ///
  4114. /// @param {ID} nodeID
  4115. /// @param {String} [name]
  4116. /// @param {String} [type]
  4117. ///
  4118. /// @returns {Boolean}
  4119. var xpathNodeMatchesStep = function( nodeID, name, type ) {
  4120. if ( name && this.name( nodeID ) != name ) {
  4121. return false;
  4122. }
  4123. var matches_type = ! type || this.uri( nodeID ) == type ||
  4124. this.prototypes( nodeID, true ).some( function( prototypeID ) {
  4125. return this.uri( prototypeID ) == type;
  4126. }, this );
  4127. return matches_type;
  4128. }
  4129. // -- xpathPropertyMatchesStep -------------------------------------------------------------
  4130. /// Determine if a property matches a step of an XPath expression being resolved.
  4131. ///
  4132. /// @name module:vwf~xpathPropertyMatchesStep
  4133. ///
  4134. /// @param {ID} nodeID
  4135. /// @param {String} [name]
  4136. ///
  4137. /// @returns {Boolean}
  4138. var xpathPropertyMatchesStep = function( nodeID, name ) {
  4139. var properties = this.models.object.properties( nodeID );
  4140. if ( name ) {
  4141. return properties[name];
  4142. } else {
  4143. return Object.keys( properties ).some( function( propertyName ) {
  4144. return properties[propertyName];
  4145. }, this );
  4146. }
  4147. }
  4148. /// Merge two component descriptors into a single descriptor for a combined component. A
  4149. /// component created from the combined descriptor will behave in the same way as a
  4150. /// component created from `nodeDescriptor` that extends a component created from
  4151. /// `prototypeDescriptor`.
  4152. ///
  4153. /// Warning: this implementation modifies `prototypeDescriptor`.
  4154. ///
  4155. /// @name module:vwf~mergeDescriptors
  4156. ///
  4157. /// @param {Object} nodeDescriptor
  4158. /// A descriptor representing a node extending `prototypeDescriptor`.
  4159. /// @param {Object} prototypeDescriptor
  4160. /// A descriptor representing a prototype for `nodeDescriptor`.
  4161. // Limitations:
  4162. //
  4163. // - Doesn't merge children from the prototype with like-named children in the node.
  4164. // - Doesn't merge property setters and getters from the prototype when the node provides
  4165. // an initializing value.
  4166. // - Methods from the prototype descriptor are lost with no way to invoke them if the node
  4167. // overrides them.
  4168. // - Scripts from both the prototype and the node are retained, but if both define an
  4169. // `initialize` function, the node's `initialize` will overwrite `initialize` in
  4170. // the prototype.
  4171. // - The prototype doesn't carry its location with it, so relative paths will load with
  4172. // respect to the location of the node.
  4173. var mergeDescriptors = function( nodeDescriptor, prototypeDescriptor ) {
  4174. if ( nodeDescriptor.implements ) {
  4175. prototypeDescriptor.implements = ( prototypeDescriptor.implements || [] ).
  4176. concat( nodeDescriptor.implements );
  4177. }
  4178. if ( nodeDescriptor.source ) {
  4179. prototypeDescriptor.source = nodeDescriptor.source;
  4180. prototypeDescriptor.type = nodeDescriptor.type;
  4181. }
  4182. if ( nodeDescriptor.properties ) {
  4183. prototypeDescriptor.properties = prototypeDescriptor.properties || {};
  4184. for ( var propertyName in nodeDescriptor.properties ) {
  4185. prototypeDescriptor.properties[propertyName] = nodeDescriptor.properties[propertyName];
  4186. }
  4187. }
  4188. if ( nodeDescriptor.methods ) {
  4189. prototypeDescriptor.methods = prototypeDescriptor.methods || {};
  4190. for ( var methodName in nodeDescriptor.methods ) {
  4191. prototypeDescriptor.methods[methodName] = nodeDescriptor.methods[methodName];
  4192. }
  4193. }
  4194. if ( nodeDescriptor.events ) {
  4195. prototypeDescriptor.events = prototypeDescriptor.events || {};
  4196. for ( var eventName in nodeDescriptor.events ) {
  4197. prototypeDescriptor.events[eventName] = nodeDescriptor.events[eventName];
  4198. }
  4199. }
  4200. if ( nodeDescriptor.children ) {
  4201. prototypeDescriptor.children = prototypeDescriptor.children || {};
  4202. for ( var childName in nodeDescriptor.children ) {
  4203. prototypeDescriptor.children[childName] = nodeDescriptor.children[childName];
  4204. }
  4205. }
  4206. if ( nodeDescriptor.scripts ) {
  4207. prototypeDescriptor.scripts = ( prototypeDescriptor.scripts || [] ).
  4208. concat( nodeDescriptor.scripts );
  4209. }
  4210. return prototypeDescriptor;
  4211. };
  4212. /// Return an {@link external:Object.defineProperty} descriptor for a property that is to be
  4213. /// enumerable, but not writable or configurable.
  4214. ///
  4215. /// @param value
  4216. /// A value to wrap in a descriptor.
  4217. ///
  4218. /// @returns
  4219. /// An {@link external:Object.defineProperty} descriptor.
  4220. var enumerable = function( value ) {
  4221. return {
  4222. value: value,
  4223. enumerable: true,
  4224. writable: false,
  4225. configurable: false,
  4226. };
  4227. };
  4228. /// Return an {@link external:Object.defineProperty} descriptor for a property that is to be
  4229. /// enumerable and writable, but not configurable.
  4230. ///
  4231. /// @param value
  4232. /// A value to wrap in a descriptor.
  4233. ///
  4234. /// @returns
  4235. /// An {@link external:Object.defineProperty} descriptor.
  4236. var writable = function( value ) {
  4237. return {
  4238. value: value,
  4239. enumerable: true,
  4240. writable: true,
  4241. configurable: false,
  4242. };
  4243. };
  4244. /// Return an {@link external:Object.defineProperty} descriptor for a property that is to be
  4245. /// enumerable, writable, and configurable.
  4246. ///
  4247. /// @param value
  4248. /// A value to wrap in a descriptor.
  4249. ///
  4250. /// @returns
  4251. /// An {@link external:Object.defineProperty} descriptor.
  4252. var configurable = function( value ) {
  4253. return {
  4254. value: value,
  4255. enumerable: true,
  4256. writable: true,
  4257. configurable: true,
  4258. };
  4259. };
  4260. // == Private variables ====================================================================
  4261. /// Prototype for name-based, unordered collections in the node registry, including
  4262. /// `node.properties`, `node.methods`, and `node.events`.
  4263. var keyedCollectionPrototype = {
  4264. /// Record that a property, method or event has been created.
  4265. ///
  4266. /// @param {String} name
  4267. /// The member name.
  4268. /// @param {Boolean} changes
  4269. /// For patchable nodes, record changes so that `kernel.getNode` may create a patch
  4270. /// when retrieving the node.
  4271. /// @param [value]
  4272. /// An optional value to assign to the record. If `value` is omitted, the record will
  4273. /// exist in the collection but have the value `undefined`.
  4274. ///
  4275. /// @returns {Boolean}
  4276. /// `true` if the member was successfully added. `false` if a member by that name
  4277. /// already exists.
  4278. create: function( name, changes, value ) {
  4279. if ( ! this.hasOwn( name ) ) {
  4280. this.makeOwn( "existing" );
  4281. // Add the member. `Object.defineProperty` is used instead of
  4282. // `this.existing[name] = ...` since the prototype may be a behavior proxy, and
  4283. // the accessor properties would prevent normal assignment.
  4284. Object.defineProperty( this.existing, name,
  4285. configurable( value ? value : undefined ) );
  4286. if ( changes ) {
  4287. this.makeOwn( "changes" );
  4288. if ( this.changes[ name ] !== "removed" ) {
  4289. this.changes[ name ] = "added";
  4290. } else {
  4291. this.changes[ name ] = "changed"; // previously removed, then added
  4292. }
  4293. if ( this.container && this.containerMember ) {
  4294. this.container.change( this.containerMember );
  4295. }
  4296. }
  4297. return true;
  4298. }
  4299. return false;
  4300. },
  4301. /// Record that a member has been deleted.
  4302. ///
  4303. /// @param {String} name
  4304. /// The member name.
  4305. ///
  4306. /// @returns {Boolean}
  4307. /// `true` if the member was successfully removed. `false` if a member by that name
  4308. /// does not exist.
  4309. delete: function( name, changes ) {
  4310. if ( this.hasOwn( name ) ) {
  4311. delete this.existing[ name ];
  4312. if ( changes ) {
  4313. this.makeOwn( "changes" );
  4314. if ( this.changes[ name ] !== "added" ) {
  4315. this.changes[ name ] = "removed";
  4316. } else {
  4317. delete this.changes[ name ]; // previously added, then removed
  4318. }
  4319. if ( this.container && this.containerMember ) {
  4320. this.container.change( this.containerMember );
  4321. }
  4322. }
  4323. return true;
  4324. }
  4325. return false;
  4326. },
  4327. /// Record that a member has changed.
  4328. ///
  4329. /// @param {String} name
  4330. /// The member name.
  4331. ///
  4332. /// @returns {Boolean}
  4333. /// `true` if the change was successfully recorded. `false` if a member by that name
  4334. /// does not exist.
  4335. change: function( name, value ) {
  4336. if ( this.hasOwn( name ) ) {
  4337. this.makeOwn( "changes" );
  4338. if ( this.changes[ name ] !== "added" ) {
  4339. this.changes[ name ] = value ?
  4340. value : this.changes[ name ] || "changed";
  4341. }
  4342. if ( this.container && this.containerMember ) {
  4343. this.container.change( this.containerMember );
  4344. }
  4345. return true;
  4346. }
  4347. return false;
  4348. },
  4349. /// Determine if a node has a member with the given name, either directly on the node or
  4350. /// inherited from a prototype.
  4351. ///
  4352. /// @param {String} name
  4353. /// The member name.
  4354. ///
  4355. /// @returns {Boolean}
  4356. has: function( name ) {
  4357. return name in this.existing;
  4358. },
  4359. /// Determine if a node has a member with the given name. The node's prototypes are not
  4360. /// considered.
  4361. ///
  4362. /// @param {String} name
  4363. /// The member name.
  4364. ///
  4365. /// @returns {Boolean}
  4366. // Since prototypes of the collection objects mirror the node's prototype chain,
  4367. // collection objects for the proto-prototype `node.vwf` intentionally don't inherit
  4368. // from `Object.prototype`. Otherwise the Object members `hasOwnProperty`,
  4369. // `isPrototypeOf`, etc. would be mistaken as members of a VWF node.
  4370. // Instead of using the simpler `this.existing.hasOwnProperty( name )`, we must reach
  4371. // `hasOwnProperty through `Object.prototype`.
  4372. hasOwn: function( name ) {
  4373. return Object.prototype.hasOwnProperty.call( this.existing, name );
  4374. },
  4375. /// Hoist a field from a prototype to the collection in preparation for making local
  4376. /// changes.
  4377. ///
  4378. /// If the field in the prototype is an object, create a new object with that field as
  4379. /// its prototype. If the field in the prototype is an array, clone the field since
  4380. /// arrays can't readily serve as prototypes for other arrays. In other cases, copy the
  4381. /// field from the prototype. Only objects, arrays and primitive values are supported.
  4382. ///
  4383. /// @param {String} fieldName
  4384. /// The name of a field to hoist from the collection's prototype.
  4385. makeOwn: function( fieldName ) {
  4386. if ( ! this.hasOwnProperty( fieldName ) ) {
  4387. if ( this[ fieldName ] instanceof Array ) {
  4388. this[ fieldName ] = this[ fieldName ].slice(); // clone arrays
  4389. } else if ( typeof this[ fieldName ] === "object" && this[ fieldName ] !== null ) {
  4390. this[ fieldName ] = Object.create( this[ fieldName ] ); // inherit from objects
  4391. } else {
  4392. this[ fieldName ] = this[ fieldName ]; // copy primitives
  4393. }
  4394. }
  4395. },
  4396. /// The property, method, or event members defined in this collection.
  4397. ///
  4398. /// `existing` is an unordered collection of elements and optional values. The keys are
  4399. /// the primary data. Existence on the object is significant regardless of the value.
  4400. /// Some collections store data in the element when the kernel owns additional details
  4401. /// about the member. Values will be `undefined` in other collections.
  4402. ///
  4403. /// For each collection, `existing` is the authoritative list of the node's members. Use
  4404. /// `collection.hasOwn( memberName )` to determine if the node defines a property,
  4405. /// method or event by that name.
  4406. ///
  4407. /// The prototype of each `existing` object will be the `existing` object of the node's
  4408. /// prototype (or a proxy to the top behavior for nodes with behaviors). Use
  4409. /// `collection.has( memberName )` to determine if a property, method or event is
  4410. /// defined on the node or its prototypes.
  4411. existing: Object.create( null
  4412. // name: undefined,
  4413. // name: { ... } -- details
  4414. // ...
  4415. ),
  4416. /// The change list for members in this collection.
  4417. ///
  4418. /// For patchable nodes, `changes` records the members that have been added, removed, or
  4419. /// changed since the node was first initialized. `changes` is not created in the
  4420. /// collection until the first change occurs. Only the change is recorded here. The
  4421. /// state behind the change is retrieved from the drivers when needed.
  4422. changes: {
  4423. // name: "added"
  4424. // name: "removed"
  4425. // name: "changed"
  4426. // name: { ... } -- changed, with details
  4427. // ...
  4428. },
  4429. /// The parent collection if this collection is a member of another. Changes applied to
  4430. /// members of this collection will call `container.change( containerMember )` to also
  4431. /// set the change flag for the containing member.
  4432. ///
  4433. /// For example, members of the `node.events` collection contain listener collections at
  4434. /// `node.events.existing[name].listeners`. Each listener collection knows its event
  4435. /// name and points back to `node.events`. Changing a listener will call
  4436. /// `node.events.change( name )` to mark the event as changed.
  4437. container: undefined,
  4438. /// This collection's name in the parent if this collection is a member of another
  4439. /// collection. Changes to members of this collection will mark that member changed in
  4440. /// the containing collection.
  4441. containerMember: undefined,
  4442. };
  4443. /// Prototype for index-based, ordered collections in the node registry, including
  4444. /// `event.listeners`.
  4445. var indexedCollectionPrototype = {
  4446. /// Record that a member has been created.
  4447. ///
  4448. /// @param {string|number|boolean|null} id
  4449. /// The member's unique id.
  4450. /// @param {Boolean} changes
  4451. /// For patchable nodes, record changes so that `kernel.getNode` may create a patch
  4452. /// when retrieving the node.
  4453. ///
  4454. /// @returns {Boolean}
  4455. /// `true` if the member was successfully added. `false` if a member with that id
  4456. /// already exists.
  4457. create: function( id, changes ) {
  4458. if ( ! this.hasOwn( id ) ) {
  4459. this.makeOwn( "existing" );
  4460. this.existing.push( id );
  4461. if ( changes ) {
  4462. this.makeOwn( "changes" );
  4463. var removedIndex = this.changes.removed ?
  4464. this.changes.removed.indexOf( id ) : -1;
  4465. if ( removedIndex < 0 ) {
  4466. this.changes.added = this.changes.added || [];
  4467. this.changes.added.push( id );
  4468. } else {
  4469. this.changes.removed.splice( removedIndex, 1 );
  4470. this.changes.changed = this.changes.changed || [];
  4471. this.changes.changed.push( id );
  4472. }
  4473. if ( this.container && this.containerMember ) {
  4474. this.container.change( this.containerMember );
  4475. }
  4476. }
  4477. return true;
  4478. }
  4479. return false;
  4480. },
  4481. /// Record that a member has been deleted.
  4482. ///
  4483. /// @param {string|number|boolean|null} id
  4484. /// The member's unique id.
  4485. ///
  4486. /// @returns {Boolean}
  4487. /// `true` if the member was successfully removed. `false` if a member with that id
  4488. /// does not exist.
  4489. delete: function( id, changes ) {
  4490. if ( this.hasOwn( id ) ) {
  4491. this.existing.splice( this.existing.indexOf( id ), 1 );
  4492. if ( changes ) {
  4493. this.makeOwn( "changes" );
  4494. var addedIndex = this.changes.added ?
  4495. this.changes.added.indexOf( id ) : -1;
  4496. if ( addedIndex < 0 ) {
  4497. this.changes.removed = this.changes.removed || [];
  4498. this.changes.removed.push( id );
  4499. } else {
  4500. this.changes.added.splice( addedIndex, 1 );
  4501. }
  4502. if ( this.container && this.containerMember ) {
  4503. this.container.change( this.containerMember );
  4504. }
  4505. }
  4506. return true;
  4507. }
  4508. return false;
  4509. },
  4510. /// Record that a member has changed.
  4511. ///
  4512. /// @param {string|number|boolean|null} id
  4513. /// The member's unique id.
  4514. ///
  4515. /// @returns {Boolean}
  4516. /// `true` if the change was successfully recorded. `false` if a member with that id
  4517. /// does not exist.
  4518. change: function( id ) {
  4519. if ( this.hasOwn( id ) ) {
  4520. this.makeOwn( "changes" );
  4521. var addedIndex = this.changes.added ?
  4522. this.changes.added.indexOf( id ) : -1;
  4523. var changedIndex = this.changes.changed ?
  4524. this.changes.changed.indexOf( id ) : -1;
  4525. if ( addedIndex < 0 && changedIndex < 0 ) {
  4526. this.changes.changed = this.changes.changed || [];
  4527. this.changes.changed.push( id );
  4528. }
  4529. if ( this.container && this.containerMember ) {
  4530. this.container.change( this.containerMember );
  4531. }
  4532. return true;
  4533. }
  4534. return false;
  4535. },
  4536. /// Determine if a node has a member with the given id.
  4537. ///
  4538. /// `has` is the same as `hasOwn` for `indexedCollectionPrototype` since index-based
  4539. /// collections don't automatically inherit from their prototypes.
  4540. ///
  4541. /// @param {string|number|boolean|null} id
  4542. /// The member's unique id.
  4543. ///
  4544. /// @returns {Boolean}
  4545. has: function( id ) {
  4546. return this.hasOwn( id );
  4547. },
  4548. /// Determine if a node has a member with the given id. The node's prototypes are not
  4549. /// considered.
  4550. ///
  4551. /// @param {string|number|boolean|null} id
  4552. /// The member's unique id.
  4553. ///
  4554. /// @returns {Boolean}
  4555. hasOwn: function( id ) {
  4556. return this.existing ? this.existing.indexOf( id ) >= 0 : false;
  4557. },
  4558. /// Hoist a field from a prototype to the collection in preparation for making local
  4559. /// changes.
  4560. ///
  4561. /// If the field in the prototype is an object, create a new object with that field as
  4562. /// its prototype. If the field in the prototype is an array, clone the field since
  4563. /// arrays can't readily serve as prototypes for other arrays. In other cases, copy the
  4564. /// field from the prototype. Only objects, arrays and primitive values are supported.
  4565. ///
  4566. /// @param {String} fieldName
  4567. /// The name of a field to hoist from the collection's prototype.
  4568. makeOwn: function( fieldName ) {
  4569. if ( ! this.hasOwnProperty( fieldName ) ) {
  4570. if ( this[ fieldName ] instanceof Array ) {
  4571. this[ fieldName ] = this[ fieldName ].slice(); // clone arrays
  4572. } else if ( typeof this[ fieldName ] === "object" && this[ fieldName ] !== null ) {
  4573. this[ fieldName ] = Object.create( this[ fieldName ] ); // inherit from objects
  4574. } else {
  4575. this[ fieldName ] = this[ fieldName ]; // copy primitives
  4576. }
  4577. }
  4578. },
  4579. /// IDs of the members defined in this collection.
  4580. ///
  4581. /// `existing` is an ordered list of IDs, which much be unique within the collection.
  4582. /// The IDs retain the order in which they were originally added.
  4583. ///
  4584. /// For each collection, `existing` is the authoritative list of the node's members. Use
  4585. /// `collection.hasOwn( memberID )` to determine if the collection contains a member
  4586. /// with that id. Unlike `keyedCollectionPrototype` collections,
  4587. /// `indexedCollectionPrototype` collections aren't connected in parallel with their
  4588. /// containers' prototype chains.
  4589. existing: [
  4590. // id,
  4591. // id,
  4592. // ...
  4593. ],
  4594. /// The change list for members in this collection.
  4595. ///
  4596. /// For patchable nodes, `changes` records the members that have been added, removed, or
  4597. /// changed since the node was first initialized. Changes are recorded in separate
  4598. /// `added`, `removed`, and `changed` arrays, respectively. The `added` array retains
  4599. /// the order in which the members were added. Although `removed` and `changed` are also
  4600. /// arrays, the order of removals and changes is not significant.
  4601. ///
  4602. /// `changes` is not created in the collection until the first change occurs. Only the
  4603. /// change is recorded here. The state behind the change is retrieved from the drivers
  4604. /// when needed.
  4605. changes: {
  4606. // added: [ id, ... ],
  4607. // removed: [ id, ... ],
  4608. // changed: [ id, ... ],
  4609. },
  4610. /// The parent collection if this collection is a member of another. Changes applied to
  4611. /// members of this collection will call `container.change( containerMember )` to also
  4612. /// set the change flag for the containing member.
  4613. ///
  4614. /// For example, members of the `node.events` collection contain listener collections at
  4615. /// `node.events.existing[name].listeners`. Each listener collection knows its event
  4616. /// name and points back to `node.events`. Changing a listener will call
  4617. /// `node.events.change( name )` to mark the event as changed.
  4618. container: undefined,
  4619. /// This collection's name in the parent if this collection is a member of another
  4620. /// collection. Changes to members of this collection will mark that member changed in
  4621. /// the containing collection.
  4622. containerMember: undefined,
  4623. };
  4624. // Prototype for the `events` collection in the `nodes` objects.
  4625. var eventCollectionPrototype = Object.create( keyedCollectionPrototype, {
  4626. create: {
  4627. value: function( name, changes, parameters ) {
  4628. var value = parameters ? {
  4629. parameters: parameters.slice(), // clone
  4630. } : {};
  4631. value.listeners = Object.create( indexedCollectionPrototype, {
  4632. container: enumerable( this ),
  4633. containerMember: enumerable( name ),
  4634. } );
  4635. return keyedCollectionPrototype.create.call( this, name, changes, value );
  4636. }
  4637. },
  4638. } );
  4639. /// The application's nodes, indexed by ID.
  4640. ///
  4641. /// The kernel defines an application as:
  4642. ///
  4643. /// * A tree of nodes,
  4644. /// * Extending prototypes and implementing behaviors,
  4645. /// * Publishing properties, and
  4646. /// * Communicating using methods and events.
  4647. ///
  4648. /// This definition is as abstract as possible to avoid imposing unnecessary policy on the
  4649. /// application. The concrete realization of these concepts lives in the hearts and minds of
  4650. /// the drivers configured for the application. `nodes` contains the kernel's authoritative
  4651. /// data about this arrangement.
  4652. ///
  4653. /// @name module:vwf~nodes
  4654. // Note: this is a first step towards moving authoritative data out of the vwf/model/object
  4655. // and vwf/model/javascript drivers and removing the kernel's dependency on them as special
  4656. // cases. Only `nodes.existing[id].properties` is currently implemented this way.
  4657. var nodes = {
  4658. /// Register a node as it is created.
  4659. ///
  4660. /// @param {ID} nodeID
  4661. /// The ID assigned to the new node. The node will be indexed in `nodes` by this ID.
  4662. /// @param {ID} prototypeID
  4663. /// The ID of the node's prototype, or `undefined` if this is the proto-prototype,
  4664. /// `node.vwf`.
  4665. /// @param {ID[]} behaviorIDs
  4666. /// An array of IDs of the node's behaviors. `behaviorIDs` should be an empty array if
  4667. /// the node doesn't have any behaviors.
  4668. /// @param {String} nodeURI
  4669. /// The node's URI. `nodeURI` should be the component URI if this is the root node of
  4670. /// a component loaded from a URI, and undefined in all other cases.
  4671. /// @param {String} nodeName
  4672. /// The node's name.
  4673. /// @param {ID} parentID
  4674. /// The ID of the node's parent, or `undefined` if this is the application root node
  4675. /// or another global, top-level node.
  4676. ///
  4677. /// @returns {Object}
  4678. /// The kernel `node` object if the node was successfully added. `undefined` if a node
  4679. /// identified by `nodeID` already exists.
  4680. create: function( nodeID, prototypeID, behaviorIDs, nodeURI, nodeName, parentID ) {
  4681. // if ( ! this.existing[nodeID] ) {
  4682. var self = this;
  4683. var prototypeNode = behaviorIDs.reduce( function( prototypeNode, behaviorID ) {
  4684. return self.proxy( prototypeNode, self.existing[behaviorID] );
  4685. }, this.existing[prototypeID] );
  4686. // Look up the parent.
  4687. var parentNode = this.existing[parentID];
  4688. // If this is the global root of a new tree, add it to the `globals` set.
  4689. if ( ! parentNode ) {
  4690. this.globals[nodeID] = undefined;
  4691. }
  4692. // Add the node to the registry.
  4693. return this.existing[nodeID] = {
  4694. // id: ...,
  4695. // Inheritance. -- not implemented here yet; still using vwf/model/object
  4696. // prototype: ...,
  4697. // behaviors: [],
  4698. // Intrinsic state. -- not implemented here yet.
  4699. // source: ...,
  4700. // type: ...,
  4701. uri: nodeURI,
  4702. name: nodeName,
  4703. // Internal state. The change flags are omitted until needed. -- not implemented here yet; still using vwf/model/object
  4704. // sequence: ...,
  4705. // sequenceChanged: true / false,
  4706. // prng: ...,
  4707. // prngChanged: true / false,
  4708. // Tree. -- not implemented here yet; still using vwf/model/object
  4709. // parent: ...,
  4710. // children: [],
  4711. // Property, Method and Event members defined on the node.
  4712. properties: Object.create( keyedCollectionPrototype, {
  4713. existing: enumerable( Object.create( prototypeNode ?
  4714. prototypeNode.properties.existing : null ) ),
  4715. } ),
  4716. methods: Object.create( keyedCollectionPrototype, {
  4717. existing: enumerable( Object.create( prototypeNode ?
  4718. prototypeNode.methods.existing : null ) ),
  4719. } ),
  4720. events: Object.create( eventCollectionPrototype, {
  4721. existing: enumerable( Object.create( prototypeNode ?
  4722. prototypeNode.events.existing : null ) ),
  4723. } ),
  4724. // Is this node patchable? Nodes are patchable if they were loaded from a
  4725. // component.
  4726. patchable: !! ( nodeURI ||
  4727. parentNode && ! parentNode.initialized && parentNode.patchable ),
  4728. // Has this node completed initialization? For applications, visibility to
  4729. // ancestors from uninitialized nodes is blocked. Change tracking starts
  4730. // after initialization.
  4731. initialized: false,
  4732. };
  4733. // } else {
  4734. // return undefined;
  4735. // }
  4736. },
  4737. /// Record that a node has initialized.
  4738. initialize: function( nodeID ) {
  4739. if ( this.existing[nodeID] ) {
  4740. this.existing[nodeID].initialized = true;
  4741. return true;
  4742. }
  4743. return false;
  4744. },
  4745. /// Unregister a node as it is deleted.
  4746. delete: function( nodeID ) {
  4747. if ( this.existing[nodeID] ) {
  4748. delete this.existing[nodeID];
  4749. delete this.globals[nodeID];
  4750. return true;
  4751. }
  4752. return false;
  4753. },
  4754. /// Create a proxy node in the form of the nodes created by `nodes.create` to represent
  4755. /// a behavior node in another node's prototype chain. The `existing` objects of the
  4756. /// proxy's collections link to the prototype collection's `existing` objects, just as
  4757. /// with a regular prototype. The proxy's members delegate to the corresponding members
  4758. /// in the behavior.
  4759. proxy: function( prototypeNode, behaviorNode ) {
  4760. return {
  4761. properties: {
  4762. existing: Object.create(
  4763. prototypeNode ? prototypeNode.properties.existing : null,
  4764. propertyDescriptorsFor( behaviorNode.properties.existing )
  4765. ),
  4766. },
  4767. methods: {
  4768. existing: Object.create(
  4769. prototypeNode ? prototypeNode.methods.existing : null,
  4770. propertyDescriptorsFor( behaviorNode.methods.existing )
  4771. ),
  4772. },
  4773. events: {
  4774. existing: Object.create(
  4775. prototypeNode ? prototypeNode.events.existing : null,
  4776. propertyDescriptorsFor( behaviorNode.events.existing )
  4777. ),
  4778. },
  4779. };
  4780. /// Return an `Object.create` properties object for a proxy object for the provided
  4781. /// collection's `existing` object.
  4782. function propertyDescriptorsFor( collectionExisting ) {
  4783. return Object.keys( collectionExisting ).reduce(
  4784. function( propertiesObject, memberName ) {
  4785. propertiesObject[memberName] = {
  4786. get: function() { return collectionExisting[memberName] },
  4787. enumerable: true,
  4788. };
  4789. return propertiesObject;
  4790. },
  4791. {}
  4792. );
  4793. }
  4794. },
  4795. /// Registry of all nodes, indexed by ID. Each is an object created by `nodes.create`.
  4796. existing: {
  4797. // id: {
  4798. // id: ...,
  4799. // uri: ...,
  4800. // name: ...,
  4801. // ...
  4802. // }
  4803. },
  4804. /// Global root nodes. Each of these is the root of a tree.
  4805. ///
  4806. /// The `globals` object is a set: the keys are the data, and only existence on the
  4807. /// object is significant.
  4808. globals: {
  4809. // id: undefined,
  4810. },
  4811. };
  4812. /// Control messages from the reflector are stored here in a priority queue, ordered by
  4813. /// execution time.
  4814. ///
  4815. /// @name module:vwf~queue
  4816. var queue = this.private.queue = {
  4817. /// Insert a message or messages into the queue. Optionally execute the simulation
  4818. /// through the time marked on the message.
  4819. ///
  4820. /// When chronic (chron-ic) is set, vwf#dispatch is called to execute the simulation up
  4821. /// through the indicated time. To prevent actions from executing out of order, insert
  4822. /// should be the caller's last operation before returning to the host when invoked with
  4823. /// chronic.
  4824. ///
  4825. /// @name module:vwf~queue.insert
  4826. ///
  4827. /// @param {Object|Object[]} fields
  4828. /// @param {Boolean} [chronic]
  4829. insert: function( fields, chronic ) {
  4830. var messages = fields instanceof Array ? fields : [ fields ];
  4831. messages.forEach( function( fields ) {
  4832. // if ( fields.action ) { // TODO: don't put ticks on the queue but just use them to fast-forward to the current time (requires removing support for passing ticks to the drivers and nodes)
  4833. fields.sequence = ++this.sequence; // track the insertion order for use as a sort key
  4834. this.queue.push( fields );
  4835. // }
  4836. if ( chronic ) {
  4837. this.time = Math.max( this.time, fields.time ); // save the latest allowed time for suspend/resume
  4838. }
  4839. }, this );
  4840. // Sort by time, then future messages ahead of reflector messages, then by sequence. // TODO: we probably want a priority queue here for better performance
  4841. //
  4842. // The sort by origin ensures that the queue is processed in a well-defined order
  4843. // when future messages and reflector messages share the same time, even if the
  4844. // reflector message has not arrived at the client yet.
  4845. //
  4846. // The sort by sequence number ensures that the messages remain in their arrival
  4847. // order when the earlier sort keys don't provide the order.
  4848. this.queue.sort( function( a, b ) {
  4849. if ( a.time != b.time ) {
  4850. return a.time - b.time;
  4851. } else if ( a.origin != "reflector" && b.origin == "reflector" ) {
  4852. return -1;
  4853. } else if ( a.origin == "reflector" && b.origin != "reflector" ) {
  4854. return 1;
  4855. } else {
  4856. return a.sequence - b.sequence;
  4857. }
  4858. } );
  4859. // Execute the simulation through the new time.
  4860. // To prevent actions from executing out of order, callers should immediately return
  4861. // to the host after invoking insert with chronic set.
  4862. if ( chronic ) {
  4863. vwf.dispatch();
  4864. }
  4865. },
  4866. /// Pull the next message from the queue.
  4867. ///
  4868. /// @name module:vwf~queue.pull
  4869. ///
  4870. /// @returns {Object|undefined} The next message if available, otherwise undefined.
  4871. pull: function() {
  4872. if ( this.suspension == 0 && this.queue.length > 0 && this.queue[0].time <= this.time ) {
  4873. return this.queue.shift();
  4874. }
  4875. },
  4876. /// Update the queue to include only the messages selected by a filtering function.
  4877. ///
  4878. /// @name module:vwf~queue.filter
  4879. ///
  4880. /// @param {Function} callback
  4881. /// `filter` calls `callback( fields )` once for each message in the queue. If
  4882. /// `callback` returns a truthy value, the message will be retained. Otherwise it will
  4883. /// be removed from the queue.
  4884. filter: function( callback /* fields */ ) {
  4885. this.queue = this.queue.filter( callback );
  4886. },
  4887. /// Suspend message execution.
  4888. ///
  4889. /// @name module:vwf~queue.suspend
  4890. ///
  4891. /// @returns {Boolean} true if the queue was suspended by this call.
  4892. suspend: function( why ) {
  4893. if ( this.suspension++ == 0 ) {
  4894. vwf.logger.infox( "-queue#suspend", "suspending queue at time", vwf.now, why ? why : "" );
  4895. return true;
  4896. } else {
  4897. vwf.logger.debugx( "-queue#suspend", "further suspending queue at time", vwf.now, why ? why : "" );
  4898. return false;
  4899. }
  4900. },
  4901. /// Resume message execution.
  4902. ///
  4903. /// vwf#dispatch may be called to continue the simulation. To prevent actions from
  4904. /// executing out of order, resume should be the caller's last operation before
  4905. /// returning to the host.
  4906. ///
  4907. /// @name module:vwf~queue.resume
  4908. ///
  4909. /// @returns {Boolean} true if the queue was resumed by this call.
  4910. resume: function( why ) {
  4911. if ( --this.suspension == 0 ) {
  4912. vwf.logger.infox( "-queue#resume", "resuming queue at time", vwf.now, why ? why : "" );
  4913. vwf.dispatch();
  4914. return true;
  4915. } else {
  4916. vwf.logger.debugx( "-queue#resume", "partially resuming queue at time", vwf.now, why ? why : "" );
  4917. return false;
  4918. }
  4919. },
  4920. /// Return the ready state of the queue.
  4921. ///
  4922. /// @name module:vwf~queue.ready
  4923. ///
  4924. /// @returns {Boolean}
  4925. ready: function() {
  4926. return this.suspension == 0;
  4927. },
  4928. /// Current time as provided by the reflector. Messages to be executed at this time or
  4929. /// earlier are available from #pull.
  4930. ///
  4931. /// @name module:vwf~queue.time
  4932. time: 0,
  4933. /// Suspension count. Queue processing is suspended when suspension is greater than 0.
  4934. ///
  4935. /// @name module:vwf~queue.suspension
  4936. suspension: 0,
  4937. /// Sequence counter for tagging messages by order of arrival. Messages are sorted by
  4938. /// time, origin, then by arrival order.
  4939. ///
  4940. /// @name module:vwf~queue.sequence
  4941. sequence: 0,
  4942. /// Array containing the messages in the queue.
  4943. ///
  4944. /// @name module:vwf~queue.queue
  4945. queue: [],
  4946. };
  4947. };
  4948. } ) ( window );