vwf.js 288 KB

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