vwf.js 287 KB

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