vwf.js 290 KB

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