vwf.js 287 KB

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