vwf.js 277 KB

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