vwf.js 282 KB

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