vwf.js 288 KB

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