vwf.js 287 KB

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