vwf.js 286 KB

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