vwf.js 291 KB

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