vwf.js 277 KB

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