vwf.js 287 KB

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