vwf.js 282 KB

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