vwf.js 290 KB

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