vwf.js 277 KB

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