vwf.js 286 KB

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