vwf.js 287 KB

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