vwf.js 286 KB

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