vwf.js 286 KB

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