vwf.js 288 KB

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