vwf.js 289 KB

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