vwf.js 279 KB

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