vwf.js 286 KB

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