vwf.js 289 KB

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