vwf.js 286 KB

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