vwf.js 277 KB

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