vwf.js 283 KB

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