2
0

view.js 259 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182
  1. import * as base from './base.js';
  2. import * as zip from './zip.js';
  3. import * as tar from './tar.js';
  4. import * as json from './json.js';
  5. import * as xml from './xml.js';
  6. import * as protobuf from './protobuf.js';
  7. import * as flatbuffers from './flatbuffers.js';
  8. import * as hdf5 from './hdf5.js';
  9. import * as python from './python.js';
  10. import * as grapher from './grapher.js';
  11. const view = {};
  12. const markdown = {};
  13. view.View = class {
  14. constructor(host) {
  15. this._host = host;
  16. this._defaultOptions = {
  17. weights: true,
  18. attributes: false,
  19. names: false,
  20. direction: 'vertical',
  21. mousewheel: 'scroll'
  22. };
  23. this._options = { ...this._defaultOptions };
  24. this._model = null;
  25. this._stack = [];
  26. this._selection = [];
  27. this._sidebar = new view.Sidebar(this._host);
  28. this._find = null;
  29. this._modelFactoryService = new view.ModelFactoryService(this._host);
  30. this._modelFactoryService.import();
  31. this._worker = new view.Worker(this._host);
  32. }
  33. async start() {
  34. try {
  35. await zip.Archive.import();
  36. await this._host.view(this);
  37. const options = this._host.get('options') || {};
  38. for (const [name, value] of Object.entries(options)) {
  39. this._options[name] = value;
  40. }
  41. this._element('sidebar-button').addEventListener('click', () => {
  42. this.showModelProperties();
  43. });
  44. this._element('zoom-in-button').addEventListener('click', () => {
  45. this.zoomIn();
  46. });
  47. this._element('zoom-out-button').addEventListener('click', () => {
  48. this.zoomOut();
  49. });
  50. this._element('toolbar-path-back-button').addEventListener('click', async () => {
  51. await this.popGraph();
  52. });
  53. this._element('sidebar').addEventListener('mousewheel', (e) => {
  54. if (e.shiftKey || e.ctrlKey) {
  55. e.preventDefault();
  56. }
  57. }, { passive: true });
  58. this._host.document.addEventListener('keydown', () => {
  59. if (this._graph) {
  60. this._graph.select(null);
  61. }
  62. });
  63. if (this._host.type === 'Electron') {
  64. this._host.update({ 'can-copy': false });
  65. this._host.document.addEventListener('selectionchange', () => {
  66. const selection = this._host.document.getSelection();
  67. const selected = selection.rangeCount === 0 || selection.toString().trim() !== '';
  68. this._host.update({ 'can-copy': selected });
  69. });
  70. }
  71. const platform = this._host.environment('platform');
  72. this._menu = new view.Menu(this._host);
  73. this._menu.add({
  74. accelerator: platform === 'darwin' ? 'Ctrl+Cmd+F' : 'F11',
  75. execute: () => this._host.execute('fullscreen')
  76. });
  77. this._menu.add({
  78. accelerator: 'Backspace',
  79. execute: async () => await this.popGraph()
  80. });
  81. if (this._host.environment('menu')) {
  82. this._menu.attach(this._element('menu'), this._element('menu-button'));
  83. const file = this._menu.group('&File');
  84. file.add({
  85. label: '&Open...',
  86. accelerator: 'CmdOrCtrl+O',
  87. execute: () => this._host.execute('open')
  88. });
  89. if (this._host.type === 'Electron') {
  90. this._recents = file.group('Open &Recent');
  91. file.add({
  92. label: '&Export...',
  93. accelerator: 'CmdOrCtrl+Shift+E',
  94. execute: () => this._host.execute('export'),
  95. enabled: () => this.activeGraph
  96. });
  97. file.add({
  98. label: platform === 'darwin' ? '&Close Window' : '&Close',
  99. accelerator: 'CmdOrCtrl+W',
  100. execute: () => this._host.execute('close'),
  101. });
  102. file.add({
  103. label: platform === 'win32' ? 'E&xit' : '&Quit',
  104. accelerator: platform === 'win32' ? '' : 'CmdOrCtrl+Q',
  105. execute: () => this._host.execute('quit'),
  106. });
  107. } else {
  108. file.add({
  109. label: 'Export as &PNG',
  110. accelerator: 'CmdOrCtrl+Shift+E',
  111. execute: async () => await this.export(`${this._host.document.title}.png`),
  112. enabled: () => this.activeGraph
  113. });
  114. file.add({
  115. label: 'Export as &SVG',
  116. accelerator: 'CmdOrCtrl+Alt+E',
  117. execute: async () => await this.export(`${this._host.document.title}.svg`),
  118. enabled: () => this.activeGraph
  119. });
  120. }
  121. const edit = this._menu.group('&Edit');
  122. edit.add({
  123. label: '&Find...',
  124. accelerator: 'CmdOrCtrl+F',
  125. execute: () => this.find(),
  126. enabled: () => this.activeGraph
  127. });
  128. const view = this._menu.group('&View');
  129. view.add({
  130. label: () => this.options.attributes ? 'Hide &Attributes' : 'Show &Attributes',
  131. accelerator: 'CmdOrCtrl+D',
  132. execute: () => this.toggle('attributes'),
  133. enabled: () => this.activeGraph
  134. });
  135. view.add({
  136. label: () => this.options.weights ? 'Hide &Weights' : 'Show &Weights',
  137. accelerator: 'CmdOrCtrl+I',
  138. execute: () => this.toggle('weights'),
  139. enabled: () => this.activeGraph
  140. });
  141. view.add({
  142. label: () => this.options.names ? 'Hide &Names' : 'Show &Names',
  143. accelerator: 'CmdOrCtrl+U',
  144. execute: () => this.toggle('names'),
  145. enabled: () => this.activeGraph
  146. });
  147. view.add({
  148. label: () => this.options.direction === 'vertical' ? 'Show &Horizontal' : 'Show &Vertical',
  149. accelerator: 'CmdOrCtrl+K',
  150. execute: () => this.toggle('direction'),
  151. enabled: () => this.activeGraph
  152. });
  153. view.add({
  154. label: () => this.options.mousewheel === 'scroll' ? '&Mouse Wheel: Zoom' : '&Mouse Wheel: Scroll',
  155. accelerator: 'CmdOrCtrl+M',
  156. execute: () => this.toggle('mousewheel'),
  157. enabled: () => this.activeGraph
  158. });
  159. view.add({});
  160. if (this._host.type === 'Electron') {
  161. view.add({
  162. label: '&Reload',
  163. accelerator: platform === 'darwin' ? 'CmdOrCtrl+R' : 'F5',
  164. execute: () => this._host.execute('reload'),
  165. enabled: () => this.activeGraph
  166. });
  167. view.add({});
  168. }
  169. view.add({
  170. label: 'Zoom &In',
  171. accelerator: 'Shift+Up',
  172. execute: () => this.zoomIn(),
  173. enabled: () => this.activeGraph
  174. });
  175. view.add({
  176. label: 'Zoom &Out',
  177. accelerator: 'Shift+Down',
  178. execute: () => this.zoomOut(),
  179. enabled: () => this.activeGraph
  180. });
  181. view.add({
  182. label: 'Actual &Size',
  183. accelerator: 'Shift+Backspace',
  184. execute: () => this.resetZoom(),
  185. enabled: () => this.activeGraph
  186. });
  187. view.add({});
  188. view.add({
  189. label: '&Properties...',
  190. accelerator: 'CmdOrCtrl+Enter',
  191. execute: () => this.showModelProperties(),
  192. enabled: () => this.activeGraph
  193. });
  194. if (this._host.type === 'Electron' && !this._host.environment('packaged')) {
  195. view.add({});
  196. view.add({
  197. label: '&Developer Tools...',
  198. accelerator: 'CmdOrCtrl+Alt+I',
  199. execute: () => this._host.execute('toggle-developer-tools')
  200. });
  201. }
  202. const help = this._menu.group('&Help');
  203. help.add({
  204. label: 'Report &Issue',
  205. execute: () => this._host.execute('report-issue')
  206. });
  207. help.add({
  208. label: `&About ${this._host.environment('name')}`,
  209. execute: () => this._host.execute('about')
  210. });
  211. }
  212. await this._host.start();
  213. } catch (error) {
  214. this.error(error, null, null);
  215. }
  216. }
  217. get host() {
  218. return this._host;
  219. }
  220. show(page) {
  221. if (!page) {
  222. page = (!this._model && !this.activeGraph) ? 'welcome' : 'default';
  223. }
  224. this._host.event('screen_view', {
  225. screen_name: page,
  226. });
  227. if (this._sidebar) {
  228. this._sidebar.close();
  229. }
  230. if (this._menu) {
  231. this._menu.close();
  232. }
  233. this._host.document.body.classList.remove(...Array.from(this._host.document.body.classList).filter((_) => _ !== 'active'));
  234. this._host.document.body.classList.add(...page.split(' '));
  235. if (page === 'default') {
  236. this._activate();
  237. } else {
  238. this._deactivate();
  239. }
  240. if (page === 'welcome') {
  241. const element = this._element('open-file-button');
  242. if (element) {
  243. element.focus();
  244. }
  245. }
  246. this._page = page;
  247. }
  248. progress(percent) {
  249. const bar = this._element('progress-bar');
  250. if (bar) {
  251. bar.style.width = `${percent}%`;
  252. }
  253. }
  254. cut() {
  255. this._host.document.execCommand('cut');
  256. }
  257. copy() {
  258. this._host.document.execCommand('copy');
  259. }
  260. paste() {
  261. this._host.document.execCommand('paste');
  262. }
  263. selectAll() {
  264. this._host.document.execCommand('selectall');
  265. }
  266. find() {
  267. if (this._graph) {
  268. this._graph.select(null);
  269. const sidebar = new view.FindSidebar(this, this.activeGraph, this.activeSignature);
  270. sidebar.on('state-changed', (sender, state) => {
  271. this._find = state;
  272. });
  273. sidebar.on('select', (sender, selection) => {
  274. this.scrollTo(this._graph.select([selection]));
  275. });
  276. sidebar.on('focus', (sender, selection) => {
  277. this._graph.focus([selection]);
  278. });
  279. sidebar.on('blur', (sender, selection) => {
  280. this._graph.blur([selection]);
  281. });
  282. this._sidebar.open(sidebar, 'Find');
  283. sidebar.focus(this._find);
  284. }
  285. }
  286. get model() {
  287. return this._model;
  288. }
  289. get options() {
  290. return this._options;
  291. }
  292. toggle(name) {
  293. switch (name) {
  294. case 'names':
  295. case 'attributes':
  296. case 'weights':
  297. this._options[name] = !this._options[name];
  298. this._reload();
  299. break;
  300. case 'direction':
  301. this._options.direction = this._options.direction === 'vertical' ? 'horizontal' : 'vertical';
  302. this._reload();
  303. break;
  304. case 'mousewheel':
  305. this._options.mousewheel = this._options.mousewheel === 'scroll' ? 'zoom' : 'scroll';
  306. break;
  307. default:
  308. throw new view.Error(`Unsupported toogle '${name}'.`);
  309. }
  310. const options = {};
  311. for (const [name, value] of Object.entries(this._options)) {
  312. if (this._defaultOptions[name] !== value) {
  313. options[name] = value;
  314. }
  315. }
  316. if (Object.entries(options).length === 0) {
  317. this._host.delete('options');
  318. } else {
  319. this._host.set('options', options);
  320. }
  321. }
  322. recents(recents) {
  323. if (this._recents) {
  324. this._recents.clear();
  325. for (let i = 0; i < recents.length; i++) {
  326. const recent = recents[i];
  327. this._recents.add({
  328. label: recent.label,
  329. accelerator: `CmdOrCtrl+${(i + 1)}`,
  330. execute: () => this._host.execute('open', recent.path)
  331. });
  332. }
  333. }
  334. }
  335. _reload() {
  336. this.show('welcome spinner');
  337. if (this._model && this._stack.length > 0) {
  338. this._updateGraph(this._model, this._stack).catch((error) => {
  339. if (error) {
  340. this.error(error, 'Graph update failed.', 'welcome');
  341. }
  342. });
  343. }
  344. }
  345. _timeout(delay) {
  346. return new Promise((resolve) => {
  347. setTimeout(resolve, delay);
  348. });
  349. }
  350. _element(id) {
  351. return this._host.document.getElementById(id);
  352. }
  353. zoomIn() {
  354. this._updateZoom(this._zoom * 1.1);
  355. }
  356. zoomOut() {
  357. this._updateZoom(this._zoom * 0.9);
  358. }
  359. resetZoom() {
  360. this._updateZoom(1);
  361. }
  362. _activate() {
  363. if (!this._events) {
  364. this._events = {};
  365. this._events.scroll = (e) => this._scrollHandler(e);
  366. this._events.wheel = (e) => this._wheelHandler(e);
  367. this._events.gesturestart = (e) => this._gestureStartHandler(e);
  368. this._events.pointerdown = (e) => this._pointerDownHandler(e);
  369. this._events.touchstart = (e) => this._touchStartHandler(e);
  370. }
  371. const graph = this._element('graph');
  372. graph.focus();
  373. graph.addEventListener('scroll', this._events.scroll);
  374. graph.addEventListener('wheel', this._events.wheel, { passive: false });
  375. graph.addEventListener('pointerdown', this._events.pointerdown);
  376. if (this._host.environment('agent') === 'safari') {
  377. graph.addEventListener('gesturestart', this._events.gesturestart, false);
  378. } else {
  379. graph.addEventListener('touchstart', this._events.touchstart, { passive: true });
  380. }
  381. }
  382. _deactivate() {
  383. if (this._events) {
  384. const graph = this._element('graph');
  385. graph.removeEventListener('scroll', this._events.scroll);
  386. graph.removeEventListener('wheel', this._events.wheel);
  387. graph.removeEventListener('pointerdown', this._events.pointerdown);
  388. graph.removeEventListener('gesturestart', this._events.gesturestart);
  389. graph.removeEventListener('touchstart', this._events.touchstart);
  390. }
  391. }
  392. _updateZoom(zoom, e) {
  393. const container = this._element('graph');
  394. const canvas = this._element('canvas');
  395. const limit = this._options.direction === 'vertical' ?
  396. container.clientHeight / this._height :
  397. container.clientWidth / this._width;
  398. const min = Math.min(Math.max(limit, 0.15), 1);
  399. zoom = Math.max(min, Math.min(zoom, 1.4));
  400. const scrollLeft = this._scrollLeft || container.scrollLeft;
  401. const scrollTop = this._scrollTop || container.scrollTop;
  402. const x = (e ? e.pageX : (container.clientWidth / 2)) + scrollLeft;
  403. const y = (e ? e.pageY : (container.clientHeight / 2)) + scrollTop;
  404. const width = zoom * this._width;
  405. const height = zoom * this._height;
  406. canvas.style.width = `${width}px`;
  407. canvas.style.height = `${height}px`;
  408. this._scrollLeft = Math.max(0, ((x * zoom) / this._zoom) - (x - scrollLeft));
  409. this._scrollTop = Math.max(0, ((y * zoom) / this._zoom) - (y - scrollTop));
  410. container.scrollLeft = this._scrollLeft;
  411. container.scrollTop = this._scrollTop;
  412. this._zoom = zoom;
  413. }
  414. _pointerDownHandler(e) {
  415. if (e.pointerType === 'touch' || e.buttons !== 1) {
  416. return;
  417. }
  418. const container = this._element('graph');
  419. if (e.target === container) {
  420. return;
  421. }
  422. e.target.setPointerCapture(e.pointerId);
  423. this._mousePosition = {
  424. left: container.scrollLeft,
  425. top: container.scrollTop,
  426. x: e.clientX,
  427. y: e.clientY
  428. };
  429. container.style.cursor = 'grabbing';
  430. e.preventDefault();
  431. e.stopImmediatePropagation();
  432. const pointerMoveHandler = (e) => {
  433. e.preventDefault();
  434. e.stopImmediatePropagation();
  435. if (this._mousePosition) {
  436. const dx = e.clientX - this._mousePosition.x;
  437. const dy = e.clientY - this._mousePosition.y;
  438. this._mousePosition.moved = dx * dx + dy * dy > 0;
  439. if (this._mousePosition.moved) {
  440. const container = this._element('graph');
  441. container.scrollTop = this._mousePosition.top - dy;
  442. container.scrollLeft = this._mousePosition.left - dx;
  443. }
  444. }
  445. };
  446. const clickHandler = (e) => {
  447. e.stopPropagation();
  448. document.removeEventListener('click', clickHandler, true);
  449. };
  450. const pointerUpHandler = (e) => {
  451. e.target.releasePointerCapture(e.pointerId);
  452. container.style.removeProperty('cursor');
  453. container.removeEventListener('pointerup', pointerUpHandler);
  454. container.removeEventListener('pointermove', pointerMoveHandler);
  455. if (this._mousePosition && this._mousePosition.moved) {
  456. e.preventDefault();
  457. e.stopImmediatePropagation();
  458. delete this._mousePosition;
  459. document.addEventListener('click', clickHandler, true);
  460. }
  461. };
  462. container.addEventListener('pointermove', pointerMoveHandler);
  463. container.addEventListener('pointerup', pointerUpHandler);
  464. }
  465. _touchStartHandler(e) {
  466. if (e.touches.length === 2) {
  467. this._touchPoints = Array.from(e.touches);
  468. this._touchZoom = this._zoom;
  469. }
  470. const touchMoveHandler = (e) => {
  471. if (Array.isArray(this._touchPoints) && this._touchPoints.length === 2 && e.touches.length === 2) {
  472. const distance = (points) => {
  473. const dx = (points[1].clientX - points[0].clientX);
  474. const dy = (points[1].clientY - points[0].clientY);
  475. return Math.sqrt(dx * dx + dy * dy);
  476. };
  477. const d1 = distance(Array.from(e.touches));
  478. const d2 = distance(this._touchPoints);
  479. if (d2 !== 0) {
  480. const points = this._touchPoints;
  481. const e = {
  482. pageX: (points[1].pageX + points[0].pageX) / 2,
  483. pageY: (points[1].pageY + points[0].pageY) / 2
  484. };
  485. const zoom = d2 === 0 ? d1 : d1 / d2;
  486. this._updateZoom(this._touchZoom * zoom, e);
  487. }
  488. }
  489. };
  490. const container = this._element('graph');
  491. const touchEndHandler = () => {
  492. container.removeEventListener('touchmove', touchMoveHandler, { passive: true });
  493. container.removeEventListener('touchcancel', touchEndHandler, { passive: true });
  494. container.removeEventListener('touchend', touchEndHandler, { passive: true });
  495. delete this._touchPoints;
  496. delete this._touchZoom;
  497. };
  498. container.addEventListener('touchmove', touchMoveHandler, { passive: true });
  499. container.addEventListener('touchcancel', touchEndHandler, { passive: true });
  500. container.addEventListener('touchend', touchEndHandler, { passive: true });
  501. }
  502. _gestureStartHandler(e) {
  503. e.preventDefault();
  504. this._gestureZoom = this._zoom;
  505. const container = this._element('graph');
  506. const gestureChangeHandler = (e) => {
  507. e.preventDefault();
  508. this._updateZoom(this._gestureZoom * e.scale, e);
  509. };
  510. const gestureEndHandler = (e) => {
  511. container.removeEventListener('gesturechange', gestureChangeHandler, false);
  512. container.removeEventListener('gestureend', gestureEndHandler, false);
  513. e.preventDefault();
  514. if (this._gestureZoom) {
  515. this._updateZoom(this._gestureZoom * e.scale, e);
  516. delete this._gestureZoom;
  517. }
  518. };
  519. container.addEventListener('gesturechange', gestureChangeHandler, false);
  520. container.addEventListener('gestureend', gestureEndHandler, false);
  521. }
  522. _scrollHandler(e) {
  523. if (this._scrollLeft && e.target.scrollLeft !== Math.floor(this._scrollLeft)) {
  524. delete this._scrollLeft;
  525. }
  526. if (this._scrollTop && e.target.scrollTop !== Math.floor(this._scrollTop)) {
  527. delete this._scrollTop;
  528. }
  529. }
  530. _wheelHandler(e) {
  531. if (e.shiftKey || e.ctrlKey || this._options.mousewheel === 'zoom') {
  532. let factor = 1;
  533. if (e.deltaMode === 1) {
  534. factor = 0.05;
  535. } else if (e.deltaMode) {
  536. factor = 1;
  537. } else {
  538. factor = 0.002;
  539. }
  540. const delta = -e.deltaY * factor * (e.ctrlKey ? 10 : 1);
  541. this._updateZoom(this._zoom * Math.pow(2, delta), e);
  542. e.preventDefault();
  543. }
  544. }
  545. scrollTo(selection) {
  546. if (selection && selection.length > 0) {
  547. const container = this._element('graph');
  548. let x = 0;
  549. let y = 0;
  550. for (const element of selection) {
  551. const rect = element.getBoundingClientRect();
  552. x += rect.left + (rect.width / 2);
  553. y += rect.top + (rect.height / 2);
  554. }
  555. x /= selection.length;
  556. y /= selection.length;
  557. const rect = container.getBoundingClientRect();
  558. const left = (container.scrollLeft + x - rect.left) - (rect.width / 2);
  559. const top = (container.scrollTop + y - rect.top) - (rect.height / 2);
  560. container.scrollTo({ left, top, behavior: 'smooth' });
  561. }
  562. }
  563. async error(error, name, screen) {
  564. if (this._sidebar) {
  565. this._sidebar.close();
  566. }
  567. this.exception(error, false);
  568. const knowns = [
  569. { name: '', message: /^Invalid value identifier/, url: 'https://github.com/lutzroeder/netron/issues/540' },
  570. { name: '', message: /^Cannot read property/, url: 'https://github.com/lutzroeder/netron/issues/647' },
  571. { name: 'Error', message: /^EPERM: operation not permitted/, url: 'https://github.com/lutzroeder/netron/issues/551' },
  572. { name: 'Error', message: /^EACCES: permission denied/, url: 'https://github.com/lutzroeder/netron/issues/504' },
  573. { name: 'RangeError', message: /^Offset is outside the bounds of the DataView/, url: 'https://github.com/lutzroeder/netron/issues/563' },
  574. { name: 'RangeError', message: /^Invalid string length/, url: 'https://github.com/lutzroeder/netron/issues/648' },
  575. { name: 'Python Error', message: /^Unknown function/, url: 'https://github.com/lutzroeder/netron/issues/546' },
  576. { name: 'Error loading model.', message: /^Unsupported file content \(/, url: 'https://github.com/lutzroeder/netron/issues/550' },
  577. { name: 'Error loading model.', message: /^Unsupported Protocol Buffers content/, url: 'https://github.com/lutzroeder/netron/issues/593' },
  578. { name: 'Error loading model.', message: /^Unsupported Protocol Buffers text content/, url: 'https://github.com/lutzroeder/netron/issues/594' },
  579. { name: 'Error loading model.', message: /^Unsupported JSON content/, url: 'https://github.com/lutzroeder/netron/issues/595' },
  580. { name: 'Error loading PyTorch model.', message: /^File does not contain root module or state dictionary/, url: 'https://github.com/lutzroeder/netron/issues/543' },
  581. { name: 'Error loading PyTorch model.', message: /^Module does not contain modules/, url: 'https://github.com/lutzroeder/netron/issues/544' },
  582. { name: 'Error loading PyTorch model.', message: /^Unknown type name/, url: 'https://github.com/lutzroeder/netron/issues/969' },
  583. { name: 'Error loading ONNX model.', message: /^File format is not onnx\.ModelProto \(Unexpected end of file\)\./, url: 'https://github.com/lutzroeder/netron/issues/1155' },
  584. { name: 'Error loading ONNX model.', message: /^File format is not onnx\.ModelProto \(Cannot read properties of undefined \(reading 'ModelProto'\)\)\./, url: 'https://github.com/lutzroeder/netron/issues/1156' },
  585. { name: 'Error loading ONNX model.', message: /^File format is not onnx\.ModelProto/, url: 'https://github.com/lutzroeder/netron/issues/549' }
  586. ];
  587. const known = knowns.find((known) => (known.name.length === 0 || known.name === error.name) && error.message.match(known.message));
  588. const url = known && known.url ? known.url : null;
  589. const message = error.message;
  590. name = name || error.name;
  591. const report = url ? true : false;
  592. await this._host.message(message, true, report ? 'Report' : 'OK');
  593. if (report) {
  594. this._host.openURL(url || `${this._host.environment('repository')}/issues`);
  595. }
  596. this.show(screen);
  597. }
  598. accept(file, size) {
  599. return this._modelFactoryService.accept(file, size);
  600. }
  601. async open(context) {
  602. this._sidebar.close();
  603. await this._timeout(2);
  604. try {
  605. const model = await this._modelFactoryService.open(context);
  606. const format = [];
  607. if (model.format) {
  608. format.push(model.format);
  609. }
  610. if (model.producer) {
  611. format.push(`(${model.producer})`);
  612. }
  613. if (format.length > 0) {
  614. this._host.event('model_open', {
  615. model_format: model.format || '',
  616. model_producer: model.producer || ''
  617. });
  618. }
  619. await this._timeout(20);
  620. const stack = [];
  621. if (Array.isArray(model.graphs) && model.graphs.length > 0) {
  622. const [graph] = model.graphs;
  623. const entry = {
  624. graph,
  625. signature: Array.isArray(graph.signatures) && graph.signatures.length > 0 ? graph.signatures[0] : null
  626. };
  627. stack.push(entry);
  628. }
  629. return await this._updateGraph(model, stack);
  630. } catch (error) {
  631. error.context = !error.context && context && context.identifier ? context.identifier : error.context || '';
  632. throw error;
  633. }
  634. }
  635. async _updateActive(stack) {
  636. this._sidebar.close();
  637. if (this._model) {
  638. this.show('welcome spinner');
  639. await this._timeout(200);
  640. try {
  641. await this._updateGraph(this._model, stack);
  642. } catch (error) {
  643. if (error) {
  644. this.error(error, 'Graph update failed.', 'welcome');
  645. }
  646. }
  647. }
  648. }
  649. get activeGraph() {
  650. if (Array.isArray(this._stack) && this._stack.length > 0) {
  651. return this._stack[0].graph;
  652. }
  653. return null;
  654. }
  655. get activeSignature() {
  656. if (Array.isArray(this._stack) && this._stack.length > 0) {
  657. return this._stack[0].signature;
  658. }
  659. return null;
  660. }
  661. async _updateGraph(model, stack) {
  662. const update = async (model, stack) => {
  663. this._model = model;
  664. this._stack = stack;
  665. const status = await this.renderGraph(this._model, this.activeGraph, this.activeSignature, this._options);
  666. if (status !== '') {
  667. this._model = null;
  668. this._stack = [];
  669. this._activeGraph = null;
  670. }
  671. this.show(null);
  672. const path = this._element('toolbar-path');
  673. const back = this._element('toolbar-path-back-button');
  674. while (path.children.length > 1) {
  675. path.removeChild(path.lastElementChild);
  676. }
  677. if (status === '') {
  678. if (this._stack.length <= 1) {
  679. back.style.opacity = 0;
  680. } else {
  681. back.style.opacity = 1;
  682. const last = this._stack.length - 2;
  683. const count = Math.min(2, last);
  684. if (count < last) {
  685. const element = this._host.document.createElement('button');
  686. element.setAttribute('class', 'toolbar-path-name-button');
  687. element.innerHTML = '&hellip;';
  688. path.appendChild(element);
  689. }
  690. for (let i = count; i >= 0; i--) {
  691. const graph = this._stack[i].graph;
  692. const element = this._host.document.createElement('button');
  693. element.setAttribute('class', 'toolbar-path-name-button');
  694. element.addEventListener('click', async () => {
  695. if (i > 0) {
  696. this._stack = this._stack.slice(i);
  697. await this._updateGraph(this._model, this._stack);
  698. } else {
  699. await this.showDefinition(graph);
  700. }
  701. });
  702. let name = '';
  703. if (graph && graph.identifier) {
  704. name = graph.identifier;
  705. } else if (graph && graph.name) {
  706. name = graph.name;
  707. }
  708. if (name.length > 24) {
  709. element.setAttribute('title', name);
  710. element.innerHTML = `&hellip;${name.substring(name.length - 24, name.length)}`;
  711. } else {
  712. element.removeAttribute('title');
  713. element.innerHTML = name;
  714. }
  715. path.appendChild(element);
  716. }
  717. }
  718. }
  719. };
  720. const lastModel = this._model;
  721. const lastStack = this._stack;
  722. try {
  723. await update(model, stack);
  724. return this._model;
  725. } catch (error) {
  726. await update(lastModel, lastStack);
  727. throw error;
  728. }
  729. }
  730. async pushGraph(graph) {
  731. if (graph && graph !== this.activeGraph && Array.isArray(graph.nodes)) {
  732. this._sidebar.close();
  733. const signature = Array.isArray(graph.signatures) && graph.signatures.length > 0 ? graph.signatures[0] : null;
  734. const entry = { graph, signature };
  735. const stack = [entry].concat(this._stack);
  736. await this._updateGraph(this._model, stack);
  737. }
  738. }
  739. async popGraph() {
  740. if (this._stack.length > 1) {
  741. this._sidebar.close();
  742. return await this._updateGraph(this._model, this._stack.slice(1));
  743. }
  744. return null;
  745. }
  746. async renderGraph(model, graph, signature, options) {
  747. this._graph = null;
  748. const canvas = this._element('canvas');
  749. while (canvas.lastChild) {
  750. canvas.removeChild(canvas.lastChild);
  751. }
  752. if (!graph) {
  753. return '';
  754. }
  755. this._zoom = 1;
  756. const groups = graph.groups || false;
  757. const nodes = graph.nodes;
  758. this._host.event('graph_view', {
  759. graph_node_count: nodes.length,
  760. graph_skip: 0
  761. });
  762. const layout = {};
  763. layout.nodesep = 20;
  764. layout.ranksep = 20;
  765. const rotate = graph.nodes.every((node) => node.inputs.filter((input) => input.value.every((argument) => !argument.initializer)).length === 0 && node.outputs.length === 0);
  766. const horizontal = rotate ? options.direction === 'vertical' : options.direction !== 'vertical';
  767. if (horizontal) {
  768. layout.rankdir = 'LR';
  769. }
  770. if (nodes.length > 3000) {
  771. layout.ranker = 'longest-path';
  772. }
  773. const viewGraph = new view.Graph(this, this._host, model, options, groups, layout);
  774. viewGraph.add(graph, signature);
  775. // Workaround for Safari background drag/zoom issue:
  776. // https://stackoverflow.com/questions/40887193/d3-js-zoom-is-not-working-with-mousewheel-in-safari
  777. const background = this._host.document.createElementNS('http://www.w3.org/2000/svg', 'rect');
  778. background.setAttribute('id', 'background');
  779. background.setAttribute('fill', 'none');
  780. background.setAttribute('pointer-events', 'all');
  781. canvas.appendChild(background);
  782. const origin = this._host.document.createElementNS('http://www.w3.org/2000/svg', 'g');
  783. origin.setAttribute('id', 'origin');
  784. canvas.appendChild(origin);
  785. viewGraph.build(this._host.document, origin);
  786. await this._timeout(20);
  787. viewGraph.measure();
  788. const status = await viewGraph.layout(this._worker);
  789. if (status === '') {
  790. viewGraph.update();
  791. const elements = Array.from(canvas.getElementsByClassName('graph-input') || []);
  792. if (elements.length === 0) {
  793. const nodeElements = Array.from(canvas.getElementsByClassName('graph-node') || []);
  794. if (nodeElements.length > 0) {
  795. elements.push(nodeElements[0]);
  796. }
  797. }
  798. const size = canvas.getBBox();
  799. const margin = 100;
  800. const width = Math.ceil(margin + size.width + margin);
  801. const height = Math.ceil(margin + size.height + margin);
  802. origin.setAttribute('transform', `translate(${margin}, ${margin}) scale(1)`);
  803. background.setAttribute('width', width);
  804. background.setAttribute('height', height);
  805. this._width = width;
  806. this._height = height;
  807. delete this._scrollLeft;
  808. delete this._scrollRight;
  809. canvas.setAttribute('viewBox', `0 0 ${width} ${height}`);
  810. canvas.setAttribute('width', width);
  811. canvas.setAttribute('height', height);
  812. this._zoom = 1;
  813. this._updateZoom(this._zoom);
  814. const container = this._element('graph');
  815. if (elements && elements.length > 0) {
  816. // Center view based on input elements
  817. const xs = [];
  818. const ys = [];
  819. for (let i = 0; i < elements.length; i++) {
  820. const element = elements[i];
  821. const rect = element.getBoundingClientRect();
  822. xs.push(rect.left + (rect.width / 2));
  823. ys.push(rect.top + (rect.height / 2));
  824. }
  825. let [x] = xs;
  826. const [y] = ys;
  827. if (ys.every((y) => y === ys[0])) {
  828. x = xs.reduce((a, b) => a + b, 0) / xs.length;
  829. }
  830. const graphRect = container.getBoundingClientRect();
  831. const left = (container.scrollLeft + x - graphRect.left) - (graphRect.width / 2);
  832. const top = (container.scrollTop + y - graphRect.top) - (graphRect.height / 2);
  833. container.scrollTo({ left, top, behavior: 'auto' });
  834. } else {
  835. const canvasRect = canvas.getBoundingClientRect();
  836. const graphRect = container.getBoundingClientRect();
  837. const left = (container.scrollLeft + (canvasRect.width / 2) - graphRect.left) - (graphRect.width / 2);
  838. const top = (container.scrollTop + (canvasRect.height / 2) - graphRect.top) - (graphRect.height / 2);
  839. container.scrollTo({ left, top, behavior: 'auto' });
  840. }
  841. this._graph = viewGraph;
  842. }
  843. return status;
  844. }
  845. applyStyleSheet(element, name) {
  846. let rules = [];
  847. for (const styleSheet of this._host.document.styleSheets) {
  848. if (styleSheet && styleSheet.href && styleSheet.href.endsWith(`/${name}`)) {
  849. rules = styleSheet.cssRules;
  850. break;
  851. }
  852. }
  853. const nodes = element.getElementsByTagName('*');
  854. for (const node of nodes) {
  855. for (const rule of rules) {
  856. if (node.matches(rule.selectorText)) {
  857. for (const item of rule.style) {
  858. node.style[item] = rule.style[item];
  859. }
  860. }
  861. }
  862. }
  863. }
  864. async export(file) {
  865. const lastIndex = file.lastIndexOf('.');
  866. const extension = lastIndex === -1 ? 'png' : file.substring(lastIndex + 1).toLowerCase();
  867. if (this.activeGraph && (extension === 'png' || extension === 'svg')) {
  868. const canvas = this._element('canvas');
  869. const clone = canvas.cloneNode(true);
  870. this.applyStyleSheet(clone, 'grapher.css');
  871. clone.setAttribute('id', 'export');
  872. clone.removeAttribute('viewBox');
  873. clone.removeAttribute('width');
  874. clone.removeAttribute('height');
  875. clone.style.removeProperty('opacity');
  876. clone.style.removeProperty('display');
  877. clone.style.removeProperty('width');
  878. clone.style.removeProperty('height');
  879. const background = clone.querySelector('#background');
  880. const origin = clone.querySelector('#origin');
  881. origin.setAttribute('transform', 'translate(0,0) scale(1)');
  882. background.removeAttribute('width');
  883. background.removeAttribute('height');
  884. const parent = canvas.parentElement;
  885. parent.insertBefore(clone, canvas);
  886. const size = clone.getBBox();
  887. parent.removeChild(clone);
  888. parent.removeChild(canvas);
  889. parent.appendChild(canvas);
  890. const delta = (Math.min(size.width, size.height) / 2.0) * 0.1;
  891. const width = Math.ceil(delta + size.width + delta);
  892. const height = Math.ceil(delta + size.height + delta);
  893. origin.setAttribute('transform', `translate(${(delta - size.x)}, ${(delta - size.y)}) scale(1)`);
  894. clone.setAttribute('width', width);
  895. clone.setAttribute('height', height);
  896. background.setAttribute('width', width);
  897. background.setAttribute('height', height);
  898. background.setAttribute('fill', '#fff');
  899. const data = new XMLSerializer().serializeToString(clone);
  900. if (extension === 'svg') {
  901. const blob = new Blob([data], { type: 'image/svg' });
  902. await this._host.export(file, blob);
  903. }
  904. if (extension === 'png') {
  905. try {
  906. const blob = await new Promise((resolve, reject) => {
  907. const image = new Image();
  908. image.onload = async () => {
  909. const max = Math.max(width, height);
  910. const scale = Math.min(24000.0 / max, 2.0);
  911. const canvas = this._host.document.createElement('canvas');
  912. canvas.width = Math.ceil(width * scale);
  913. canvas.height = Math.ceil(height * scale);
  914. const context = canvas.getContext('2d');
  915. context.scale(scale, scale);
  916. context.drawImage(image, 0, 0);
  917. canvas.toBlob((blob) => {
  918. if (blob) {
  919. resolve(blob);
  920. } else {
  921. const error = new Error('Image may be too large to render as PNG.');
  922. error.name = 'Error exporting image.';
  923. reject(error);
  924. }
  925. }, 'image/png');
  926. };
  927. image.onerror = (error) => {
  928. reject(error);
  929. };
  930. image.src = `data:image/svg+xml;base64,${this._host.window.btoa(unescape(encodeURIComponent(data)))}`;
  931. });
  932. await this._host.export(file, blob);
  933. } catch (error) {
  934. await this.error(error);
  935. }
  936. }
  937. }
  938. }
  939. showModelProperties() {
  940. if (this._model) {
  941. try {
  942. const sidebar = new view.ModelSidebar(this, this.model, this.activeGraph, this.activeSignature);
  943. sidebar.on('update-active-graph', (sender, graph) => {
  944. const entry = {
  945. graph,
  946. signature: Array.isArray(graph.signatures) && graph.signatures.length > 0 ? graph.signatures[0] : null
  947. };
  948. this._updateActive([entry]);
  949. });
  950. sidebar.on('update-active-graph-signature', (sender, signature) => {
  951. const stack = this._stack.map((entry) => {
  952. return { graph: entry.graph, signature: entry.signature };
  953. });
  954. stack[0].signature = signature;
  955. this._updateActive(stack);
  956. });
  957. this._sidebar.open(sidebar, 'Model Properties');
  958. } catch (error) {
  959. this.error(error, 'Error showing model properties.', null);
  960. }
  961. }
  962. }
  963. showNodeProperties(node) {
  964. if (node) {
  965. try {
  966. if (this._menu) {
  967. this._menu.close();
  968. }
  969. const sidebar = new view.NodeSidebar(this, node);
  970. sidebar.on('show-documentation', async (/* sender, e */) => {
  971. await this.showDefinition(node.type);
  972. });
  973. sidebar.on('export-tensor', async (sender, tensor) => {
  974. const defaultPath = tensor.name ? tensor.name.split('/').join('_').split(':').join('_').split('.').join('_') : 'tensor';
  975. const file = await this._host.save('NumPy Array', 'npy', defaultPath);
  976. if (file) {
  977. try {
  978. let data_type = tensor.type.dataType;
  979. data_type = data_type === 'boolean' ? 'bool' : data_type;
  980. const execution = new python.Execution();
  981. const bytes = execution.invoke('io.BytesIO', []);
  982. const dtype = execution.invoke('numpy.dtype', [data_type]);
  983. const array = execution.invoke('numpy.asarray', [tensor.value, dtype]);
  984. execution.invoke('numpy.save', [bytes, array]);
  985. bytes.seek(0);
  986. const blob = new Blob([bytes.read()], { type: 'application/octet-stream' });
  987. await this._host.export(file, blob);
  988. } catch (error) {
  989. this.error(error, 'Error saving NumPy tensor.', null);
  990. }
  991. }
  992. });
  993. sidebar.on('activate', (sender, value) => {
  994. this._graph.select([value]);
  995. });
  996. sidebar.on('deactivate', () => {
  997. this._graph.select(null);
  998. });
  999. sidebar.on('select', (sender, value) => {
  1000. this.scrollTo(this._graph.activate(value));
  1001. });
  1002. this._sidebar.open(sidebar, 'Node Properties');
  1003. } catch (error) {
  1004. this.error(error, 'Error showing node properties.', null);
  1005. }
  1006. }
  1007. }
  1008. showConnectionProperties(value, from, to) {
  1009. try {
  1010. if (this._menu) {
  1011. this._menu.close();
  1012. }
  1013. const sidebar = new view.ConnectionSidebar(this, value, from, to);
  1014. sidebar.on('activate', (sender, value) => {
  1015. this._graph.select([value]);
  1016. });
  1017. sidebar.on('deactivate', () => {
  1018. this._graph.select(null);
  1019. });
  1020. sidebar.on('select', (sender, value) => {
  1021. this.scrollTo(this._graph.activate(value));
  1022. });
  1023. this._sidebar.open(sidebar, 'Connection Properties');
  1024. } catch (error) {
  1025. this.error(error, 'Error showing connection properties.', null);
  1026. }
  1027. }
  1028. exception(error, fatal) {
  1029. if (error && !error.context && this._model && this._model.identifier) {
  1030. error.context = this._model.identifier;
  1031. }
  1032. this._host.exception(error, fatal);
  1033. }
  1034. async showDefinition(type) {
  1035. if (type && (type.description || type.inputs || type.outputs || type.attributes)) {
  1036. if (type.nodes && type.nodes.length > 0) {
  1037. await this.pushGraph(type);
  1038. }
  1039. const sidebar = new view.DocumentationSidebar(this, type);
  1040. sidebar.on('navigate', (sender, e) => {
  1041. this._host.openURL(e.link);
  1042. });
  1043. const title = type.type === 'function' ? 'Function' : 'Documentation';
  1044. this._sidebar.push(sidebar, title);
  1045. }
  1046. }
  1047. about() {
  1048. this._host.document.getElementById('version').innerText = this._host.version;
  1049. const handler = () => {
  1050. this._host.window.removeEventListener('keydown', handler);
  1051. this._host.document.body.removeEventListener('click', handler);
  1052. this._host.document.body.classList.remove('about');
  1053. };
  1054. this._host.window.addEventListener('keydown', handler);
  1055. this._host.document.body.addEventListener('click', handler);
  1056. this._host.document.body.classList.add('about');
  1057. }
  1058. };
  1059. view.Menu = class {
  1060. constructor(host) {
  1061. this.items = [];
  1062. this._darwin = host.environment('platform') === 'darwin';
  1063. this._document = host.document;
  1064. this._stack = [];
  1065. this._root = [];
  1066. this._buttons = [];
  1067. this._accelerators = new Map();
  1068. this._keyCodes = new Map([
  1069. ['Backspace', 0x08], ['Enter', 0x0D], ['Escape', 0x1B],
  1070. ['Left', 0x25], ['Up', 0x26], ['Right', 0x27], ['Down', 0x28],
  1071. ['F5', 0x74], ['F11', 0x7a]
  1072. ]);
  1073. this._symbols = new Map([
  1074. ['Backspace', '&#x232B;'], ['Enter', '&#x23ce;'],
  1075. ['Up', '&#x2191;'], ['Down', '&#x2193;'],
  1076. ]);
  1077. this._keydown = (e) => {
  1078. this._alt = false;
  1079. const code = e.keyCode | (e.altKey ? 0x0200 : 0) | (e.shiftKey ? 0x0100 : 0);
  1080. const modifier = (e.ctrlKey ? 0x0400 : 0) | (e.metaKey ? 0x0800 : 0);
  1081. if ((code | modifier) === 0x0212) { // Alt
  1082. this._alt = true;
  1083. } else {
  1084. const action =
  1085. this._accelerators.get(code | modifier) ||
  1086. this._accelerators.get(code | ((e.ctrlKey && !this._darwin) || (e.metaKey && this._darwin) ? 0x1000 : 0));
  1087. if (action && this._execute(action)) {
  1088. e.preventDefault();
  1089. } else {
  1090. const item = this._mnemonic(code | modifier);
  1091. if (item && this._activate(item)) {
  1092. e.preventDefault();
  1093. }
  1094. }
  1095. }
  1096. };
  1097. this._keyup = (e) => {
  1098. const code = e.keyCode;
  1099. if (code === 0x0012 && this._alt) { // Alt
  1100. switch (this._stack.length) {
  1101. case 0: {
  1102. if (this.open()) {
  1103. e.preventDefault();
  1104. }
  1105. break;
  1106. }
  1107. case 1: {
  1108. if (this.close()) {
  1109. e.preventDefault();
  1110. }
  1111. break;
  1112. }
  1113. default: {
  1114. this._stack = [this];
  1115. if (this._root.length > 1) {
  1116. this._root = [this];
  1117. this._rebuild();
  1118. }
  1119. this._update();
  1120. e.preventDefault();
  1121. break;
  1122. }
  1123. }
  1124. }
  1125. this._alt = false;
  1126. };
  1127. this._next = () => {
  1128. const button = this._element.ownerDocument.activeElement;
  1129. const index = this._buttons.indexOf(button);
  1130. if (index !== -1 && index < this._buttons.length - 1) {
  1131. const next = this._buttons[index + 1];
  1132. next.focus();
  1133. }
  1134. };
  1135. this._previous = () => {
  1136. const button = this._element.ownerDocument.activeElement;
  1137. const index = this._buttons.indexOf(button);
  1138. if (index > 0) {
  1139. const next = this._buttons[index - 1];
  1140. next.focus();
  1141. }
  1142. };
  1143. this._push = () => {
  1144. const button = this._element.ownerDocument.activeElement;
  1145. if (button && button.getAttribute('data-type') === 'group') {
  1146. button.click();
  1147. }
  1148. };
  1149. this._pop = () => {
  1150. if (this._stack.length > 1) {
  1151. this._deactivate();
  1152. }
  1153. };
  1154. this._exit = () => {
  1155. this._deactivate();
  1156. if (this._stack.length === 0) {
  1157. this.close();
  1158. }
  1159. };
  1160. host.window.addEventListener('keydown', this._keydown);
  1161. host.window.addEventListener('keyup', this._keyup);
  1162. }
  1163. attach(element, button) {
  1164. this._element = element;
  1165. button.addEventListener('click', (e) => {
  1166. this.toggle();
  1167. e.preventDefault();
  1168. });
  1169. }
  1170. add(value) {
  1171. const item = new view.Menu.Command(value);
  1172. this.register(item, item.accelerator);
  1173. }
  1174. group(label) {
  1175. const item = new view.Menu.Group(this, label);
  1176. item.identifier = `menu-item-${this.items.length}`;
  1177. this.items.push(item);
  1178. item.shortcut = this.register(item.accelerator);
  1179. return item;
  1180. }
  1181. toggle() {
  1182. if (this._element.style.opacity >= 1) {
  1183. this.close();
  1184. } else {
  1185. this._root = [this];
  1186. this._stack = [this];
  1187. this.open();
  1188. }
  1189. }
  1190. open() {
  1191. if (this._element) {
  1192. if (this._stack.length === 0) {
  1193. this.toggle();
  1194. this._stack = [this];
  1195. }
  1196. this._rebuild();
  1197. this._update();
  1198. this.register(this._exit, 'Escape');
  1199. this.register(this._previous, 'Up');
  1200. this.register(this._next, 'Down');
  1201. this.register(this._pop, 'Left');
  1202. this.register(this._push, 'Right');
  1203. }
  1204. }
  1205. close() {
  1206. if (this._element) {
  1207. this.unregister(this._exit);
  1208. this.unregister(this._previous);
  1209. this.unregister(this._next);
  1210. this.unregister(this._pop);
  1211. this.unregister(this._push);
  1212. this._element.style.opacity = 0;
  1213. this._element.style.left = '-17em';
  1214. const button = this._element.ownerDocument.activeElement;
  1215. if (this._buttons.indexOf(button) > 0) {
  1216. button.blur();
  1217. }
  1218. while (this._root.length > 1) {
  1219. this._deactivate();
  1220. }
  1221. this._stack = [];
  1222. }
  1223. }
  1224. register(action, accelerator) {
  1225. let shortcut = '';
  1226. if (accelerator) {
  1227. let shift = false;
  1228. let alt = false;
  1229. let ctrl = false;
  1230. let cmd = false;
  1231. let cmdOrCtrl = false;
  1232. let key = '';
  1233. for (const part of accelerator.split('+')) {
  1234. switch (part) {
  1235. case 'CmdOrCtrl': cmdOrCtrl = true; break;
  1236. case 'Cmd': cmd = true; break;
  1237. case 'Ctrl': ctrl = true; break;
  1238. case 'Alt': alt = true; break;
  1239. case 'Shift': shift = true; break;
  1240. default: key = part; break;
  1241. }
  1242. }
  1243. if (key !== '') {
  1244. if (this._darwin) {
  1245. shortcut += ctrl ? '&#x2303' : '';
  1246. shortcut += alt ? '&#x2325;' : '';
  1247. shortcut += shift ? '&#x21e7;' : '';
  1248. shortcut += cmdOrCtrl || cmd ? '&#x2318;' : '';
  1249. shortcut += this._symbols.has(key) ? this._symbols.get(key) : key;
  1250. } else {
  1251. shortcut += cmdOrCtrl || ctrl ? 'Ctrl+' : '';
  1252. shortcut += alt ? 'Alt+' : '';
  1253. shortcut += shift ? 'Shift+' : '';
  1254. shortcut += key;
  1255. }
  1256. let code = (cmdOrCtrl ? 0x1000 : 0) | (cmd ? 0x0800 : 0) | (ctrl ? 0x0400 : 0) | (alt ? 0x0200 : 0) | (shift ? 0x0100 : 0);
  1257. code |= this._keyCodes.has(key) ? this._keyCodes.get(key) : key.charCodeAt(0);
  1258. this._accelerators.set(code, action);
  1259. }
  1260. }
  1261. return shortcut;
  1262. }
  1263. unregister(action) {
  1264. this._accelerators = new Map(Array.from(this._accelerators.entries()).filter(([, value]) => value !== action));
  1265. }
  1266. _execute(action) {
  1267. if (typeof action === 'function') {
  1268. action();
  1269. return true;
  1270. }
  1271. switch (action ? action.type : null) {
  1272. case 'group': {
  1273. while (this._stack.length > this._root.length) {
  1274. this._stack.pop();
  1275. }
  1276. this._root.push({ items: [action] });
  1277. this._stack.push(action);
  1278. this._rebuild();
  1279. this._update();
  1280. return true;
  1281. }
  1282. case 'command': {
  1283. this.close();
  1284. setTimeout(() => action.execute(), 10);
  1285. return true;
  1286. }
  1287. default: {
  1288. return false;
  1289. }
  1290. }
  1291. }
  1292. _mnemonic(code) {
  1293. const key = /[a-zA-Z0-9]/.test(String.fromCharCode(code & 0x00FF));
  1294. const modifier = (code & 0xFF00) !== 0;
  1295. const alt = (code & 0xFF00) === 0x0200;
  1296. if (alt && key) {
  1297. this.open();
  1298. }
  1299. if (this._stack.length > 0 && key && (alt || !modifier)) {
  1300. const key = String.fromCharCode(code & 0x00FF);
  1301. const group = this._stack.length > 0 ? this._stack[this._stack.length - 1] : this;
  1302. const item = group.items.find((item) => key === item.mnemonic && (item.type === 'group' || item.type === 'command') && item.enabled);
  1303. if (item) {
  1304. return item;
  1305. }
  1306. }
  1307. return null;
  1308. }
  1309. _activate(item) {
  1310. switch (item ? item.type : null) {
  1311. case 'group': {
  1312. this._stack.push(item);
  1313. this._rebuild();
  1314. this._update();
  1315. return true;
  1316. }
  1317. case 'command': {
  1318. return this._execute(item);
  1319. }
  1320. default: {
  1321. return false;
  1322. }
  1323. }
  1324. }
  1325. _deactivate() {
  1326. if (this._root.length > 1) {
  1327. this._root.pop();
  1328. const group = this._stack.pop();
  1329. this._rebuild();
  1330. this._update();
  1331. if (group) {
  1332. const button = this._buttons.find((button) => button.getAttribute('id') === group.identifier);
  1333. if (button) {
  1334. button.focus();
  1335. }
  1336. }
  1337. } else if (this._stack.length > 0) {
  1338. this._stack.pop();
  1339. this._update();
  1340. }
  1341. }
  1342. _label(item, mnemonic) {
  1343. delete item.mnemonic;
  1344. const value = item.label;
  1345. if (value) {
  1346. const index = value.indexOf('&');
  1347. if (index !== -1) {
  1348. if (mnemonic) {
  1349. item.mnemonic = value[index + 1].toUpperCase();
  1350. return `${value.substring(0, index)}<u>${value[index + 1]}</u>${value.substring(index + 2)}`;
  1351. }
  1352. return value.substring(0, index) + value.substring(index + 1);
  1353. }
  1354. }
  1355. return value || '';
  1356. }
  1357. _rebuild() {
  1358. this._element.innerHTML = '';
  1359. const root = this._root[this._root.length - 1];
  1360. for (const group of root.items) {
  1361. const container = this._document.createElement('div');
  1362. container.setAttribute('id', group.identifier);
  1363. container.setAttribute('class', 'menu-group');
  1364. container.innerHTML = "<div class='menu-group-header'></div>";
  1365. for (const item of group.items) {
  1366. switch (item.type) {
  1367. case 'group':
  1368. case 'command': {
  1369. const button = this._document.createElement('button');
  1370. button.setAttribute('class', 'menu-command');
  1371. button.setAttribute('id', item.identifier);
  1372. button.setAttribute('data-type', item.type);
  1373. button.addEventListener('mouseenter', () => button.focus());
  1374. button.addEventListener('click', () => this._execute(item));
  1375. const accelerator = this._document.createElement('span');
  1376. accelerator.setAttribute('class', 'menu-shortcut');
  1377. if (item.type === 'group') {
  1378. accelerator.innerHTML = '&#10095;';
  1379. } else if (item.shortcut) {
  1380. accelerator.innerHTML = item.shortcut;
  1381. }
  1382. button.appendChild(accelerator);
  1383. const content = this._document.createElement('span');
  1384. content.setAttribute('class', 'menu-label');
  1385. button.appendChild(content);
  1386. container.appendChild(button);
  1387. break;
  1388. }
  1389. case 'separator': {
  1390. const element = this._document.createElement('div');
  1391. element.setAttribute('class', 'menu-separator');
  1392. element.setAttribute('id', item.identifier);
  1393. container.appendChild(element);
  1394. break;
  1395. }
  1396. default: {
  1397. break;
  1398. }
  1399. }
  1400. }
  1401. this._element.appendChild(container);
  1402. }
  1403. this._element.style.opacity = 1.0;
  1404. this._element.style.left = '0px';
  1405. if (this._root.length > 1) {
  1406. this._element.style.width = 'auto';
  1407. this._element.style.maxWidth = '60%';
  1408. } else {
  1409. this._element.style.removeProperty('width');
  1410. this._element.style.maxWidth = 'auto';
  1411. }
  1412. }
  1413. _update() {
  1414. this._buttons = [];
  1415. const selected = this._stack.length > 0 ? this._stack[this._stack.length - 1] : null;
  1416. const root = this._root[this._root.length - 1];
  1417. for (const group of root.items) {
  1418. let visible = false;
  1419. let block = false;
  1420. const active = this._stack.length <= 1 || this._stack[1] === group;
  1421. const container = this._document.getElementById(group.identifier);
  1422. container.childNodes[0].innerHTML = this._label(group, this === selected);
  1423. for (const item of group.items) {
  1424. switch (item.type) {
  1425. case 'group':
  1426. case 'command': {
  1427. const label = this._label(item, group === selected);
  1428. const button = this._document.getElementById(item.identifier);
  1429. button.childNodes[1].innerHTML = label;
  1430. if (item.enabled) {
  1431. button.removeAttribute('disabled');
  1432. button.style.display = 'block';
  1433. visible = true;
  1434. block = true;
  1435. if (active) {
  1436. this._buttons.push(button);
  1437. }
  1438. } else {
  1439. button.setAttribute('disabled', '');
  1440. button.style.display = 'none';
  1441. }
  1442. break;
  1443. }
  1444. case 'separator': {
  1445. const element = this._document.getElementById(item.identifier);
  1446. element.style.display = block ? 'block' : 'none';
  1447. block = false;
  1448. break;
  1449. }
  1450. default: {
  1451. break;
  1452. }
  1453. }
  1454. }
  1455. for (let i = group.items.length - 1; i >= 0; i--) {
  1456. const item = group.items[i];
  1457. if ((item.type === 'group' || item.type === 'command') && item.enabled) {
  1458. break;
  1459. } else if (item.type === 'separator') {
  1460. const element = this._document.getElementById(item.identifier);
  1461. element.style.display = 'none';
  1462. }
  1463. }
  1464. if (!visible) {
  1465. container.style.display = 'none';
  1466. }
  1467. container.style.opacity = active ? 1 : 0;
  1468. }
  1469. const button = this._element.ownerDocument.activeElement;
  1470. const index = this._buttons.indexOf(button);
  1471. if (index === -1 && this._buttons.length > 0) {
  1472. this._buttons[0].focus();
  1473. }
  1474. }
  1475. };
  1476. view.Menu.Group = class {
  1477. constructor(parent, label) {
  1478. this.type = 'group';
  1479. this.parent = parent;
  1480. this.label = label;
  1481. this.items = [];
  1482. }
  1483. get enabled() {
  1484. return this.items.some((item) => item.enabled);
  1485. }
  1486. add(value) {
  1487. const item = Object.keys(value).length > 0 ? new view.Menu.Command(value) : new view.Menu.Separator();
  1488. item.identifier = `${this.identifier}-${this.items.length}`;
  1489. this.items.push(item);
  1490. item.shortcut = this.parent.register(item, item.accelerator);
  1491. }
  1492. group(label) {
  1493. const item = new view.Menu.Group(this, label);
  1494. item.identifier = `${this.identifier}-${this.items.length}`;
  1495. this.items.push(item);
  1496. item.shortcut = this.parent.register(item, item.accelerator);
  1497. return item;
  1498. }
  1499. clear() {
  1500. for (const item of this.items) {
  1501. if (item.clear) {
  1502. item.clear();
  1503. }
  1504. this.parent.unregister(item);
  1505. }
  1506. this.items = [];
  1507. }
  1508. register(item, accelerator) {
  1509. return this.parent.register(item, accelerator);
  1510. }
  1511. unregister(item) {
  1512. this.parent.unregister(item);
  1513. }
  1514. };
  1515. view.Menu.Command = class {
  1516. constructor(item) {
  1517. this.type = 'command';
  1518. this.accelerator = item.accelerator;
  1519. this._label = item.label;
  1520. this._enabled = item.enabled;
  1521. this._execute = item.execute;
  1522. }
  1523. get label() {
  1524. return typeof this._label === 'function' ? this._label() : this._label;
  1525. }
  1526. get enabled() {
  1527. return this._enabled ? this._enabled() : true;
  1528. }
  1529. execute() {
  1530. if (this._execute && this.enabled) {
  1531. this._execute();
  1532. }
  1533. }
  1534. };
  1535. view.Menu.Separator = class {
  1536. constructor() {
  1537. this.type = 'separator';
  1538. this.enabled = false;
  1539. }
  1540. };
  1541. view.Worker = class {
  1542. constructor(host) {
  1543. this._host = host;
  1544. const type = this._host.type;
  1545. this._browser = type === 'Browser' || type === 'Python';
  1546. if (this._browser) {
  1547. this._create();
  1548. }
  1549. }
  1550. async request(message, delay, notification) {
  1551. this._timeout = -1;
  1552. return new Promise((resolve, reject) => {
  1553. this._resolve = resolve;
  1554. this._reject = reject;
  1555. if (!this._worker) {
  1556. this._create();
  1557. }
  1558. this._worker.postMessage(message);
  1559. this._timeout = setTimeout(async () => {
  1560. await this._host.message(notification, null, 'Cancel');
  1561. this._cancel(true);
  1562. delete this._resolve;
  1563. delete this._reject;
  1564. resolve({ type: 'cancel' });
  1565. }, delay);
  1566. });
  1567. }
  1568. _create() {
  1569. this._worker = this._host.worker('./worker');
  1570. this._worker.addEventListener('message', (e) => {
  1571. this._cancel(false);
  1572. const message = e.data;
  1573. if (message.type === 'error') {
  1574. this._reject(new Error(message.message));
  1575. } else {
  1576. this._resolve(message);
  1577. }
  1578. delete this._resolve;
  1579. delete this._reject;
  1580. });
  1581. this._worker.addEventListener('error', (e) => {
  1582. this._cancel(true);
  1583. if (this._reject) {
  1584. this._reject(new Error(`Unknown worker error type '${e.type}'.`));
  1585. delete this._resolve;
  1586. delete this._reject;
  1587. }
  1588. });
  1589. }
  1590. _cancel(terminate) {
  1591. terminate = terminate || !this._browser;
  1592. if (this._worker && terminate) {
  1593. this._worker.terminate();
  1594. this._worker = null;
  1595. }
  1596. if (this._timeout >= 0) {
  1597. clearTimeout(this._timeout);
  1598. this._timeout = -1;
  1599. this._host.message();
  1600. }
  1601. }
  1602. };
  1603. view.Graph = class extends grapher.Graph {
  1604. constructor(view, host, model, options, compound, layout) {
  1605. super(compound, layout);
  1606. this.view = view;
  1607. this.host = host;
  1608. this.model = model;
  1609. this.options = options;
  1610. this._nodeKey = 0;
  1611. this._values = new Map();
  1612. this._table = new Map();
  1613. this._selection = new Set();
  1614. }
  1615. createNode(node, type) {
  1616. if (type) {
  1617. const value = new view.Node(this, { type });
  1618. value.name = (this._nodeKey++).toString();
  1619. this._table.set(type, value);
  1620. return value;
  1621. }
  1622. const value = new view.Node(this, node);
  1623. value.name = (this._nodeKey++).toString();
  1624. this._table.set(node, value);
  1625. return value;
  1626. }
  1627. createInput(input) {
  1628. const value = new view.Input(this, input);
  1629. value.name = (this._nodeKey++).toString();
  1630. this._table.set(input, value);
  1631. return value;
  1632. }
  1633. createOutput(output) {
  1634. const value = new view.Output(this, output);
  1635. value.name = (this._nodeKey++).toString();
  1636. this._table.set(output, value);
  1637. return value;
  1638. }
  1639. createValue(argument) {
  1640. const name = argument.name;
  1641. if (this._values.has(name)) {
  1642. // duplicate argument name
  1643. const value = this._values.get(name);
  1644. this._table.set(argument, value);
  1645. } else {
  1646. const value = new view.Value(this, argument);
  1647. this._values.set(name, value);
  1648. this._table.set(argument, value);
  1649. }
  1650. return this._values.get(name);
  1651. }
  1652. add(graph, signature) {
  1653. const clusters = new Set();
  1654. const clusterParentMap = new Map();
  1655. const groups = graph.groups;
  1656. if (groups) {
  1657. for (const node of graph.nodes) {
  1658. if (node.group) {
  1659. const path = node.group.split('/');
  1660. while (path.length > 0) {
  1661. const name = path.join('/');
  1662. path.pop();
  1663. clusterParentMap.set(name, path.join('/'));
  1664. }
  1665. }
  1666. }
  1667. }
  1668. const inputs = signature ? signature.inputs : graph.inputs;
  1669. const outputs = signature ? signature.outputs : graph.outputs;
  1670. if (Array.isArray(inputs)) {
  1671. for (const input of inputs) {
  1672. const viewInput = this.createInput(input);
  1673. this.setNode(viewInput);
  1674. for (const value of input.value) {
  1675. this.createValue(value).from = viewInput;
  1676. }
  1677. }
  1678. }
  1679. for (const node of graph.nodes) {
  1680. const viewNode = this.createNode(node);
  1681. this.setNode(viewNode);
  1682. const inputs = node.inputs;
  1683. for (const input of inputs) {
  1684. for (const value of input.value) {
  1685. if (value.name !== '' && !value.initializer) {
  1686. this.createValue(value).to.push(viewNode);
  1687. }
  1688. }
  1689. }
  1690. let outputs = node.outputs;
  1691. if (node.chain && node.chain.length > 0) {
  1692. const chainOutputs = node.chain[node.chain.length - 1].outputs;
  1693. if (chainOutputs.length > 0) {
  1694. outputs = chainOutputs;
  1695. }
  1696. }
  1697. for (const output of outputs) {
  1698. for (const value of output.value) {
  1699. if (!value) {
  1700. throw new view.Error('Invalid null argument.');
  1701. }
  1702. if (value.name !== '') {
  1703. this.createValue(value).from = viewNode;
  1704. }
  1705. }
  1706. }
  1707. if (node.controlDependencies && node.controlDependencies.length > 0) {
  1708. for (const value of node.controlDependencies) {
  1709. this.createValue(value).controlDependency(viewNode);
  1710. }
  1711. }
  1712. const createCluster = (name) => {
  1713. if (!clusters.has(name)) {
  1714. this.setNode({ name, rx: 5, ry: 5 });
  1715. clusters.add(name);
  1716. const parent = clusterParentMap.get(name);
  1717. if (parent) {
  1718. createCluster(parent);
  1719. this.setParent(name, parent);
  1720. }
  1721. }
  1722. };
  1723. if (groups) {
  1724. let groupName = node.group;
  1725. if (groupName && groupName.length > 0) {
  1726. if (!clusterParentMap.has(groupName)) {
  1727. const lastIndex = groupName.lastIndexOf('/');
  1728. if (lastIndex === -1) {
  1729. groupName = null;
  1730. } else {
  1731. groupName = groupName.substring(0, lastIndex);
  1732. if (!clusterParentMap.has(groupName)) {
  1733. groupName = null;
  1734. }
  1735. }
  1736. }
  1737. if (groupName) {
  1738. createCluster(`${groupName}\ngroup`);
  1739. this.setParent(viewNode.name, `${groupName}\ngroup`);
  1740. }
  1741. }
  1742. }
  1743. }
  1744. if (Array.isArray(outputs)) {
  1745. for (const output of outputs) {
  1746. const viewOutput = this.createOutput(output);
  1747. this.setNode(viewOutput);
  1748. for (const value of output.value) {
  1749. this.createValue(value).to.push(viewOutput);
  1750. }
  1751. }
  1752. }
  1753. }
  1754. build(document, origin) {
  1755. for (const value of this._values.values()) {
  1756. value.build();
  1757. }
  1758. super.build(document, origin);
  1759. }
  1760. select(selection) {
  1761. if (this._selection.size > 0) {
  1762. for (const element of this._selection) {
  1763. element.deselect();
  1764. }
  1765. this._selection.clear();
  1766. }
  1767. if (selection) {
  1768. let array = [];
  1769. for (const value of selection) {
  1770. if (this._table.has(value)) {
  1771. const element = this._table.get(value);
  1772. array = array.concat(element.select());
  1773. this._selection.add(element);
  1774. }
  1775. }
  1776. return array;
  1777. }
  1778. return null;
  1779. }
  1780. activate(value) {
  1781. if (this._table.has(value)) {
  1782. this.select(null);
  1783. const element = this._table.get(value);
  1784. element.activate();
  1785. return this.select([value]);
  1786. }
  1787. return [];
  1788. }
  1789. focus(selection) {
  1790. for (const value of selection) {
  1791. const element = this._table.get(value);
  1792. if (element && !this._selection.has(element)) {
  1793. element.select();
  1794. }
  1795. }
  1796. }
  1797. blur(selection) {
  1798. for (const value of selection) {
  1799. const element = this._table.get(value);
  1800. if (element && !this._selection.has(element)) {
  1801. element.deselect();
  1802. }
  1803. }
  1804. }
  1805. };
  1806. view.Node = class extends grapher.Node {
  1807. constructor(context, value) {
  1808. super();
  1809. this.context = context;
  1810. this.value = value;
  1811. view.Node.counter = view.Node.counter || 0;
  1812. this.id = `node-${value.name ? `name-${value.name}` : `id-${(view.Node.counter++)}`}`;
  1813. this._add(this.value);
  1814. }
  1815. get class() {
  1816. return 'graph-node';
  1817. }
  1818. get inputs() {
  1819. return this.value.inputs;
  1820. }
  1821. get outputs() {
  1822. return this.value.outputs;
  1823. }
  1824. _add(node) {
  1825. const options = this.context.options;
  1826. const header = this.header();
  1827. const styles = ['node-item-type'];
  1828. const type = node.type;
  1829. const category = type && type.category ? type.category : '';
  1830. if (category) {
  1831. styles.push(`node-item-type-${category.toLowerCase()}`);
  1832. }
  1833. if (typeof type.name !== 'string' || !type.name.split) { // #416
  1834. const error = new view.Error(`Unsupported node type '${JSON.stringify(type.name)}'.`);
  1835. if (this.context.model && this.context.model.identifier) {
  1836. error.context = this.context.model.identifier;
  1837. }
  1838. throw error;
  1839. }
  1840. let content = options.names && (node.name || node.location) ? (node.name || node.location) : type.name.split('.').pop();
  1841. const tooltip = options.names && (node.name || node.location) ? type.name : (node.name || node.location);
  1842. if (content.length > 24) {
  1843. content = `${content.substring(0, 12)}\u2026${content.substring(content.length - 12, content.length)}`;
  1844. }
  1845. const title = header.add(null, styles, content, tooltip);
  1846. title.on('click', () => {
  1847. this.context.activate(node);
  1848. });
  1849. if (Array.isArray(node.type.nodes) && node.type.nodes.length > 0) {
  1850. const definition = header.add(null, styles, '\u0192', 'Show Function Definition');
  1851. definition.on('click', async () => await this.context.view.pushGraph(node.type));
  1852. }
  1853. if (Array.isArray(node.nodes)) {
  1854. // this._expand = header.add(null, styles, '+', null);
  1855. // this._expand.on('click', () => this.toggle());
  1856. }
  1857. const initializers = [];
  1858. let hiddenInitializers = false;
  1859. if (options.weights) {
  1860. if (Array.isArray(node.inputs)) {
  1861. for (const input of node.inputs) {
  1862. if (input.visible !== false && input.value.length === 1 && input.value[0].initializer) {
  1863. initializers.push(input);
  1864. }
  1865. if ((input.visible === false || input.value.length > 1) &&
  1866. input.value.some((argument) => argument.initializer)) {
  1867. hiddenInitializers = true;
  1868. }
  1869. }
  1870. }
  1871. }
  1872. const objects = [];
  1873. const attributes = [];
  1874. if (Array.isArray(node.attributes) && node.attributes.length > 0) {
  1875. for (const attribute of node.attributes) {
  1876. switch (attribute.type) {
  1877. case 'graph':
  1878. case 'object':
  1879. case 'object[]':
  1880. case 'function':
  1881. case 'function[]': {
  1882. objects.push(attribute);
  1883. break;
  1884. }
  1885. default: {
  1886. if (options.attributes && attribute.visible !== false) {
  1887. attributes.push(attribute);
  1888. }
  1889. }
  1890. }
  1891. }
  1892. attributes.sort((a, b) => a.name.toUpperCase().localeCompare(b.name.toUpperCase()));
  1893. }
  1894. if (initializers.length > 0 || hiddenInitializers || attributes.length > 0 || objects.length > 0) {
  1895. const list = this.list();
  1896. list.on('click', () => this.context.activate(node));
  1897. for (const argument of initializers) {
  1898. const [value] = argument.value;
  1899. const type = value.type;
  1900. let shape = '';
  1901. let separator = '';
  1902. if (type && type.shape && type.shape.dimensions && Array.isArray(type.shape.dimensions)) {
  1903. shape = `\u3008${type.shape.dimensions.map((d) => (d !== null && d !== undefined) ? d : '?').join('\u00D7')}\u3009`;
  1904. if (type.shape.dimensions.length === 0 && value.initializer) {
  1905. try {
  1906. const initializer = value.initializer;
  1907. const tensor = new view.Tensor(initializer);
  1908. const encoding = tensor.encoding;
  1909. if ((encoding === '<' || encoding === '>' || encoding === '|') && !tensor.empty && tensor.type.dataType !== '?') {
  1910. shape = tensor.toString();
  1911. if (shape && shape.length > 10) {
  1912. shape = `${shape.substring(0, 10)}\u2026`;
  1913. }
  1914. separator = ' = ';
  1915. }
  1916. } catch (error) {
  1917. this.context.view.exception(error, false);
  1918. }
  1919. }
  1920. }
  1921. list.add(argument.name, shape, type ? type.toString() : '', separator);
  1922. }
  1923. if (hiddenInitializers) {
  1924. list.add('\u3008\u2026\u3009', '', null, '');
  1925. }
  1926. for (const attribute of attributes) {
  1927. if (attribute.visible !== false) {
  1928. let value = new view.Formatter(attribute.value, attribute.type).toString();
  1929. if (value && value.length > 25) {
  1930. value = `${value.substring(0, 25)}\u2026`;
  1931. }
  1932. list.add(attribute.name, value, attribute.type, ' = ');
  1933. }
  1934. }
  1935. for (const attribute of objects) {
  1936. if (attribute.type === 'graph') {
  1937. const node = this.context.createNode(null, attribute.value);
  1938. list.add(attribute.name, node, '', '');
  1939. }
  1940. if (attribute.type === 'function' || attribute.type === 'object') {
  1941. const node = this.context.createNode(attribute.value);
  1942. list.add(attribute.name, node, '', '');
  1943. }
  1944. if (attribute.type === 'function[]' || attribute.type === 'object[]') {
  1945. const nodes = attribute.value.map((value) => this.context.createNode(value));
  1946. list.add(attribute.name, nodes, '', '');
  1947. }
  1948. }
  1949. }
  1950. if (Array.isArray(node.nodes) && node.nodes.length > 0) {
  1951. // this.canvas = this.canvas();
  1952. }
  1953. if (Array.isArray(node.chain) && node.chain.length > 0) {
  1954. for (const innerNode of node.chain) {
  1955. this.context.createNode(innerNode);
  1956. this._add(innerNode);
  1957. }
  1958. }
  1959. if (node.inner) {
  1960. this.context.createNode(node.inner);
  1961. this._add(node.inner);
  1962. }
  1963. }
  1964. toggle() {
  1965. this._expand.content = '-';
  1966. this._graph = new view.Graph(this.context.view, this.context.view.host, this.context.model, this.context.options, false, {});
  1967. this._graph.add(this.value);
  1968. // const document = this.element.ownerDocument;
  1969. // const parent = this.element.parentElement;
  1970. // this._graph.build(document, parent);
  1971. // this._graph.update();
  1972. this.canvas.width = 300;
  1973. this.canvas.height = 300;
  1974. this.layout();
  1975. this.context.update();
  1976. }
  1977. activate() {
  1978. this.context.view.showNodeProperties(this.value);
  1979. }
  1980. edge(to) {
  1981. this._edges = this._edges || new Map();
  1982. if (!this._edges.has(to)) {
  1983. this._edges.set(to, new view.Edge(this, to));
  1984. }
  1985. return this._edges.get(to);
  1986. }
  1987. };
  1988. view.Input = class extends grapher.Node {
  1989. constructor(context, value) {
  1990. super();
  1991. this.context = context;
  1992. this.value = value;
  1993. view.Input.counter = view.Input.counter || 0;
  1994. const types = value.value.map((argument) => argument.type || '').join('\n');
  1995. let name = value.name || '';
  1996. if (name.length > 16) {
  1997. name = name.split('/').pop();
  1998. }
  1999. const header = this.header();
  2000. const title = header.add(null, ['graph-item-input'], name, types);
  2001. title.on('click', () => this.context.view.showModelProperties());
  2002. this.id = `input-${name ? `name-${name}` : `id-${(view.Input.counter++)}`}`;
  2003. }
  2004. get class() {
  2005. return 'graph-input';
  2006. }
  2007. get inputs() {
  2008. return [];
  2009. }
  2010. get outputs() {
  2011. return [this.value];
  2012. }
  2013. activate() {
  2014. this.context.view.showModelProperties();
  2015. }
  2016. edge(to) {
  2017. this._edges = this._edges || new Map();
  2018. if (!this._edges.has(to)) {
  2019. this._edges.set(to, new view.Edge(this, to));
  2020. }
  2021. return this._edges.get(to);
  2022. }
  2023. };
  2024. view.Output = class extends grapher.Node {
  2025. constructor(context, value) {
  2026. super();
  2027. this.context = context;
  2028. this.value = value;
  2029. const types = value.value.map((argument) => argument.type || '').join('\n');
  2030. let name = value.name || '';
  2031. if (name.length > 16) {
  2032. name = name.split('/').pop();
  2033. }
  2034. const header = this.header();
  2035. const title = header.add(null, ['graph-item-output'], name, types);
  2036. title.on('click', () => this.context.view.showModelProperties());
  2037. }
  2038. get inputs() {
  2039. return [this.value];
  2040. }
  2041. get outputs() {
  2042. return [];
  2043. }
  2044. activate() {
  2045. this.context.view.showModelProperties();
  2046. }
  2047. };
  2048. view.Value = class {
  2049. constructor(context, argument) {
  2050. this.context = context;
  2051. this.value = argument;
  2052. this.from = null;
  2053. this.to = [];
  2054. }
  2055. controlDependency(node) {
  2056. this._controlDependencies = this._controlDependencies || new Set();
  2057. this._controlDependencies.add(this.to.length);
  2058. this.to.push(node);
  2059. }
  2060. build() {
  2061. this._edges = this._edges || [];
  2062. if (this.from && Array.isArray(this.to)) {
  2063. for (let i = 0; i < this.to.length; i++) {
  2064. const to = this.to[i];
  2065. let content = '';
  2066. const type = this.value.type;
  2067. if (type &&
  2068. type.shape &&
  2069. type.shape.dimensions &&
  2070. type.shape.dimensions.length > 0 &&
  2071. type.shape.dimensions.every((dim) => !dim || Number.isInteger(dim) || typeof dim === 'bigint' || (typeof dim === 'string'))) {
  2072. content = type.shape.dimensions.map((dim) => (dim !== null && dim !== undefined) ? dim : '?').join('\u00D7');
  2073. content = content.length > 16 ? '' : content;
  2074. }
  2075. if (this.context.options.names) {
  2076. content = this.value.name.split('\n').shift(); // custom argument id
  2077. }
  2078. const edge = this.from.edge(to);
  2079. if (!edge.value) {
  2080. edge.value = this;
  2081. if (content) {
  2082. edge.label = content;
  2083. }
  2084. edge.id = `edge-${this.value.name}`;
  2085. if (this._controlDependencies && this._controlDependencies.has(i)) {
  2086. edge.class = 'edge-path-control-dependency';
  2087. }
  2088. }
  2089. this.context.setEdge(edge);
  2090. this._edges.push(edge);
  2091. }
  2092. }
  2093. }
  2094. select() {
  2095. let array = [];
  2096. if (Array.isArray(this._edges)) {
  2097. for (const edge of this._edges) {
  2098. array = array.concat(edge.select());
  2099. }
  2100. }
  2101. return array;
  2102. }
  2103. deselect() {
  2104. if (Array.isArray(this._edges)) {
  2105. for (const edge of this._edges) {
  2106. edge.deselect();
  2107. }
  2108. }
  2109. }
  2110. activate() {
  2111. if (this.value && this.from && Array.isArray(this.to)) {
  2112. const value = this.value;
  2113. const from = this.from.value;
  2114. const to = this.to.map((node) => node.value);
  2115. this.context.view.showConnectionProperties(value, from, to);
  2116. }
  2117. }
  2118. };
  2119. view.Edge = class extends grapher.Edge {
  2120. constructor(from, to) {
  2121. super(from, to);
  2122. this.v = from.name;
  2123. this.w = to.name;
  2124. }
  2125. get minlen() {
  2126. if (this.from.inputs.every((argument) => argument.value.every((value) => value.initializer))) {
  2127. return 2;
  2128. }
  2129. return 1;
  2130. }
  2131. emit(event) {
  2132. switch (event) {
  2133. case 'pointerover': {
  2134. this.value.context.focus([this.value.value]);
  2135. break;
  2136. }
  2137. case 'pointerleave': {
  2138. this.value.context.blur([this.value.value]);
  2139. break;
  2140. }
  2141. case 'click': {
  2142. this.value.context.activate(this.value.value);
  2143. break;
  2144. }
  2145. default:
  2146. break;
  2147. }
  2148. }
  2149. };
  2150. view.Sidebar = class {
  2151. constructor(host) {
  2152. this._host = host;
  2153. this._stack = [];
  2154. const pop = () => this._update(this._stack.slice(0, -1));
  2155. this._closeSidebarHandler = () => pop();
  2156. this._closeSidebarKeyDownHandler = (e) => {
  2157. if (e.keyCode === 27) {
  2158. e.preventDefault();
  2159. pop();
  2160. }
  2161. };
  2162. const sidebar = this._element('sidebar');
  2163. sidebar.addEventListener('transitionend', (event) => {
  2164. if (event.propertyName === 'opacity' && sidebar.style.opacity === '0') {
  2165. const content = this._element('sidebar-content');
  2166. content.innerHTML = '';
  2167. }
  2168. });
  2169. }
  2170. _element(id) {
  2171. return this._host.document.getElementById(id);
  2172. }
  2173. open(content, title) {
  2174. content = this._render(content);
  2175. const entry = { title, content };
  2176. this._update([entry]);
  2177. }
  2178. close() {
  2179. this._update([]);
  2180. }
  2181. push(content, title) {
  2182. content = this._render(content);
  2183. const entry = { title, content };
  2184. this._update(this._stack.concat(entry));
  2185. }
  2186. _render(content) {
  2187. try {
  2188. content.render();
  2189. } catch (error) {
  2190. content.error(error, false);
  2191. }
  2192. const element = content.element;
  2193. return Array.isArray(element) ? element : [element];
  2194. }
  2195. _update(stack) {
  2196. const sidebar = this._element('sidebar');
  2197. const content = this._element('sidebar-content');
  2198. const container = this._element('graph');
  2199. const closeButton = this._element('sidebar-closebutton');
  2200. closeButton.removeEventListener('click', this._closeSidebarHandler);
  2201. this._host.document.removeEventListener('keydown', this._closeSidebarKeyDownHandler);
  2202. if (stack) {
  2203. this._stack = stack;
  2204. } else if (this._stack.length > 0) {
  2205. this._stack.pop();
  2206. }
  2207. if (this._stack.length > 0) {
  2208. const item = this._stack[this._stack.length - 1];
  2209. this._element('sidebar-title').innerHTML = item.title || '';
  2210. closeButton.addEventListener('click', this._closeSidebarHandler);
  2211. if (typeof item.content === 'string') {
  2212. content.innerHTML = item.content;
  2213. } else if (item.content instanceof Array) {
  2214. content.innerHTML = '';
  2215. for (const element of item.content) {
  2216. content.appendChild(element);
  2217. }
  2218. } else {
  2219. content.innerHTML = '';
  2220. content.appendChild(item.content);
  2221. }
  2222. sidebar.style.width = 'min(calc(100% * 0.6), 42em)';
  2223. sidebar.style.right = 0;
  2224. sidebar.style.opacity = 1;
  2225. this._host.document.addEventListener('keydown', this._closeSidebarKeyDownHandler);
  2226. container.style.width = 'max(40vw, calc(100vw - 42em))';
  2227. } else {
  2228. sidebar.style.right = 'calc(0px - min(calc(100% * 0.6), 42em))';
  2229. sidebar.style.opacity = 0;
  2230. const clone = content.cloneNode(true);
  2231. content.parentNode.replaceChild(clone, content);
  2232. container.style.width = '100%';
  2233. container.focus();
  2234. }
  2235. }
  2236. };
  2237. view.Control = class {
  2238. constructor(context) {
  2239. this._view = context;
  2240. this._host = context.host;
  2241. }
  2242. createElement(tagName, className) {
  2243. const element = this._host.document.createElement(tagName);
  2244. if (className) {
  2245. element.setAttribute('class', className);
  2246. }
  2247. return element;
  2248. }
  2249. on(event, callback) {
  2250. this._events = this._events || {};
  2251. this._events[event] = this._events[event] || [];
  2252. this._events[event].push(callback);
  2253. }
  2254. emit(event, data) {
  2255. if (this._events && this._events[event]) {
  2256. for (const callback of this._events[event]) {
  2257. callback(this, data);
  2258. }
  2259. }
  2260. }
  2261. error(error, fatal) {
  2262. this._view.exception(error, fatal || false);
  2263. }
  2264. };
  2265. view.ObjectSidebar = class extends view.Control {
  2266. constructor(context) {
  2267. super(context);
  2268. this.element = this.createElement('div', 'sidebar-object');
  2269. }
  2270. add(name, item) {
  2271. const entry = new view.NameValueView(this._view, name, item);
  2272. const element = entry.render();
  2273. this.element.appendChild(element);
  2274. }
  2275. addProperty(name, value, style) {
  2276. const item = new view.ValueTextView(this._view, value, style);
  2277. this.add(name, item);
  2278. return item;
  2279. }
  2280. addHeader(title) {
  2281. const element = this.createElement('div', 'sidebar-header');
  2282. element.innerText = title;
  2283. this.element.appendChild(element);
  2284. }
  2285. error(error, fatal) {
  2286. super.error(error, fatal);
  2287. const element = this.createElement('span');
  2288. element.innerHTML = `<b>ERROR:</b> ${error.message}`;
  2289. this.element.appendChild(element);
  2290. }
  2291. };
  2292. view.NodeSidebar = class extends view.ObjectSidebar {
  2293. constructor(context, node) {
  2294. super(context);
  2295. this._node = node;
  2296. this._attributes = [];
  2297. this._inputs = [];
  2298. this._outputs = [];
  2299. }
  2300. render() {
  2301. const node = this._node;
  2302. if (node.type) {
  2303. const type = node.type;
  2304. const item = this.addProperty('type', node.type.identifier || node.type.name);
  2305. if (type && (type.description || type.inputs || type.outputs || type.attributes)) {
  2306. item.action(type.nodes ? '\u0192' : '?', () => {
  2307. this.emit('show-documentation', null);
  2308. });
  2309. }
  2310. const module = node.type.module;
  2311. const version = node.type.version;
  2312. const status = node.type.status;
  2313. if (module || version || status) {
  2314. const list = [module, version ? `v${version}` : '', status];
  2315. const value = list.filter((value) => value).join(' ');
  2316. this.addProperty('module', value, 'nowrap');
  2317. }
  2318. }
  2319. if (node.name) {
  2320. this.addProperty('name', node.name, 'nowrap');
  2321. }
  2322. if (node.identifier) {
  2323. this.addProperty('identifier', node.identifier, 'nowrap');
  2324. }
  2325. if (node.description) {
  2326. this.addProperty('description', node.description);
  2327. }
  2328. if (node.device) {
  2329. this.addProperty('device', node.device);
  2330. }
  2331. const metadata = node.metadata;
  2332. if (Array.isArray(metadata) && metadata.length > 0) {
  2333. this.addHeader('Metadata');
  2334. for (const entry of metadata) {
  2335. this._addAttribute(entry.name, entry);
  2336. }
  2337. }
  2338. const attributes = node.attributes;
  2339. if (Array.isArray(attributes) && attributes.length > 0) {
  2340. this.addHeader('Attributes');
  2341. attributes.sort((a, b) => a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }));
  2342. for (const attribute of attributes) {
  2343. this._addAttribute(attribute.name, attribute);
  2344. }
  2345. }
  2346. const inputs = node.inputs;
  2347. if (Array.isArray(inputs) && inputs.length > 0) {
  2348. this.addHeader('Inputs');
  2349. for (const input of inputs) {
  2350. this._addInput(input.name, input);
  2351. }
  2352. }
  2353. const outputs = node.outputs;
  2354. if (Array.isArray(outputs) && outputs.length > 0) {
  2355. this.addHeader('Outputs');
  2356. for (const output of outputs) {
  2357. this._addOutput(output.name, output);
  2358. }
  2359. }
  2360. }
  2361. _addAttribute(name, attribute) {
  2362. let value = null;
  2363. switch (attribute.type) {
  2364. case 'tensor': {
  2365. value = new view.ValueView(this._view, { type: attribute.value.type, initializer: attribute.value }, '');
  2366. value.on('export-tensor', (sender, value) => this.emit('export-tensor', value));
  2367. break;
  2368. }
  2369. case 'tensor[]': {
  2370. const values = attribute.value.map((value) => {
  2371. return { type: value.type, initializer: value };
  2372. });
  2373. value = new view.ArgumentView(this._view, { value: values }, '');
  2374. break;
  2375. }
  2376. default: {
  2377. value = new view.AttributeView(this._view, attribute);
  2378. value.on('activate', (sender, graph) => {
  2379. this.emit('activate', graph);
  2380. });
  2381. break;
  2382. }
  2383. }
  2384. const item = new view.NameValueView(this._view, name, value);
  2385. this._attributes.push(item);
  2386. this.element.appendChild(item.render());
  2387. }
  2388. _addInput(name, input) {
  2389. if (input.value.length > 0) {
  2390. const value = new view.ArgumentView(this._view, input);
  2391. value.on('export-tensor', (sender, value) => this.emit('export-tensor', value));
  2392. value.on('activate', (sender, value) => this.emit('activate', value));
  2393. value.on('deactivate', (sender, value) => this.emit('deactivate', value));
  2394. value.on('select', (sender, value) => this.emit('select', value));
  2395. const item = new view.NameValueView(this._view, name, value);
  2396. this._inputs.push(item);
  2397. this.element.appendChild(item.render());
  2398. }
  2399. }
  2400. _addOutput(name, output) {
  2401. if (output.value.length > 0) {
  2402. const value = new view.ArgumentView(this._view, output);
  2403. value.on('activate', (sender, value) => this.emit('activate', value));
  2404. value.on('deactivate', (sender, value) => this.emit('deactivate', value));
  2405. value.on('select', (sender, value) => this.emit('select', value));
  2406. const item = new view.NameValueView(this._view, name, value);
  2407. this._outputs.push(item);
  2408. this.element.appendChild(item.render());
  2409. }
  2410. }
  2411. };
  2412. view.NameValueView = class extends view.Control {
  2413. constructor(context, name, value) {
  2414. super(context);
  2415. this._name = name;
  2416. this._value = value;
  2417. const nameElement = this.createElement('div', 'sidebar-item-name');
  2418. const input = this.createElement('input');
  2419. input.setAttribute('type', 'text');
  2420. input.setAttribute('value', name);
  2421. input.setAttribute('title', name);
  2422. input.setAttribute('readonly', 'true');
  2423. nameElement.appendChild(input);
  2424. const valueElement = this.createElement('div', 'sidebar-item-value-list');
  2425. for (const element of value.render()) {
  2426. valueElement.appendChild(element);
  2427. }
  2428. this._element = this.createElement('div', 'sidebar-item');
  2429. this._element.appendChild(nameElement);
  2430. this._element.appendChild(valueElement);
  2431. }
  2432. get name() {
  2433. return this._name;
  2434. }
  2435. render() {
  2436. return this._element;
  2437. }
  2438. toggle() {
  2439. this._value.toggle();
  2440. }
  2441. };
  2442. view.SelectView = class extends view.Control {
  2443. constructor(context, entries, selected) {
  2444. super(context);
  2445. this._elements = [];
  2446. this._entries = Array.from(entries);
  2447. const selectElement = this.createElement('select', 'sidebar-item-select');
  2448. selectElement.addEventListener('change', (e) => {
  2449. this.emit('change', this._entries[e.target.selectedIndex][1]);
  2450. });
  2451. this._elements.push(selectElement);
  2452. for (const [name, value] of this._entries) {
  2453. const element = this.createElement('option');
  2454. element.innerText = name;
  2455. if (value === selected) {
  2456. element.setAttribute('selected', 'selected');
  2457. }
  2458. selectElement.appendChild(element);
  2459. }
  2460. }
  2461. render() {
  2462. return this._elements;
  2463. }
  2464. };
  2465. view.ValueTextView = class extends view.Control {
  2466. constructor(context, value, style) {
  2467. super(context);
  2468. this._element = this.createElement('div', 'sidebar-item-value');
  2469. if (value) {
  2470. const list = Array.isArray(value) ? value : [value];
  2471. let className = 'sidebar-item-value-line';
  2472. for (const item of list) {
  2473. const line = this.createElement('div', className);
  2474. switch (style) {
  2475. case 'code':
  2476. line.innerHTML = `<code>${item}<code>`;
  2477. break;
  2478. case 'bold':
  2479. line.innerHTML = `<b>${item}<b>`;
  2480. break;
  2481. case 'nowrap':
  2482. line.innerText = item;
  2483. line.style.whiteSpace = style;
  2484. break;
  2485. default:
  2486. line.innerText = item;
  2487. break;
  2488. }
  2489. this._element.appendChild(line);
  2490. className = 'sidebar-item-value-line-border';
  2491. }
  2492. }
  2493. }
  2494. action(text, callback) {
  2495. this._action = this.createElement('div', 'sidebar-item-value-expander');
  2496. this._action.innerHTML = text;
  2497. this._action.addEventListener('click', () => {
  2498. callback();
  2499. });
  2500. this._element.insertBefore(this._action, this._element.childNodes[0]);
  2501. }
  2502. render() {
  2503. return [this._element];
  2504. }
  2505. toggle() {
  2506. }
  2507. };
  2508. view.AttributeView = class extends view.Control {
  2509. constructor(context, attribute) {
  2510. super(context);
  2511. this._attribute = attribute;
  2512. this._element = this.createElement('div', 'sidebar-item-value');
  2513. const type = this._attribute.type;
  2514. if (type && type !== 'tensor') {
  2515. this._expander = this.createElement('div', 'sidebar-item-value-expander');
  2516. this._expander.innerText = '+';
  2517. this._expander.addEventListener('click', () => {
  2518. this.toggle();
  2519. });
  2520. this._element.appendChild(this._expander);
  2521. }
  2522. const value = this._attribute.value;
  2523. switch (type) {
  2524. case 'graph': {
  2525. const line = this.createElement('div', 'sidebar-item-value-line-link');
  2526. line.innerHTML = value.name || '&nbsp;';
  2527. line.addEventListener('click', () => {
  2528. this.emit('activate', value);
  2529. });
  2530. this._element.appendChild(line);
  2531. break;
  2532. }
  2533. case 'function': {
  2534. const line = this.createElement('div', 'sidebar-item-value-line-link');
  2535. line.innerHTML = value.type.name;
  2536. line.addEventListener('click', () => {
  2537. this.emit('activate', value);
  2538. });
  2539. this._element.appendChild(line);
  2540. break;
  2541. }
  2542. case 'tensor': {
  2543. throw new view.Error('Attribute view tensor not implemented.');
  2544. }
  2545. default: {
  2546. let content = new view.Formatter(value, type).toString();
  2547. if (content && content.length > 1000) {
  2548. content = `${content.substring(0, 1000)}\u2026`;
  2549. }
  2550. if (content && typeof content === 'string') {
  2551. content = content.split('<').join('&lt;').split('>').join('&gt;');
  2552. }
  2553. const line = this.createElement('div', 'sidebar-item-value-line');
  2554. line.innerHTML = content ? content : '&nbsp;';
  2555. this._element.appendChild(line);
  2556. }
  2557. }
  2558. }
  2559. render() {
  2560. return [this._element];
  2561. }
  2562. toggle() {
  2563. if (this._expander.innerText === '+') {
  2564. this._expander.innerText = '-';
  2565. const type = this._attribute.type;
  2566. const value = this._attribute.value;
  2567. const content = type === 'tensor' && value && value.type ? value.type.toString() : this._attribute.type;
  2568. const typeLine = this.createElement('div', 'sidebar-item-value-line-border');
  2569. typeLine.innerHTML = `type: <code><b>${content}</b></code>`;
  2570. this._element.appendChild(typeLine);
  2571. const description = this._attribute.description;
  2572. if (description) {
  2573. const descriptionLine = this.createElement('div', 'sidebar-item-value-line-border');
  2574. descriptionLine.innerHTML = description;
  2575. this._element.appendChild(descriptionLine);
  2576. }
  2577. } else {
  2578. this._expander.innerText = '+';
  2579. while (this._element.childElementCount > 2) {
  2580. this._element.removeChild(this._element.lastChild);
  2581. }
  2582. }
  2583. }
  2584. };
  2585. view.ArgumentView = class extends view.Control {
  2586. constructor(context, argument) {
  2587. super(context);
  2588. this._argument = argument;
  2589. this._elements = [];
  2590. this._items = [];
  2591. for (const value of argument.value) {
  2592. const item = new view.ValueView(context, value);
  2593. item.on('export-tensor', (sender, value) => this.emit('export-tensor', value));
  2594. item.on('activate', (sender, value) => this.emit('activate', value));
  2595. item.on('deactivate', (sender, value) => this.emit('deactivate', value));
  2596. item.on('select', (sender, value) => this.emit('select', value));
  2597. this._items.push(item);
  2598. for (const element of item.render()) {
  2599. this._elements.push(element);
  2600. }
  2601. }
  2602. }
  2603. render() {
  2604. return this._elements;
  2605. }
  2606. toggle() {
  2607. for (const item of this._items) {
  2608. item.toggle();
  2609. }
  2610. }
  2611. };
  2612. view.ValueView = class extends view.Control {
  2613. constructor(context, value, name) {
  2614. super(context);
  2615. this._value = value;
  2616. this._element = this.createElement('div', 'sidebar-item-value');
  2617. try {
  2618. const type = this._value.type;
  2619. const initializer = this._value.initializer;
  2620. const quantization = this._value.quantization;
  2621. const location = this._value.location !== undefined;
  2622. if (initializer) {
  2623. this._element.classList.add('sidebar-item-value-dark');
  2624. }
  2625. if (type || initializer || quantization || location || name !== undefined) {
  2626. this._expander = this.createElement('div', 'sidebar-item-value-expander');
  2627. this._expander.innerText = '+';
  2628. this._expander.addEventListener('click', () => {
  2629. try {
  2630. this.toggle();
  2631. } catch (error) {
  2632. super.error(error, false);
  2633. this._info('ERROR', error.message);
  2634. }
  2635. });
  2636. this._element.appendChild(this._expander);
  2637. }
  2638. const tensor = name !== undefined;
  2639. name = this._value.name ? this._value.name.split('\n').shift() : ''; // custom argument id
  2640. this._hasId = name && !tensor ? true : false;
  2641. this._hasCategory = initializer && initializer.category ? true : false;
  2642. if (this._hasId || (!this._hasCategory && !type && !tensor)) {
  2643. this._hasId = true;
  2644. const element = this.createElement('div', 'sidebar-item-value-line');
  2645. if (typeof name !== 'string') {
  2646. throw new Error(`Invalid value identifier '${JSON.stringify(name)}'.`);
  2647. }
  2648. element.innerHTML = `<span class='sidebar-item-value-line-content'>name: <b>${name || ' '}</b></span>`;
  2649. element.addEventListener('pointerenter', () => this.emit('activate', this._value));
  2650. element.addEventListener('pointerleave', () => this.emit('deactivate', this._value));
  2651. if (!initializer) {
  2652. element.style.cursor = 'pointer';
  2653. element.addEventListener('click', () => this.emit('select', this._value));
  2654. }
  2655. this._element.appendChild(element);
  2656. } else if (this._hasCategory) {
  2657. this._bold('category', initializer.category);
  2658. } else if (type) {
  2659. this._code('tensor', type.toString().split('<').join('&lt;').split('>').join('&gt;'));
  2660. }
  2661. } catch (error) {
  2662. super.error(error, false);
  2663. this._info('ERROR', error.message);
  2664. }
  2665. }
  2666. render() {
  2667. return [this._element];
  2668. }
  2669. toggle() {
  2670. if (this._expander) {
  2671. if (this._expander.innerText === '+') {
  2672. this._expander.innerText = '-';
  2673. try {
  2674. const initializer = this._value.initializer;
  2675. if (this._hasId && this._hasCategory) {
  2676. this._bold('category', initializer.category);
  2677. }
  2678. let type = null;
  2679. let denotation = null;
  2680. if (this._value.type) {
  2681. type = this._value.type.toString();
  2682. denotation = this._value.type.denotation || null;
  2683. }
  2684. if (type && (this._hasId || this._hasCategory)) {
  2685. this._code('tensor', type.split('<').join('&lt;').split('>').join('&gt;'));
  2686. }
  2687. if (denotation) {
  2688. this._code('denotation', denotation);
  2689. }
  2690. const description = this._value.description;
  2691. if (description) {
  2692. const descriptionLine = this.createElement('div', 'sidebar-item-value-line-border');
  2693. descriptionLine.innerHTML = description;
  2694. this._element.appendChild(descriptionLine);
  2695. }
  2696. const quantization = this._value.quantization;
  2697. if (quantization) {
  2698. if (typeof quantization.type !== 'string') {
  2699. throw new view.Error('Unsupported quantization value.');
  2700. }
  2701. const value = new view.Quantization(quantization).toString();
  2702. if (quantization.type && (quantization.type !== 'linear' || (value && value !== 'q'))) {
  2703. const line = this.createElement('div', 'sidebar-item-value-line-border');
  2704. const content = [
  2705. `<span class='sidebar-item-value-line-content'>quantization: <b>${quantization.type}</b></span>`
  2706. ];
  2707. if (value) {
  2708. content.push(`<pre style='margin: 4px 0 2px 0'>${value}</pre>`);
  2709. }
  2710. line.innerHTML = content.join('');
  2711. this._element.appendChild(line);
  2712. }
  2713. }
  2714. const identifier = this._value.identifier;
  2715. if (identifier !== undefined) {
  2716. this._bold('identifier', identifier);
  2717. }
  2718. const layout = this._value.type ? this._value.type.layout : null;
  2719. if (layout) {
  2720. const layouts = new Map([
  2721. ['sparse', 'sparse'],
  2722. ['sparse.coo', 'sparse coo'],
  2723. ['sparse.csr', 'sparse csr'],
  2724. ['sparse.csc', 'sparse csc'],
  2725. ['sparse.bsr', 'sparse bsr'],
  2726. ['sparse.bsc', 'sparse bsc']
  2727. ]);
  2728. this._bold('layout', layouts.get(layout));
  2729. }
  2730. if (initializer) {
  2731. if (initializer.location) {
  2732. this._bold('location', initializer.location);
  2733. }
  2734. this._tensor(initializer);
  2735. }
  2736. } catch (error) {
  2737. super.error(error, false);
  2738. this._info('ERROR', error.message);
  2739. }
  2740. } else {
  2741. this._expander.innerText = '+';
  2742. while (this._element.childElementCount > 2) {
  2743. this._element.removeChild(this._element.lastChild);
  2744. }
  2745. }
  2746. }
  2747. }
  2748. _bold(name, value) {
  2749. const line = this.createElement('div');
  2750. line.innerHTML = `${name}: <b>${value}</b>`;
  2751. this._add(line);
  2752. }
  2753. _code(name, value) {
  2754. const line = this.createElement('div');
  2755. line.innerHTML = `${name}: <code><b>${value}</b></code>`;
  2756. this._add(line);
  2757. }
  2758. _info(name, value) {
  2759. const line = this.createElement('div');
  2760. line.innerHTML = `<b>${name}:</b> ${value}`;
  2761. this._add(line);
  2762. }
  2763. _add(child) {
  2764. child.className = this._element.childNodes.length < 2 ? 'sidebar-item-value-line' : 'sidebar-item-value-line-border';
  2765. this._element.appendChild(child);
  2766. }
  2767. _tensor(value) {
  2768. const contentLine = this.createElement('pre');
  2769. const tensor = new view.Tensor(value);
  2770. if (Array.isArray(tensor.stride) && tensor.stride.length > 0) {
  2771. this._code('stride', tensor.stride.join(','));
  2772. }
  2773. if (tensor.encoding !== '<' && tensor.encoding !== '>' && tensor.encoding !== '|') {
  2774. contentLine.innerHTML = `Tensor encoding '${tensor.layout}' is not implemented.`;
  2775. } else if (tensor.layout && (tensor.layout !== 'sparse' && tensor.layout !== 'sparse.coo')) {
  2776. contentLine.innerHTML = `Tensor layout '${tensor.layout}' is not implemented.`;
  2777. } else if (tensor.empty) {
  2778. contentLine.innerHTML = 'Tensor data is empty.';
  2779. } else if (tensor.type && tensor.type.dataType === '?') {
  2780. contentLine.innerHTML = 'Tensor data type is not defined.';
  2781. } else if (tensor.type && !tensor.type.shape) {
  2782. contentLine.innerHTML = 'Tensor shape is not defined.';
  2783. } else {
  2784. contentLine.innerHTML = tensor.toString();
  2785. if (this._host.save &&
  2786. value.type.shape && value.type.shape.dimensions &&
  2787. value.type.shape.dimensions.length > 0) {
  2788. this._saveButton = this.createElement('div', 'sidebar-item-value-expander');
  2789. this._saveButton.innerHTML = '&#x1F4BE;';
  2790. this._saveButton.addEventListener('click', () => {
  2791. this.emit('export-tensor', tensor);
  2792. });
  2793. this._element.appendChild(this._saveButton);
  2794. }
  2795. }
  2796. const valueLine = this.createElement('div', 'sidebar-item-value-line-border');
  2797. valueLine.appendChild(contentLine);
  2798. this._element.appendChild(valueLine);
  2799. }
  2800. };
  2801. view.NodeView = class extends view.Control {
  2802. constructor(context, node) {
  2803. super(context);
  2804. this._node = node;
  2805. this._element = this.createElement('div', 'sidebar-item-value');
  2806. const name = node.name;
  2807. const type = node.type ? node.type.name : '';
  2808. if (name && type) {
  2809. this._expander = this.createElement('div', 'sidebar-item-value-expander');
  2810. this._expander.innerText = '+';
  2811. this._expander.addEventListener('click', () => {
  2812. this.toggle();
  2813. });
  2814. this._element.appendChild(this._expander);
  2815. }
  2816. if (type) {
  2817. const type = node.type.name;
  2818. const element = this.createElement('div', 'sidebar-item-value-line');
  2819. element.innerHTML = `<span class='sidebar-item-value-line-content'>node: <b>${type || ' '}</b></span>`;
  2820. element.addEventListener('pointerenter', () => this.emit('activate', this._node));
  2821. element.addEventListener('pointerleave', () => this.emit('deactivate', this._node));
  2822. element.addEventListener('click', () => this.emit('select', this._node));
  2823. element.style.cursor = 'pointer';
  2824. this._element.appendChild(element);
  2825. } else {
  2826. const element = this.createElement('div', 'sidebar-item-value-line');
  2827. element.innerHTML = `<span class='sidebar-item-value-line-content'>name: <b>${name || ' '}</b></span>`;
  2828. element.addEventListener('pointerenter', () => this.emit('activate', this._node));
  2829. element.addEventListener('pointerleave', () => this.emit('deactivate', this._node));
  2830. element.addEventListener('click', () => this.emit('select', this._node));
  2831. element.style.cursor = 'pointer';
  2832. this._element.appendChild(element);
  2833. }
  2834. }
  2835. render() {
  2836. return [this._element];
  2837. }
  2838. toggle() {
  2839. if (this._expander) {
  2840. if (this._expander.innerText === '+') {
  2841. this._expander.innerText = '-';
  2842. const name = this._node.name;
  2843. const element = this.createElement('div', 'sidebar-item-value-line-border');
  2844. element.innerHTML = `<span class='sidebar-item-value-line-content'>name: <b>${name}</b></span>`;
  2845. element.addEventListener('pointerenter', () => this.emit('activate', this._node));
  2846. element.addEventListener('pointerleave', () => this.emit('deactivate', this._node));
  2847. element.addEventListener('click', () => this.emit('select', this._node));
  2848. element.style.cursor = 'pointer';
  2849. this._element.appendChild(element);
  2850. } else {
  2851. this._expander.innerText = '+';
  2852. while (this._element.childElementCount > 2) {
  2853. this._element.removeChild(this._element.lastChild);
  2854. }
  2855. }
  2856. }
  2857. }
  2858. };
  2859. view.NodeListView = class extends view.Control {
  2860. constructor(context, list) {
  2861. super(context);
  2862. this._elements = [];
  2863. for (const node of list) {
  2864. const item = new view.NodeView(this._view, node);
  2865. item.on('activate', (sender, value) => this.emit('activate', value));
  2866. item.on('deactivate', (sender, value) => this.emit('deactivate', value));
  2867. item.on('select', (sender, value) => this.emit('select', value));
  2868. item.toggle();
  2869. for (const element of item.render()) {
  2870. this._elements.push(element);
  2871. }
  2872. }
  2873. }
  2874. render() {
  2875. return this._elements;
  2876. }
  2877. };
  2878. view.ConnectionSidebar = class extends view.ObjectSidebar {
  2879. constructor(context, value, from, to) {
  2880. super(context);
  2881. this._value = value;
  2882. this._from = from;
  2883. this._to = to;
  2884. }
  2885. render() {
  2886. const value = this._value;
  2887. const from = this._from;
  2888. const to = this._to;
  2889. const [name] = value.name.split('\n');
  2890. this.addProperty('name', name);
  2891. if (value.type) {
  2892. const item = new view.ValueView(this._view, value, '');
  2893. this.add('type', item);
  2894. item.toggle();
  2895. }
  2896. if (from) {
  2897. this.addHeader('Inputs');
  2898. const list = new view.NodeListView(this._view, [from]);
  2899. list.on('activate', (sender, value) => this.emit('activate', value));
  2900. list.on('deactivate', (sender, value) => this.emit('deactivate', value));
  2901. list.on('select', (sender, value) => this.emit('select', value));
  2902. const item = new view.NameValueView(this._view, 'from', list);
  2903. this.element.appendChild(item.render());
  2904. }
  2905. if (Array.isArray(to) && to.length > 0) {
  2906. this.addHeader('Outputs');
  2907. const list = new view.NodeListView(this._view, to);
  2908. list.on('activate', (sender, value) => this.emit('activate', value));
  2909. list.on('deactivate', (sender, value) => this.emit('deactivate', value));
  2910. list.on('select', (sender, value) => this.emit('select', value));
  2911. const item = new view.NameValueView(this._view, 'to', list);
  2912. this.element.appendChild(item.render());
  2913. }
  2914. }
  2915. };
  2916. view.ModelSidebar = class extends view.ObjectSidebar {
  2917. constructor(context, model, graph, signature) {
  2918. super(context);
  2919. this._model = model;
  2920. this._graph = graph;
  2921. this._signature = signature;
  2922. }
  2923. render() {
  2924. const model = this._model;
  2925. const graph = this._graph;
  2926. const signature = this._signature;
  2927. if (model.format) {
  2928. this.addProperty('format', model.format);
  2929. }
  2930. if (model.producer) {
  2931. this.addProperty('producer', model.producer);
  2932. }
  2933. if (model.name) {
  2934. this.addProperty('name', model.name);
  2935. }
  2936. if (model.version) {
  2937. this.addProperty('version', model.version);
  2938. }
  2939. if (model.description) {
  2940. this.addProperty('description', model.description);
  2941. }
  2942. if (model.domain) {
  2943. this.addProperty('domain', model.domain);
  2944. }
  2945. if (model.imports) {
  2946. this.addProperty('imports', model.imports);
  2947. }
  2948. if (model.runtime) {
  2949. this.addProperty('runtime', model.runtime);
  2950. }
  2951. if (model.source) {
  2952. this.addProperty('source', model.source);
  2953. }
  2954. const graphs = Array.isArray(model.graphs) ? model.graphs : [];
  2955. if (graphs.length === 1 && graphs[0].name) {
  2956. this.addProperty('graph', graphs[0].name);
  2957. } else if (graphs.length > 1) {
  2958. const entries = new Map();
  2959. for (const graph of model.graphs) {
  2960. entries.set(graph.name, graph);
  2961. }
  2962. const selector = new view.SelectView(this._view, entries, graph);
  2963. selector.on('change', (sender, data) => this.emit('update-active-graph', data));
  2964. this.add('graph', selector);
  2965. }
  2966. if (graph && Array.isArray(graph.signatures) && graph.signatures.length > 0) {
  2967. const entries = new Map();
  2968. entries.set('', graph);
  2969. for (const signature of graph.signatures) {
  2970. entries.set(signature.name, signature);
  2971. }
  2972. const selector = new view.SelectView(this._view, entries, signature || graph);
  2973. selector.on('change', (sender, data) => this.emit('update-active-graph-signature', data));
  2974. this.add('signature', selector);
  2975. }
  2976. const metadata = model.metadata instanceof Map ?
  2977. Array.from(model.metadata).map(([name, value]) => ({ name, value })) :
  2978. model.metadata;
  2979. if (Array.isArray(metadata) && metadata.length > 0) {
  2980. this.addHeader('Metadata');
  2981. for (const argument of model.metadata) {
  2982. this.addProperty(argument.name, argument.value);
  2983. }
  2984. }
  2985. if (graph) {
  2986. if (graph.version) {
  2987. this.addProperty('version', graph.version);
  2988. }
  2989. if (graph.type) {
  2990. this.addProperty('type', graph.type);
  2991. }
  2992. if (graph.tags) {
  2993. this.addProperty('tags', graph.tags);
  2994. }
  2995. if (graph.description) {
  2996. this.addProperty('description', graph.description);
  2997. }
  2998. const inputs = signature ? signature.inputs : graph.inputs;
  2999. const outputs = signature ? signature.outputs : graph.outputs;
  3000. if (Array.isArray(inputs) && inputs.length > 0) {
  3001. this.addHeader('Inputs');
  3002. for (const input of inputs) {
  3003. this.addArgument(input.name, input);
  3004. }
  3005. }
  3006. if (Array.isArray(outputs) && outputs.length > 0) {
  3007. this.addHeader('Outputs');
  3008. for (const output of outputs) {
  3009. this.addArgument(output.name, output);
  3010. }
  3011. }
  3012. }
  3013. }
  3014. addArgument(name, argument) {
  3015. const value = new view.ArgumentView(this._view, argument);
  3016. value.toggle();
  3017. const item = new view.NameValueView(this._view, name, value);
  3018. this.element.appendChild(item.render());
  3019. }
  3020. };
  3021. view.DocumentationSidebar = class extends view.Control {
  3022. constructor(context, type) {
  3023. super(context);
  3024. this._type = type;
  3025. }
  3026. render() {
  3027. if (!this.element) {
  3028. this.element = this.createElement('div', 'sidebar-documentation');
  3029. const type = view.Documentation.format(this._type);
  3030. this._append(this.element, 'h1', type.name);
  3031. if (type.summary) {
  3032. this._append(this.element, 'p', type.summary);
  3033. }
  3034. if (type.description) {
  3035. this._append(this.element, 'p', type.description);
  3036. }
  3037. if (Array.isArray(type.attributes) && type.attributes.length > 0) {
  3038. this._append(this.element, 'h2', 'Attributes');
  3039. const attributes = this._append(this.element, 'dl');
  3040. for (const attribute of type.attributes) {
  3041. this._append(attributes, 'dt', attribute.name + (attribute.type ? `: <tt>${attribute.type}</tt>` : ''));
  3042. this._append(attributes, 'dd', attribute.description);
  3043. }
  3044. this.element.appendChild(attributes);
  3045. }
  3046. if (Array.isArray(type.inputs) && type.inputs.length > 0) {
  3047. this._append(this.element, 'h2', `Inputs${type.inputs_range ? ` (${type.inputs_range})` : ''}`);
  3048. const inputs = this._append(this.element, 'dl');
  3049. for (const input of type.inputs) {
  3050. this._append(inputs, 'dt', input.name + (input.type ? `: <tt>${input.type}</tt>` : '') + (input.option ? ` (${input.option})` : ''));
  3051. this._append(inputs, 'dd', input.description);
  3052. }
  3053. }
  3054. if (Array.isArray(type.outputs) && type.outputs.length > 0) {
  3055. this._append(this.element, 'h2', `Outputs${type.outputs_range ? ` (${type.outputs_range})` : ''}`);
  3056. const outputs = this._append(this.element, 'dl');
  3057. for (const output of type.outputs) {
  3058. this._append(outputs, 'dt', output.name + (output.type ? `: <tt>${output.type}</tt>` : '') + (output.option ? ` (${output.option})` : ''));
  3059. this._append(outputs, 'dd', output.description);
  3060. }
  3061. }
  3062. if (Array.isArray(type.type_constraints) && type.type_constraints.length > 0) {
  3063. this._append(this.element, 'h2', 'Type Constraints');
  3064. const type_constraints = this._append(this.element, 'dl');
  3065. for (const type_constraint of type.type_constraints) {
  3066. this._append(type_constraints, 'dt', `${type_constraint.type_param_str}: ${type_constraint.allowed_type_strs.map((item) => `<tt>${item}</tt>`).join(', ')}`);
  3067. this._append(type_constraints, 'dd', type_constraint.description);
  3068. }
  3069. }
  3070. if (Array.isArray(type.examples) && type.examples.length > 0) {
  3071. this._append(this.element, 'h2', 'Examples');
  3072. for (const example of type.examples) {
  3073. this._append(this.element, 'h3', example.summary);
  3074. this._append(this.element, 'pre', example.code);
  3075. }
  3076. }
  3077. if (Array.isArray(type.references) && type.references.length > 0) {
  3078. this._append(this.element, 'h2', 'References');
  3079. const references = this._append(this.element, 'ul');
  3080. for (const reference of type.references) {
  3081. this._append(references, 'li', reference.description);
  3082. }
  3083. }
  3084. if (this._host.type === 'Electron') {
  3085. this.element.addEventListener('click', (e) => {
  3086. if (e.target && e.target.href) {
  3087. const url = e.target.href;
  3088. if (url.startsWith('http://') || url.startsWith('https://')) {
  3089. e.preventDefault();
  3090. this.emit('navigate', { link: url });
  3091. }
  3092. }
  3093. });
  3094. }
  3095. }
  3096. }
  3097. _append(parent, type, content) {
  3098. const element = this.createElement(type);
  3099. if (content) {
  3100. element.innerHTML = content;
  3101. }
  3102. parent.appendChild(element);
  3103. return element;
  3104. }
  3105. error(error, fatal) {
  3106. super.error(error, fatal);
  3107. const element = this.createElement('span');
  3108. element.innerHTML = `<b>ERROR:</b> ${error.message}`;
  3109. this.element.appendChild(element);
  3110. }
  3111. };
  3112. view.FindSidebar = class extends view.Control {
  3113. constructor(context, graph, signature) {
  3114. super(context);
  3115. this._graph = graph;
  3116. this._signature = signature;
  3117. this._state = {
  3118. query: '',
  3119. node: true,
  3120. connection: true,
  3121. weight: true
  3122. };
  3123. this._toggles = {
  3124. node: { hide: 'Hide Nodes', show: 'Show Nodes' },
  3125. connection: { hide: 'Hide Connections', show: 'Show Connections' },
  3126. weight: { hide: 'Hide Weights', show: 'Show Weights' }
  3127. };
  3128. }
  3129. on(event, callback) {
  3130. this._events = this._events || {};
  3131. this._events[event] = this._events[event] || [];
  3132. this._events[event].push(callback);
  3133. }
  3134. emit(event, data) {
  3135. if (this._events && this._events[event]) {
  3136. for (const callback of this._events[event]) {
  3137. callback(this, data);
  3138. }
  3139. }
  3140. }
  3141. focus(state) {
  3142. this._state = state || this._state;
  3143. this._query.focus();
  3144. this._query.value = '';
  3145. this._query.value = this._state.query;
  3146. for (const [name, toggle] of Object.entries(this._toggles)) {
  3147. toggle.checkbox.checked = this._state[name];
  3148. toggle.element.setAttribute('title', this._state[name] ? toggle.hide : toggle.show);
  3149. }
  3150. this._update();
  3151. }
  3152. _clear() {
  3153. this._table.clear();
  3154. this._index = 0;
  3155. const unquote = this._state.query.match(new RegExp(/^'(.*)'|"(.*)"$/));
  3156. if (unquote) {
  3157. this._exact = true;
  3158. const term = unquote[1] || unquote[2];
  3159. this._terms = [term];
  3160. } else {
  3161. this._exact = false;
  3162. this._terms = this._state.query.trim().toLowerCase().split(' ').map((term) => term.trim()).filter((term) => term.length > 0);
  3163. }
  3164. }
  3165. _term(value) {
  3166. return this._exact ?
  3167. value === this._terms[0] :
  3168. this._terms.every((term) => value && value.toLowerCase().indexOf(term) !== -1);
  3169. }
  3170. _value(value) {
  3171. if (this._terms.length === 0) {
  3172. return true;
  3173. }
  3174. if (value.name && this._term(value.name.split('\n').shift())) {
  3175. return true;
  3176. }
  3177. if (value.location && this._term(value.location)) {
  3178. return true;
  3179. }
  3180. if (value.type && !this._exact) {
  3181. for (const term of this._terms) {
  3182. if (value.type.dataType && term === value.type.dataType.toLowerCase()) {
  3183. return true;
  3184. }
  3185. if (value.type.shape) {
  3186. if (term === value.type.shape.toString().toLowerCase()) {
  3187. return true;
  3188. }
  3189. if (value.type.shape && Array.isArray(value.type.shape.dimensions)) {
  3190. const dimensions = value.type.shape.dimensions.map((dimension) => dimension ? dimension.toString().toLowerCase() : '');
  3191. if (term === dimensions.join(',')) {
  3192. return true;
  3193. }
  3194. if (dimensions.some((dimension) => term === dimension)) {
  3195. return true;
  3196. }
  3197. }
  3198. }
  3199. }
  3200. }
  3201. return false;
  3202. }
  3203. _add(value, content, icon) {
  3204. const key = this._index.toString();
  3205. this._index++;
  3206. this._table.set(key, value);
  3207. const element = this.createElement('li');
  3208. element.innerHTML = `<svg class='sidebar-find-content-icon'><use href="#sidebar-find-icon-${icon}"></use></svg>`;
  3209. const text = this.createElement('span');
  3210. text.innerText = content;
  3211. element.appendChild(text);
  3212. element.setAttribute('data', key);
  3213. element.addEventListener('pointerover', (e) => {
  3214. const identifier = e.target.getAttribute('data');
  3215. if (this._table.has(identifier)) {
  3216. this.emit('focus', this._table.get(identifier));
  3217. }
  3218. });
  3219. element.addEventListener('pointerleave', (e) => {
  3220. const identifier = e.target.getAttribute('data');
  3221. if (this._table.has(identifier)) {
  3222. this.emit('blur', this._table.get(identifier));
  3223. }
  3224. });
  3225. this._content.appendChild(element);
  3226. }
  3227. _update() {
  3228. this._content.innerHTML = '';
  3229. try {
  3230. this._clear();
  3231. const edges = new Set();
  3232. const edge = (value) => {
  3233. if (value.name && !edges.has(value.name) && this._value(value)) {
  3234. const content = `${value.name.split('\n').shift()}`;
  3235. this._add(value, content, 'connection'); // split custom argument id
  3236. edges.add(value.name);
  3237. }
  3238. };
  3239. const inputs = this._signature ? this._signature.inputs : this._graph.inputs;
  3240. if (this._state.connection) {
  3241. for (const input of inputs) {
  3242. for (const value of input.value) {
  3243. edge(value);
  3244. }
  3245. }
  3246. }
  3247. for (const node of this._graph.nodes) {
  3248. if (this._state.connection) {
  3249. for (const input of node.inputs) {
  3250. for (const value of input.value) {
  3251. if (!value.initializer) {
  3252. edge(value);
  3253. }
  3254. }
  3255. }
  3256. }
  3257. if (this._state.node) {
  3258. const name = node.name;
  3259. const type = node.type.name;
  3260. const location = node.location;
  3261. if ((name && this._term(name)) || (type && this._term(type)) || (location && this._term(location))) {
  3262. const content = `${name || `[${type}]`}`;
  3263. this._add(node, content, 'node');
  3264. }
  3265. }
  3266. if (this._state.weight) {
  3267. for (const input of node.inputs) {
  3268. for (const value of input.value) {
  3269. if (value.initializer && value.name && !edges.has(value.name) && this._value(value)) {
  3270. const content = `${value.name.split('\n').shift()}`;
  3271. this._add(node, content, 'weight'); // split custom argument id
  3272. }
  3273. }
  3274. }
  3275. }
  3276. }
  3277. if (this._state.connection) {
  3278. const outputs = this._signature ? this._signature.outputs : this._graph.inputs;
  3279. for (const output of outputs) {
  3280. for (const value of output.value) {
  3281. edge(value);
  3282. }
  3283. }
  3284. }
  3285. } catch (error) {
  3286. this.error(error, false);
  3287. }
  3288. }
  3289. render() {
  3290. this._table = new Map();
  3291. this._search = this.createElement('div', 'sidebar-find-search');
  3292. this._query = this.createElement('input', 'sidebar-find-query');
  3293. this._search.appendChild(this._query);
  3294. this._content = this.createElement('ol', 'sidebar-find-content');
  3295. this._elements = [this._query, this._content];
  3296. this._query.setAttribute('id', 'search');
  3297. this._query.setAttribute('type', 'text');
  3298. this._query.setAttribute('spellcheck', 'false');
  3299. this._query.setAttribute('placeholder', 'Search');
  3300. this._query.addEventListener('input', (e) => {
  3301. this._state.query = e.target.value;
  3302. this.emit('state-changed', this._state);
  3303. this._update();
  3304. });
  3305. this._query.addEventListener('keydown', (e) => {
  3306. if (e.keyCode === 0x08 && !e.altKey && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
  3307. e.stopPropagation();
  3308. }
  3309. });
  3310. for (const [name, toggle] of Object.entries(this._toggles)) {
  3311. toggle.element = this.createElement('label', 'sidebar-find-toggle');
  3312. toggle.element.innerHTML = `<svg class='sidebar-find-toggle-icon'><use href="#sidebar-find-icon-${name}"></use></svg>`;
  3313. toggle.element.setAttribute('title', this._state[name] ? toggle.hide : toggle.show);
  3314. toggle.checkbox = this.createElement('input');
  3315. toggle.checkbox.setAttribute('type', 'checkbox');
  3316. toggle.checkbox.setAttribute('data', name);
  3317. toggle.checkbox.addEventListener('change', (e) => {
  3318. const name = e.target.getAttribute('data');
  3319. this._state[name] = e.target.checked;
  3320. const toggle = this._toggles[name];
  3321. toggle.element.setAttribute('title', e.target.checked ? toggle.hide : toggle.show);
  3322. this.emit('state-changed', this._state);
  3323. this._update();
  3324. });
  3325. toggle.element.insertBefore(toggle.checkbox, toggle.element.firstChild);
  3326. this._search.appendChild(toggle.element);
  3327. }
  3328. this._content.addEventListener('click', (e) => {
  3329. const name = e.target.getAttribute('data');
  3330. if (this._table.has(name)) {
  3331. this.emit('select', this._table.get(name));
  3332. }
  3333. });
  3334. }
  3335. get element() {
  3336. return [this._search, this._content];
  3337. }
  3338. error(error, fatal) {
  3339. super.error(error, fatal);
  3340. const element = this.createElement('li');
  3341. element.innerHTML = `<b>ERROR:</b> ${error.message}`;
  3342. this._content.appendChild(element);
  3343. }
  3344. };
  3345. view.Tensor = class {
  3346. constructor(tensor) {
  3347. this._tensor = tensor;
  3348. this._type = tensor.type;
  3349. this._encoding = tensor.encoding;
  3350. this._layout = tensor.type.layout;
  3351. this._stride = tensor.stride;
  3352. switch (this._encoding) {
  3353. case undefined:
  3354. case '':
  3355. case '<': {
  3356. this._data = this._tensor.values;
  3357. this._encoding = '<';
  3358. this._littleEndian = true;
  3359. break;
  3360. }
  3361. case '>': {
  3362. this._data = this._tensor.values;
  3363. this._encoding = '>';
  3364. this._littleEndian = false;
  3365. break;
  3366. }
  3367. case '|': {
  3368. this._values = this._tensor.values;
  3369. this._encoding = '|';
  3370. break;
  3371. }
  3372. default: {
  3373. throw new view.Error(`Unsupported tensor encoding '${this._encoding}'.`);
  3374. }
  3375. }
  3376. switch (this._layout) {
  3377. case 'sparse':
  3378. case 'sparse.coo': {
  3379. this._indices = this._tensor.indices;
  3380. this._values = this._tensor.values;
  3381. break;
  3382. }
  3383. default: {
  3384. break;
  3385. }
  3386. }
  3387. view.Tensor.dataTypes = view.Tensor.dataTypeSizes || new Map([
  3388. ['boolean', 1],
  3389. ['qint8', 1], ['qint16', 2], ['qint32', 4],
  3390. ['quint8', 1], ['quint16', 2], ['quint32', 4],
  3391. ['xint8', 1],
  3392. ['int8', 1], ['int16', 2], ['int32', 4], ['int64', 8],
  3393. ['uint8', 1], ['uint16', 2], ['uint32', 4,], ['uint64', 8],
  3394. ['float16', 2], ['float32', 4], ['float64', 8], ['bfloat16', 2],
  3395. ['complex64', 8], ['complex128', 16],
  3396. ['float8e4m3fn', 1], ['float8e4m3fnuz', 1], ['float8e5m2', 1], ['float8e5m2fnuz', 1]
  3397. ]);
  3398. }
  3399. get type() {
  3400. return this._type;
  3401. }
  3402. get encoding() {
  3403. return this._encoding;
  3404. }
  3405. get layout() {
  3406. return this._layout;
  3407. }
  3408. get stride() {
  3409. return this._stride;
  3410. }
  3411. get empty() {
  3412. switch (this._layout) {
  3413. case 'sparse':
  3414. case 'sparse.coo': {
  3415. return !this._values || this.indices || this._values.values === null || this._values.values.length === 0;
  3416. }
  3417. default: {
  3418. switch (this._encoding) {
  3419. case '<':
  3420. case '>':
  3421. return !(Array.isArray(this._data) || this._data instanceof Uint8Array || this._data instanceof Int8Array) || this._data.length === 0;
  3422. case '|':
  3423. return !(Array.isArray(this._values) || ArrayBuffer.isView(this._values)) || this._values.length === 0;
  3424. default:
  3425. throw new Error(`Unsupported tensor encoding '${this._encoding}'.`);
  3426. }
  3427. }
  3428. }
  3429. }
  3430. get value() {
  3431. const context = this._context();
  3432. context.limit = Number.MAX_SAFE_INTEGER;
  3433. switch (context.encoding) {
  3434. case '<':
  3435. case '>': {
  3436. return this._decodeData(context, 0, 0);
  3437. }
  3438. case '|': {
  3439. return this._decodeValues(context, 0, 0);
  3440. }
  3441. default: {
  3442. throw new Error(`Unsupported tensor encoding '${context.encoding}'.`);
  3443. }
  3444. }
  3445. }
  3446. toString() {
  3447. const context = this._context();
  3448. context.limit = 10000;
  3449. switch (context.encoding) {
  3450. case '<':
  3451. case '>': {
  3452. const value = this._decodeData(context, 0, 0);
  3453. return view.Tensor._stringify(value, '', ' ');
  3454. }
  3455. case '|': {
  3456. const value = this._decodeValues(context, 0, 0);
  3457. return view.Tensor._stringify(value, '', ' ');
  3458. }
  3459. default: {
  3460. throw new Error(`Unsupported tensor encoding '${context.encoding}'.`);
  3461. }
  3462. }
  3463. }
  3464. _context() {
  3465. if (this._encoding !== '<' && this._encoding !== '>' && this._encoding !== '|') {
  3466. throw new Error(`Tensor encoding '${this._encoding}' is not supported.`);
  3467. }
  3468. if (this._layout && (this._layout !== 'sparse' && this._layout !== 'sparse.coo')) {
  3469. throw new Error(`Tensor layout '${this._layout}' is not supported.`);
  3470. }
  3471. const dataType = this._type.dataType;
  3472. const context = {};
  3473. context.encoding = this._encoding;
  3474. context.dimensions = this._type.shape.dimensions.map((value) => typeof value === 'bigint' ? value.toNumber() : value);
  3475. context.dataType = dataType;
  3476. const shape = context.dimensions;
  3477. context.stride = this._stride;
  3478. if (!Array.isArray(context.stride)) {
  3479. context.stride = new Array(shape.length);
  3480. let value = 1;
  3481. for (let i = shape.length - 1; i >= 0; i--) {
  3482. context.stride[i] = value;
  3483. value *= shape[i];
  3484. }
  3485. }
  3486. switch (this._layout) {
  3487. case 'sparse': {
  3488. const indices = new view.Tensor(this._indices).value;
  3489. const values = new view.Tensor(this._values).value;
  3490. context.data = this._decodeSparse(dataType, context.dimensions, indices, values);
  3491. context.encoding = '|';
  3492. break;
  3493. }
  3494. case 'sparse.coo': {
  3495. const values = new view.Tensor(this._values).value;
  3496. const data = new view.Tensor(this._indices).value;
  3497. const dimensions = context.dimensions.length;
  3498. let stride = 1;
  3499. const strides = context.dimensions.slice().reverse().map((dim) => {
  3500. const value = stride;
  3501. stride *= dim;
  3502. return value;
  3503. }).reverse();
  3504. const indices = new Uint32Array(values.length);
  3505. for (let i = 0; i < dimensions; i++) {
  3506. const stride = strides[i];
  3507. const dimension = data[i];
  3508. for (let i = 0; i < indices.length; i++) {
  3509. indices[i] += dimension[i].toNumber() * stride;
  3510. }
  3511. }
  3512. context.data = this._decodeSparse(dataType, context.dimensions, indices, values);
  3513. context.encoding = '|';
  3514. break;
  3515. }
  3516. default: {
  3517. switch (this._encoding) {
  3518. case '<':
  3519. case '>': {
  3520. context.data = (this._data instanceof Uint8Array || this._data instanceof Int8Array) ? this._data : this._data.peek();
  3521. context.view = new DataView(context.data.buffer, context.data.byteOffset, context.data.byteLength);
  3522. if (view.Tensor.dataTypes.has(dataType)) {
  3523. const itemsize = view.Tensor.dataTypes.get(dataType);
  3524. const length = context.data.length;
  3525. const stride = context.stride;
  3526. if (length < (itemsize * shape.reduce((a, v) => a * v, 1))) {
  3527. const max = stride.reduce((a, v, i) => v > stride[i] ? i : a, 0);
  3528. if (length !== (itemsize * stride[max] * shape[max])) {
  3529. throw new Error('Invalid tensor data size.');
  3530. }
  3531. }
  3532. context.itemsize = itemsize;
  3533. context.stride = stride.map((v) => v * itemsize);
  3534. } else if (dataType.startsWith('uint') && !isNaN(parseInt(dataType.substring(4), 10))) {
  3535. context.dataType = 'uint';
  3536. context.bits = parseInt(dataType.substring(4), 10);
  3537. context.itemsize = 1;
  3538. } else if (dataType.startsWith('int') && !isNaN(parseInt(dataType.substring(3), 10))) {
  3539. context.dataType = 'int';
  3540. context.bits = parseInt(dataType.substring(3), 10);
  3541. context.itemsize = 1;
  3542. } else {
  3543. throw new Error(`Tensor data type '${dataType}' is not implemented.`);
  3544. }
  3545. break;
  3546. }
  3547. case '|': {
  3548. context.data = this._values;
  3549. if (!view.Tensor.dataTypes.has(dataType) && dataType !== 'string' && dataType !== 'object') {
  3550. throw new Error(`Tensor data type '${dataType}' is not implemented.`);
  3551. }
  3552. const size = context.dimensions.reduce((a, v) => a * v, 1);
  3553. if (size !== this._values.length) {
  3554. throw new Error('Invalid tensor data length.');
  3555. }
  3556. break;
  3557. }
  3558. default: {
  3559. throw new view.Tensor(`Unsupported tensor encoding '${this._encoding}'.`);
  3560. }
  3561. }
  3562. }
  3563. }
  3564. context.index = 0;
  3565. context.count = 0;
  3566. return context;
  3567. }
  3568. _decodeSparse(dataType, dimensions, indices, values) {
  3569. const size = dimensions.reduce((a, b) => a * b, 1);
  3570. const array = new Array(size);
  3571. switch (dataType) {
  3572. case 'boolean':
  3573. array.fill(false);
  3574. break;
  3575. default:
  3576. array.fill(0);
  3577. break;
  3578. }
  3579. if (indices.length > 0) {
  3580. if (Object.prototype.hasOwnProperty.call(indices[0], 'low')) {
  3581. for (let i = 0; i < indices.length; i++) {
  3582. const index = indices[i].toNumber();
  3583. array[index] = values[i];
  3584. }
  3585. } else {
  3586. for (let i = 0; i < indices.length; i++) {
  3587. array[indices[i]] = values[i];
  3588. }
  3589. }
  3590. }
  3591. return array;
  3592. }
  3593. _decodeData(context, dimension, offset) {
  3594. const results = [];
  3595. const shape = context.dimensions.length === 0 ? [1] : context.dimensions;
  3596. const size = shape[dimension];
  3597. const dataType = context.dataType;
  3598. const view = context.view;
  3599. const stride = context.stride[dimension];
  3600. if (dimension === shape.length - 1) {
  3601. const ellipsis = (context.count + size) > context.limit;
  3602. const length = ellipsis ? context.limit - context.count : size;
  3603. const max = offset + (length * context.itemsize);
  3604. switch (dataType) {
  3605. case 'boolean':
  3606. for (; offset < max; offset += stride) {
  3607. results.push(view.getUint8(offset) !== 0);
  3608. }
  3609. break;
  3610. case 'qint8':
  3611. case 'xint8':
  3612. case 'int8':
  3613. for (; offset < max; offset += stride) {
  3614. results.push(view.getInt8(offset));
  3615. }
  3616. break;
  3617. case 'qint16':
  3618. case 'int16':
  3619. for (; offset < max; offset += stride) {
  3620. results.push(view.getInt16(offset, this._littleEndian));
  3621. }
  3622. break;
  3623. case 'qint32':
  3624. case 'int32':
  3625. for (; offset < max; offset += stride) {
  3626. results.push(view.getInt32(offset, this._littleEndian));
  3627. }
  3628. break;
  3629. case 'int64':
  3630. for (; offset < max; offset += stride) {
  3631. results.push(view.getBigInt64(offset, this._littleEndian));
  3632. }
  3633. break;
  3634. case 'int':
  3635. for (; offset < max; offset += stride) {
  3636. results.push(view.getIntBits(offset, context.bits, this._littleEndian));
  3637. }
  3638. break;
  3639. case 'quint8':
  3640. case 'uint8':
  3641. for (; offset < max; offset += stride) {
  3642. results.push(view.getUint8(offset));
  3643. }
  3644. break;
  3645. case 'quint16':
  3646. case 'uint16':
  3647. for (; offset < max; offset += stride) {
  3648. results.push(view.getUint16(offset, true));
  3649. }
  3650. break;
  3651. case 'quint32':
  3652. case 'uint32':
  3653. for (; offset < max; offset += stride) {
  3654. results.push(view.getUint32(offset, true));
  3655. }
  3656. break;
  3657. case 'uint64':
  3658. for (; offset < max; offset += stride) {
  3659. results.push(view.getBigUint64(offset, true));
  3660. }
  3661. break;
  3662. case 'uint':
  3663. for (; offset < max; offset += stride) {
  3664. results.push(view.getUintBits(offset, context.bits, this._littleEndian));
  3665. }
  3666. break;
  3667. case 'float16':
  3668. for (; offset < max; offset += stride) {
  3669. results.push(view.getFloat16(offset, this._littleEndian));
  3670. }
  3671. break;
  3672. case 'float32':
  3673. for (; offset < max; offset += stride) {
  3674. results.push(view.getFloat32(offset, this._littleEndian));
  3675. }
  3676. break;
  3677. case 'float64':
  3678. for (; offset < max; offset += stride) {
  3679. results.push(view.getFloat64(offset, this._littleEndian));
  3680. }
  3681. break;
  3682. case 'bfloat16':
  3683. for (; offset < max; offset += stride) {
  3684. results.push(view.getBfloat16(offset, this._littleEndian));
  3685. }
  3686. break;
  3687. case 'complex64':
  3688. for (; offset < max; offset += stride) {
  3689. results.push(view.getComplex64(offset, this._littleEndian));
  3690. }
  3691. break;
  3692. case 'complex128':
  3693. for (; offset < max; offset += stride) {
  3694. results.push(view.getComplex128(offset, this._littleEndian));
  3695. }
  3696. break;
  3697. case 'float8e4m3fn':
  3698. for (; offset < max; offset += stride) {
  3699. results.push(view.getFloat8e4m3(offset, true, false));
  3700. }
  3701. break;
  3702. case 'float8e4m3fnuz':
  3703. for (; offset < max; offset += stride) {
  3704. results.push(view.getFloat8e4m3(offset, true, true));
  3705. }
  3706. break;
  3707. case 'float8e5m2':
  3708. for (; offset < max; offset += stride) {
  3709. results.push(view.getFloat8e5m2(offset, false, false));
  3710. }
  3711. break;
  3712. case 'float8e5m2fnuz':
  3713. for (; offset < max; offset += stride) {
  3714. results.push(view.getFloat8e5m2(offset, true, true));
  3715. }
  3716. break;
  3717. default:
  3718. throw new Error(`Unsupported tensor data type '${dataType}'.`);
  3719. }
  3720. context.count += length;
  3721. if (ellipsis) {
  3722. results.push('...');
  3723. }
  3724. } else {
  3725. for (let j = 0; j < size; j++) {
  3726. if (context.count >= context.limit) {
  3727. results.push('...');
  3728. return results;
  3729. }
  3730. const nextOffset = offset + (j * stride);
  3731. results.push(this._decodeData(context, dimension + 1, nextOffset));
  3732. }
  3733. }
  3734. if (context.dimensions.length === 0) {
  3735. return results[0];
  3736. }
  3737. return results;
  3738. }
  3739. _decodeValues(context, dimension, position) {
  3740. const results = [];
  3741. const shape = (context.dimensions.length === 0) ? [1] : context.dimensions;
  3742. const size = shape[dimension];
  3743. const dataType = context.dataType;
  3744. const stride = context.stride[dimension];
  3745. if (dimension === shape.length - 1) {
  3746. const ellipsis = (context.count + size) > context.limit;
  3747. const length = ellipsis ? context.limit - context.count : size;
  3748. const data = context.data;
  3749. for (let i = 0; i < length; i++) {
  3750. if (context.count > context.limit) {
  3751. results.push('...');
  3752. return results;
  3753. }
  3754. switch (dataType) {
  3755. case 'boolean':
  3756. results.push(data[position] === 0 ? false : true);
  3757. break;
  3758. default:
  3759. results.push(data[position]);
  3760. break;
  3761. }
  3762. position += stride;
  3763. context.count++;
  3764. }
  3765. } else {
  3766. for (let i = 0; i < size; i++) {
  3767. if (context.count >= context.limit) {
  3768. results.push('...');
  3769. return results;
  3770. }
  3771. const nextPosition = position + (i * stride);
  3772. results.push(this._decodeValues(context, dimension + 1, nextPosition));
  3773. }
  3774. }
  3775. if (context.dimensions.length === 0) {
  3776. return results[0];
  3777. }
  3778. return results;
  3779. }
  3780. static _stringify(value, indentation, indent) {
  3781. if (Array.isArray(value)) {
  3782. const result = [];
  3783. result.push(`${indentation}[`);
  3784. const items = value.map((item) => view.Tensor._stringify(item, indentation + indent, indent));
  3785. if (items.length > 0) {
  3786. result.push(items.join(',\n'));
  3787. }
  3788. result.push(`${indentation}]`);
  3789. return result.join('\n');
  3790. }
  3791. if (value === null) {
  3792. return `${indentation}null`;
  3793. }
  3794. switch (typeof value) {
  3795. case 'boolean':
  3796. return indentation + value.toString();
  3797. case 'string':
  3798. return `${indentation}"${value}"`;
  3799. case 'number':
  3800. if (value === Infinity) {
  3801. return `${indentation}Infinity`;
  3802. }
  3803. if (value === -Infinity) {
  3804. return `${indentation}-Infinity`;
  3805. }
  3806. if (isNaN(value)) {
  3807. return `${indentation}NaN`;
  3808. }
  3809. return indentation + value.toString();
  3810. case 'bigint':
  3811. return indentation + value.toString();
  3812. default:
  3813. if (value && value.toString) {
  3814. return indentation + value.toString();
  3815. }
  3816. return `${indentation}(undefined)`;
  3817. }
  3818. }
  3819. };
  3820. view.Quantization = class {
  3821. constructor(quantization) {
  3822. Object.assign(this, quantization);
  3823. }
  3824. toString() {
  3825. if (this.type === 'linear' || /^quant\d\d?_.*$/.test(this.type)) {
  3826. const content = [];
  3827. const scale = this.scale || [];
  3828. const offset = this.offset || [];
  3829. const bias = this.bias || [];
  3830. const max = this.max || [];
  3831. const min = this.min || [];
  3832. const length = Math.max(scale.length, offset.length, bias.length, min.length, max.length);
  3833. const size = length.toString().length;
  3834. for (let i = 0; i < length; i++) {
  3835. let s = 'q';
  3836. let bracket = false;
  3837. if (i < offset.length && offset[i] !== undefined && offset[i] !== 0 && offset[i] !== 0n) {
  3838. const value = offset[i];
  3839. s = value > 0 ? `${s} - ${value}` : `${s} + ${-value}`;
  3840. bracket = true;
  3841. }
  3842. if (i < scale.length && scale[i] !== undefined && scale[i] !== 1 && scale[i] !== 1n) {
  3843. const value = scale[i];
  3844. s = bracket ? `(${s})` : s;
  3845. s = `${value} * ${s}`;
  3846. bracket = true;
  3847. }
  3848. if (i < bias.length && bias[i] !== undefined && bias[i] !== 0 && bias[i] !== 0n) {
  3849. const value = bias[i];
  3850. s = bracket ? `(${s})` : s;
  3851. s = value < 0 ? `${s} - ${-value}` : `${s} + ${value}`;
  3852. }
  3853. if (i < min.length && min[i] !== undefined && min[i] !== 0 && min[i] !== 0n) {
  3854. s = `${min[i]} \u2264 ${s}`;
  3855. }
  3856. if (i < max.length && max[i] !== undefined && max[i] !== 0 && max[i] !== 0n) {
  3857. s = `${s} \u2264 ${max[i]}`;
  3858. }
  3859. content.push(length > 1 ? `${i.toString().padStart(size, ' ')}: ${s}` : `${s}`);
  3860. }
  3861. return content.join('\n');
  3862. } else if (this.type === 'lookup') {
  3863. const size = this.value.length.toString().length;
  3864. return this.value.map((value, index) => `${index.toString().padStart(size, ' ')}: ${value}`).join('\n');
  3865. } else if (this.type === 'annotation') {
  3866. return Array.from(this.value).map(([name, value]) => `${name} = ${value}`).join('\n');
  3867. } else if (/^q\d_[01k]$/.test(this.type) || /^iq\d_[xsnlm]+$/.test(this.type)) {
  3868. return '';
  3869. }
  3870. throw new view.Error(`Unknown quantization type '${this.type}'.`);
  3871. }
  3872. };
  3873. view.Documentation = class {
  3874. static format(source) {
  3875. if (source) {
  3876. const generator = new markdown.Generator();
  3877. const target = {};
  3878. if (source.name) {
  3879. target.name = source.name;
  3880. }
  3881. if (source.module) {
  3882. target.module = source.module;
  3883. }
  3884. if (source.category) {
  3885. target.category = source.category;
  3886. }
  3887. if (source.summary) {
  3888. target.summary = generator.html(source.summary);
  3889. }
  3890. if (source.description) {
  3891. target.description = generator.html(source.description);
  3892. }
  3893. if (Array.isArray(source.attributes)) {
  3894. target.attributes = source.attributes.map((source) => {
  3895. const target = {};
  3896. target.name = source.name;
  3897. if (source.type !== undefined) {
  3898. target.type = source.type;
  3899. }
  3900. if (source.option !== undefined) {
  3901. target.option = source.option;
  3902. }
  3903. if (source.optional !== undefined) {
  3904. target.optional = source.optional;
  3905. }
  3906. if (source.required !== undefined) {
  3907. target.required = source.required;
  3908. }
  3909. if (source.minimum !== undefined) {
  3910. target.minimum = source.minimum;
  3911. }
  3912. if (source.src !== undefined) {
  3913. target.src = source.src;
  3914. }
  3915. if (source.src_type !== undefined) {
  3916. target.src_type = source.src_type;
  3917. }
  3918. if (source.description !== undefined) {
  3919. target.description = generator.html(source.description);
  3920. }
  3921. if (source.default !== undefined) {
  3922. target.default = source.default;
  3923. }
  3924. if (source.visible !== undefined) {
  3925. target.visible = source.visible;
  3926. }
  3927. return target;
  3928. });
  3929. }
  3930. if (Array.isArray(source.inputs)) {
  3931. target.inputs = source.inputs.map((source) => {
  3932. const target = {};
  3933. target.name = source.name;
  3934. if (source.type !== undefined) {
  3935. target.type = source.type;
  3936. }
  3937. if (source.description) {
  3938. target.description = generator.html(source.description);
  3939. }
  3940. if (source.default !== undefined) {
  3941. target.default = source.default;
  3942. }
  3943. if (source.src !== undefined) {
  3944. target.src = source.src;
  3945. }
  3946. if (source.list !== undefined) {
  3947. target.list = source.list;
  3948. }
  3949. if (source.isRef !== undefined) {
  3950. target.isRef = source.isRef;
  3951. }
  3952. if (source.typeAttr !== undefined) {
  3953. target.typeAttr = source.typeAttr;
  3954. }
  3955. if (source.numberAttr !== undefined) {
  3956. target.numberAttr = source.numberAttr;
  3957. }
  3958. if (source.typeListAttr !== undefined) {
  3959. target.typeListAttr = source.typeListAttr;
  3960. }
  3961. if (source.option !== undefined) {
  3962. target.option = source.option;
  3963. }
  3964. if (source.optional !== undefined) {
  3965. target.optional = source.optional;
  3966. }
  3967. if (source.visible !== undefined) {
  3968. target.visible = source.visible;
  3969. }
  3970. return target;
  3971. });
  3972. }
  3973. if (Array.isArray(source.outputs)) {
  3974. target.outputs = source.outputs.map((source) => {
  3975. const target = {};
  3976. target.name = source.name;
  3977. if (source.type) {
  3978. target.type = source.type;
  3979. }
  3980. if (source.description) {
  3981. target.description = generator.html(source.description);
  3982. }
  3983. if (source.list !== undefined) {
  3984. target.list = source.list;
  3985. }
  3986. if (source.typeAttr !== undefined) {
  3987. target.typeAttr = source.typeAttr;
  3988. }
  3989. if (source.typeListAttr !== undefined) {
  3990. target.typeListAttr = source.typeAttr;
  3991. }
  3992. if (source.numberAttr !== undefined) {
  3993. target.numberAttr = source.numberAttr;
  3994. }
  3995. if (source.isRef !== undefined) {
  3996. target.isRef = source.isRef;
  3997. }
  3998. if (source.option !== undefined) {
  3999. target.option = source.option;
  4000. }
  4001. return target;
  4002. });
  4003. }
  4004. if (Array.isArray(source.references)) {
  4005. target.references = source.references.map((source) => {
  4006. if (source) {
  4007. target.description = generator.html(source.description);
  4008. }
  4009. return target;
  4010. });
  4011. }
  4012. if (source.version !== undefined) {
  4013. target.version = source.version;
  4014. }
  4015. if (source.operator !== undefined) {
  4016. target.operator = source.operator;
  4017. }
  4018. if (source.identifier !== undefined) {
  4019. target.identifier = source.identifier;
  4020. }
  4021. if (source.package !== undefined) {
  4022. target.package = source.package;
  4023. }
  4024. if (source.status !== undefined) {
  4025. target.status = source.status;
  4026. }
  4027. if (source.min_input !== undefined) {
  4028. target.min_input = source.min_input;
  4029. }
  4030. if (source.max_input !== undefined) {
  4031. target.max_input = source.max_input;
  4032. }
  4033. if (source.min_output !== undefined) {
  4034. target.min_output = source.min_output;
  4035. }
  4036. if (source.max_input !== undefined) {
  4037. target.max_output = source.max_output;
  4038. }
  4039. if (source.inputs_range !== undefined) {
  4040. target.inputs_range = source.inputs_range;
  4041. }
  4042. if (source.outputs_range !== undefined) {
  4043. target.outputs_range = source.outputs_range;
  4044. }
  4045. if (source.examples !== undefined) {
  4046. target.examples = source.examples;
  4047. }
  4048. if (source.constants !== undefined) {
  4049. target.constants = source.constants;
  4050. }
  4051. if (source.type_constraints !== undefined) {
  4052. target.type_constraints = source.type_constraints;
  4053. }
  4054. return target;
  4055. }
  4056. return '';
  4057. }
  4058. };
  4059. view.Formatter = class {
  4060. constructor(value, type, quote) {
  4061. this._value = value;
  4062. this._type = type;
  4063. this._quote = quote;
  4064. this._values = new Set();
  4065. }
  4066. toString() {
  4067. return this._format(this._value, this._type, this._quote);
  4068. }
  4069. _format(value, type, quote) {
  4070. if (value && value.__class__ && value.__class__.__module__ === 'builtins' && value.__class__.__name__ === 'type') {
  4071. return `${value.__module__}.${value.__name__}`;
  4072. }
  4073. if (value && value.__class__ && value.__class__.__module__ === 'builtins' && value.__class__.__name__ === 'function') {
  4074. return `${value.__module__}.${value.__name__}`;
  4075. }
  4076. if (typeof value === 'function') {
  4077. return value();
  4078. }
  4079. if (value && typeof value === 'bigint') {
  4080. return value.toString();
  4081. }
  4082. if (Number.isNaN(value)) {
  4083. return 'NaN';
  4084. }
  4085. switch (type) {
  4086. case 'shape':
  4087. return value ? value.toString() : '(null)';
  4088. case 'shape[]':
  4089. if (value && !Array.isArray(value)) {
  4090. throw new Error(`Invalid shape '${JSON.stringify(value)}'.`);
  4091. }
  4092. return value ? value.map((item) => item.toString()).join(', ') : '(null)';
  4093. case 'graph':
  4094. return value ? value.name : '(null)';
  4095. case 'graph[]':
  4096. return value ? value.map((graph) => graph.name).join(', ') : '(null)';
  4097. case 'tensor':
  4098. if (value && value.type && value.type.shape && value.type.shape.dimensions && value.type.shape.dimensions.length === 0) {
  4099. return value.toString();
  4100. }
  4101. return '[...]';
  4102. case 'object':
  4103. case 'function':
  4104. return value.type.name;
  4105. case 'object[]':
  4106. case 'function[]':
  4107. return value ? value.map((item) => item.type.name).join(', ') : '(null)';
  4108. case 'type':
  4109. return value ? value.toString() : '(null)';
  4110. case 'type[]':
  4111. return value ? value.map((item) => item.toString()).join(', ') : '(null)';
  4112. default:
  4113. break;
  4114. }
  4115. if (typeof value === 'string' && (!type || type !== 'string')) {
  4116. return quote ? `"${value}"` : value;
  4117. }
  4118. if (Array.isArray(value)) {
  4119. if (value.length === 0) {
  4120. return quote ? '[]' : '';
  4121. }
  4122. let ellipsis = false;
  4123. if (value.length > 1000) {
  4124. value = value.slice(0, 1000);
  4125. ellipsis = true;
  4126. }
  4127. const itemType = (type && type.endsWith('[]')) ? type.substring(0, type.length - 2) : null;
  4128. const array = value.map((value) => {
  4129. if (value && typeof value === 'bigint') {
  4130. return value.toString();
  4131. }
  4132. if (Number.isNaN(value)) {
  4133. return 'NaN';
  4134. }
  4135. const quote = !itemType || itemType === 'string';
  4136. return this._format(value, itemType, quote);
  4137. });
  4138. if (ellipsis) {
  4139. array.push('\u2026');
  4140. }
  4141. return quote ? ['[', array.join(', '), ']'].join(' ') : array.join(', ');
  4142. }
  4143. if (value === null) {
  4144. return quote ? 'null' : '';
  4145. }
  4146. if (value === undefined) {
  4147. return 'undefined';
  4148. }
  4149. if (value !== Object(value)) {
  4150. return value.toString();
  4151. }
  4152. if (this._values.has(value)) {
  4153. return '\u2026';
  4154. }
  4155. this._values.add(value);
  4156. let list = null;
  4157. const entries = Object.entries(value).filter(([name]) => !name.startsWith('__') && !name.endsWith('__'));
  4158. if (entries.length === 1) {
  4159. list = [this._format(entries[0][1], null, true)];
  4160. } else {
  4161. list = entries.map(([name, value]) => `${name}: ${this._format(value, null, true)}`);
  4162. }
  4163. let objectType = value.__type__;
  4164. if (!objectType && value.constructor.name && value.constructor.name !== 'Object') {
  4165. objectType = value.constructor.name;
  4166. }
  4167. if (objectType) {
  4168. return objectType + (list.length === 0 ? '()' : ['(', list.join(', '), ')'].join(''));
  4169. }
  4170. switch (list.length) {
  4171. case 0:
  4172. return quote ? '()' : '';
  4173. case 1:
  4174. return list[0];
  4175. default:
  4176. return quote ? ['(', list.join(', '), ')'].join(' ') : list.join(', ');
  4177. }
  4178. }
  4179. };
  4180. markdown.Generator = class {
  4181. constructor() {
  4182. this._newlineRegExp = /^\n+/;
  4183. this._codeRegExp = /^( {4}[^\n]+\n*)+/;
  4184. this._fencesRegExp = /^ {0,3}(`{3,}(?=[^`\n]*\n)|~{3,})([^\n]*)\n(?:|([\s\S]*?)\n)(?: {0,3}\1[~`]* *(?:\n+|$)|$)/;
  4185. this._hrRegExp = /^ {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)/;
  4186. this._headingRegExp = /^ {0,3}(#{1,6}) +([^\n]*?)(?: +#+)? *(?:\n+|$)/;
  4187. this._blockquoteRegExp = /^( {0,3}> ?(([^\n]+(?:\n(?! {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)| {0,3}#{1,6} | {0,3}>| {0,3}(?:`{3,}(?=[^`\n]*\n)|~{3,})[^\n]*\n| {0,3}(?:[*+-]|1[.)]) |<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?: +|\n|\/?>)|<(?:script|pre|style|!--))[^\n]+)*)|[^\n]*)(?:\n|$))+/;
  4188. this._listRegExp = /^( {0,3})((?:[*+-]|\d{1,9}[.)])) [\s\S]+?(?:\n+(?=\1?(?:(?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$))|\n+(?= {0,3}\[((?!\s*\])(?:\\[[\]]|[^[\]])+)\]: *\n? *<?([^\s>]+)>?(?:(?: +\n? *| *\n *)((?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))))? *(?:\n+|$))|\n{2,}(?! )(?!\1(?:[*+-]|\d{1,9}[.)]) )\n*|\s*$)/;
  4189. this._htmlRegExp = /^ {0,3}(?:<(script|pre|style)[\s>][\s\S]*?(?:<\/\1>[^\n]*\n+|$)|<!--(?!-?>)[\s\S]*?(?:-->|$)[^\n]*(\n+|$)|<\?[\s\S]*?(?:\?>\n*|$)|<![A-Z][\s\S]*?(?:>\n*|$)|<!\[CDATA\[[\s\S]*?(?:\]\]>\n*|$)|<\/?(address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?: +|\n|\/?>)[\s\S]*?(?:\n{2,}|$)|<(?!script|pre|style)([a-z][\w-]*)(?: +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?)*? *\/?>(?=[ \t]*(?:\n|$))[\s\S]*?(?:\n{2,}|$)|<\/(?!script|pre|style)[a-z][\w-]*\s*>(?=[ \t]*(?:\n|$))[\s\S]*?(?:\n{2,}|$))/i;
  4190. this._defRegExp = /^ {0,3}\[((?!\s*\])(?:\\[[\]]|[^[\]])+)\]: *\n? *<?([^\s>]+)>?(?:(?: +\n? *| *\n *)((?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))))? *(?:\n+|$)/;
  4191. this._nptableRegExp = /^ *([^|\n ].*\|.*)\n {0,3}([-:]+ *\|[-| :]*)(?:\n((?:(?!\n| {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)| {0,3}#{1,6} | {0,3}>| {4}[^\n]| {0,3}(?:`{3,}(?=[^`\n]*\n)|~{3,})[^\n]*\n| {0,3}(?:[*+-]|1[.)]) |<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?: +|\n|\/?>)|<(?:script|pre|style|!--)).*(?:\n|$))*)\n*|$)/;
  4192. this._tableRegExp = /^ *\|(.+)\n {0,3}\|?( *[-:]+[-| :]*)(?:\n *((?:(?!\n| {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)| {0,3}#{1,6} | {0,3}>| {4}[^\n]| {0,3}(?:`{3,}(?=[^`\n]*\n)|~{3,})[^\n]*\n| {0,3}(?:[*+-]|1[.)]) |<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?: +|\n|\/?>)|<(?:script|pre|style|!--)).*(?:\n|$))*)\n*|$)/;
  4193. this._lheadingRegExp = /^([^\n]+)\n {0,3}(=+|-+) *(?:\n+|$)/;
  4194. this._textRegExp = /^[^\n]+/;
  4195. this._bulletRegExp = /(?:[*+-]|\d{1,9}[.)])/;
  4196. this._itemRegExp = /^( *)((?:[*+-]|\d{1,9}[.)])) ?[^\n]*(?:\n(?!\1(?:[*+-]|\d{1,9}[.)]) ?)[^\n]*)*/gm;
  4197. this._paragraphRegExp = /^([^\n]+(?:\n(?! {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\* *){3,})(?:\n+|$)| {0,3}#{1,6} | {0,3}>| {0,3}(?:`{3,}(?=[^`\n]*\n)|~{3,})[^\n]*\n| {0,3}(?:[*+-]|1[.)]) |<\/?(?:address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?: +|\n|\/?>)|<(?:script|pre|style|!--))[^\n]+)*)/;
  4198. this._backpedalRegExp = /(?:[^?!.,:;*_~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_~)]+(?!$))+/;
  4199. this._escapeRegExp = /^\\([!"#$%&'()*+,\-./:;<=>?@[\]\\^_`{|}~~|])/;
  4200. this._escapesRegExp = /\\([!"#$%&'()*+,\-./:;<=>?@[\]\\^_`{|}~])/g;
  4201. /* eslint-disable no-control-regex */
  4202. this._autolinkRegExp = /^<([a-zA-Z][a-zA-Z0-9+.-]{1,31}:[^\s\x00-\x1f<>]*|[a-zA-Z0-9.!#$%&'*+/=?_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_]))>/;
  4203. this._linkRegExp = /^!?\[((?:\[(?:\\.|[^[\]\\])*\]|\\.|`[^`]*`|[^[\]\\`])*?)\]\(\s*(<(?:\\[<>]?|[^\s<>\\])*>|[^\s\x00-\x1f]*)(?:\s+("(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)))?\s*\)/;
  4204. /* eslint-enable no-control-regex */
  4205. this._urlRegExp = /^((?:ftp|https?):\/\/|www\.)(?:[a-zA-Z0-9-]+\.?)+[^\s<]*|^[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/i;
  4206. this._tagRegExp = /^<!--(?!-?>)[\s\S]*?-->|^<\/[a-zA-Z][\w:-]*\s*>|^<[a-zA-Z][\w-]*(?:\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?)*?\s*\/?>|^<\?[\s\S]*?\?>|^<![a-zA-Z]+\s[\s\S]*?>|^<!\[CDATA\[[\s\S]*?\]\]>/;
  4207. this._reflinkRegExp = /^!?\[((?:\[(?:\\.|[^[\]\\])*\]|\\.|`[^`]*`|[^[\]\\`])*?)\]\[(?!\s*\])((?:\\[[\]]?|[^[\]\\])+)\]/;
  4208. this._nolinkRegExp = /^!?\[(?!\s*\])((?:\[[^[\]]*\]|\\[[\]]|[^[\]])*)\](?:\[\])?/;
  4209. this._reflinkSearchRegExp = /!?\[((?:\[(?:\\.|[^[\]\\])*\]|\\.|`[^`]*`|[^[\]\\`])*?)\]\[(?!\s*\])((?:\\[[\]]?|[^[\]\\])+)\]|!?\[(?!\s*\])((?:\[[^[\]]*\]|\\[[\]]|[^[\]])*)\](?:\[\])?(?!\()/g;
  4210. this._strongStartRegExp = /^(?:(\*\*(?=[*!"#$%&'()+\-.,/:;<=>?@[\]`{|}~]))|\*\*)(?![\s])|__/;
  4211. this._strongMiddleRegExp = /^\*\*(?:(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^*]|\\\*)|__[^_]*?__|\*\*\[^\*\]*?\*\*)|\*(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^*]|\\\*)|__[^_]*?__|\*\*\[^\*\]*?\*\*)*?\*)+?\*\*$|^__(?![\s])((?:(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^_]|\\_)|__[^_]*?__|\*\*\[^\*\]*?\*\*)|_(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^_]|\\_)|__[^_]*?__|\*\*\[^\*\]*?\*\*)*?_)+?)__$/;
  4212. this._strongEndAstRegExp = /[^!"#$%&'()+\-.,/:;<=>?@[\]`{|}~\s]\*\*(?!\*)|[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~]\*\*(?!\*)(?:(?=[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~_\s]|$))/g;
  4213. this._strongEndUndRegExp = /[^\s]__(?!_)(?:(?=[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~*\s])|$)/g;
  4214. this._emStartRegExp = /^(?:(\*(?=[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~]))|\*)(?![*\s])|_/;
  4215. this._emMiddleRegExp = /^\*(?:(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^*]|\\\*)|__[^_]*?__|\*\*\[^\*\]*?\*\*)|\*(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^*]|\\\*)|__[^_]*?__|\*\*\[^\*\]*?\*\*)*?\*)+?\*$|^_(?![_\s])(?:(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^_]|\\_)|__[^_]*?__|\*\*\[^\*\]*?\*\*)|_(?:(?!__[^_]*?__|\*\*\[^\*\]*?\*\*)(?:[^_]|\\_)|__[^_]*?__|\*\*\[^\*\]*?\*\*)*?_)+?_$/;
  4216. this._emEndAstRegExp = /[^!"#$%&'()+\-.,/:;<=>?@[\]`{|}~\s]\*(?!\*)|[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~]\*(?!\*)(?:(?=[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~_\s]|$))/g;
  4217. this._emEndUndRegExp = /[^\s]_(?!_)(?:(?=[!"#$%&'()+\-.,/:;<=>?@[\]`{|}~*\s])|$)/g;
  4218. this._codespanRegExp = /^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/;
  4219. this._brRegExp = /^( {2,}|\\)\n(?!\s*$)/;
  4220. this._delRegExp = /^~+(?=\S)([\s\S]*?\S)~+/;
  4221. this._textspanRegExp = /^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<![`*~]|\b_|https?:\/\/|ftp:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+/=?_`{|}~-](?=[a-zA-Z0-9.!#$%&'*+/=?_`{|}~-]+@))|(?=[a-zA-Z0-9.!#$%&'*+/=?_`{|}~-]+@))/;
  4222. this._punctuationRegExp = /^([\s*!"#$%&'()+\-.,/:;<=>?@[\]`{|}~])/;
  4223. this._blockSkipRegExp = /\[[^\]]*?\]\([^)]*?\)|`[^`]*?`|<[^>]*?>/g;
  4224. this._escapeTestRegExp = /[&<>"']/;
  4225. this._escapeReplaceRegExp = /[&<>"']/g;
  4226. this._escapeTestNoEncodeRegExp = /[<>"']|&(?!#?\w+;)/;
  4227. this._escapeReplaceNoEncodeRegExp = /[<>"']|&(?!#?\w+;)/g;
  4228. this._escapeReplacementsMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' };
  4229. }
  4230. html(source) {
  4231. const tokens = [];
  4232. const links = new Map();
  4233. source = source.replace(/\r\n|\r/g, '\n').replace(/\t/g, ' ');
  4234. this._tokenize(source, tokens, links, true);
  4235. this._tokenizeBlock(tokens, links);
  4236. const result = this._render(tokens, true);
  4237. return result;
  4238. }
  4239. _tokenize(source, tokens, links, top) {
  4240. source = source.replace(/^ +$/gm, '');
  4241. while (source) {
  4242. let match = this._newlineRegExp.exec(source);
  4243. if (match) {
  4244. source = source.substring(match[0].length);
  4245. if (match[0].length > 1) {
  4246. tokens.push({ type: 'space' });
  4247. }
  4248. continue;
  4249. }
  4250. match = this._codeRegExp.exec(source);
  4251. if (match) {
  4252. source = source.substring(match[0].length);
  4253. const lastToken = tokens[tokens.length - 1];
  4254. if (lastToken && lastToken.type === 'paragraph') {
  4255. lastToken.text += `\n${match[0].trimRight()}`;
  4256. } else {
  4257. const text = match[0].replace(/^ {4}/gm, '').replace(/\n*$/, '');
  4258. tokens.push({ type: 'code', text });
  4259. }
  4260. continue;
  4261. }
  4262. match = this._fencesRegExp.exec(source);
  4263. if (match) {
  4264. source = source.substring(match[0].length);
  4265. const language = match[2] ? match[2].trim() : match[2];
  4266. let content = match[3] || '';
  4267. const matchIndent = match[0].match(/^(\s+)(?:```)/);
  4268. if (matchIndent !== null) {
  4269. const [, indent] = matchIndent;
  4270. content = content.split('\n').map((node) => {
  4271. const match = node.match(/^\s+/);
  4272. return (match !== null && match[0].length >= indent.length) ? node.slice(indent.length) : node;
  4273. }).join('\n');
  4274. }
  4275. tokens.push({ type: 'code', language, text: content });
  4276. continue;
  4277. }
  4278. match = this._headingRegExp.exec(source);
  4279. if (match) {
  4280. source = source.substring(match[0].length);
  4281. tokens.push({ type: 'heading', depth: match[1].length, text: match[2] });
  4282. continue;
  4283. }
  4284. match = this._nptableRegExp.exec(source);
  4285. if (match) {
  4286. const header = this._splitCells(match[1].replace(/^ *| *\| *$/g, ''));
  4287. const align = match[2].replace(/^ *|\| *$/g, '').split(/ *\| */);
  4288. if (header.length === align.length) {
  4289. const cells = match[3] ? match[3].replace(/\n$/, '').split('\n') : [];
  4290. const token = { type: 'table', header, align, cells, raw: match[0] };
  4291. for (let i = 0; i < token.align.length; i++) {
  4292. if (/^ *-+: *$/.test(token.align[i])) {
  4293. token.align[i] = 'right';
  4294. } else if (/^ *:-+: *$/.test(token.align[i])) {
  4295. token.align[i] = 'center';
  4296. } else if (/^ *:-+ *$/.test(token.align[i])) {
  4297. token.align[i] = 'left';
  4298. } else {
  4299. token.align[i] = null;
  4300. }
  4301. }
  4302. token.cells = token.cells.map((cell) => this._splitCells(cell, token.header.length));
  4303. source = source.substring(token.raw.length);
  4304. tokens.push(token);
  4305. continue;
  4306. }
  4307. }
  4308. match = this._hrRegExp.exec(source);
  4309. if (match) {
  4310. source = source.substring(match[0].length);
  4311. tokens.push({ type: 'hr' });
  4312. continue;
  4313. }
  4314. match = this._blockquoteRegExp.exec(source);
  4315. if (match) {
  4316. source = source.substring(match[0].length);
  4317. const text = match[0].replace(/^ *> ?/gm, '');
  4318. tokens.push({ type: 'blockquote', text, tokens: this._tokenize(text, [], links, top) });
  4319. continue;
  4320. }
  4321. match = this._listRegExp.exec(source);
  4322. if (match) {
  4323. const [value, , bull] = match;
  4324. const ordered = bull.length > 1;
  4325. const parent = bull[bull.length - 1] === ')';
  4326. let raw = value;
  4327. const list = { type: 'list', raw, ordered, start: ordered ? Number(bull.slice(0, -1)) : '', loose: false, items: [] };
  4328. const itemMatch = value.match(this._itemRegExp);
  4329. let next = false;
  4330. const length = itemMatch.length;
  4331. for (let i = 0; i < length; i++) {
  4332. let item = itemMatch[i];
  4333. raw = item;
  4334. let space = item.length;
  4335. item = item.replace(/^ *([*+-]|\d+[.)]) ?/, '');
  4336. if (item.indexOf('\n ') !== -1) {
  4337. space -= item.length;
  4338. item = item.replace(new RegExp(`^ {1,${space}}`, 'gm'), '');
  4339. }
  4340. if (i !== length - 1) {
  4341. const [bullet] = this._bulletRegExp.exec(itemMatch[i + 1]);
  4342. if (ordered ? bullet.length === 1 || (!parent && bullet[bullet.length - 1] === ')') : (bullet.length > 1)) {
  4343. const addBack = itemMatch.slice(i + 1).join('\n');
  4344. list.raw = list.raw.substring(0, list.raw.length - addBack.length);
  4345. i = length - 1;
  4346. }
  4347. }
  4348. let loose = next || /\n\n(?!\s*$)/.test(item);
  4349. if (i !== length - 1) {
  4350. next = item.charAt(item.length - 1) === '\n';
  4351. if (!loose) {
  4352. loose = next;
  4353. }
  4354. }
  4355. if (loose) {
  4356. list.loose = true;
  4357. }
  4358. const task = /^\[[ xX]\] /.test(item);
  4359. let checked = false;
  4360. if (task) {
  4361. checked = item[1] !== ' ';
  4362. item = item.replace(/^\[[ xX]\] +/, '');
  4363. }
  4364. list.items.push({ type: 'list_item', raw, task, checked, loose, text: item });
  4365. }
  4366. source = source.substring(list.raw.length);
  4367. for (const item of list.items) {
  4368. item.tokens = this._tokenize(item.text, [], links, false);
  4369. }
  4370. tokens.push(list);
  4371. continue;
  4372. }
  4373. match = this._htmlRegExp.exec(source);
  4374. if (match) {
  4375. source = source.substring(match[0].length);
  4376. tokens.push({ type: 'html', pre: (match[1] === 'pre' || match[1] === 'script' || match[1] === 'style'), text: match[0] });
  4377. continue;
  4378. }
  4379. if (top) {
  4380. match = this._defRegExp.exec(source);
  4381. if (match) {
  4382. source = source.substring(match[0].length);
  4383. match[3] = match[3] ? match[3].substring(1, match[3].length - 1) : match[3];
  4384. const tag = match[1].toLowerCase().replace(/\s+/g, ' ');
  4385. if (!links.has(tag)) {
  4386. links.set(tag, { href: match[2], title: match[3] });
  4387. }
  4388. continue;
  4389. }
  4390. }
  4391. match = this._tableRegExp.exec(source);
  4392. if (match) {
  4393. const header = this._splitCells(match[1].replace(/^ *| *\| *$/g, ''));
  4394. const align = match[2].replace(/^ *|\| *$/g, '').split(/ *\| */);
  4395. if (header.length === align.length) {
  4396. const cells = match[3] ? match[3].replace(/\n$/, '').split('\n') : [];
  4397. const token = { type: 'table', header, align, cells, raw: match[0] };
  4398. for (let i = 0; i < token.align.length; i++) {
  4399. if (/^ *-+: *$/.test(token.align[i])) {
  4400. token.align[i] = 'right';
  4401. } else if (/^ *:-+: *$/.test(token.align[i])) {
  4402. token.align[i] = 'center';
  4403. } else if (/^ *:-+ *$/.test(token.align[i])) {
  4404. token.align[i] = 'left';
  4405. } else {
  4406. token.align[i] = null;
  4407. }
  4408. }
  4409. token.cells = token.cells.map((cell) => this._splitCells(cell.replace(/^ *\| *| *\| *$/g, ''), token.header.length));
  4410. source = source.substring(token.raw.length);
  4411. tokens.push(token);
  4412. continue;
  4413. }
  4414. }
  4415. match = this._lheadingRegExp.exec(source);
  4416. if (match) {
  4417. source = source.substring(match[0].length);
  4418. tokens.push({ type: 'heading', depth: match[2].charAt(0) === '=' ? 1 : 2, text: match[1] });
  4419. continue;
  4420. }
  4421. if (top) {
  4422. match = this._paragraphRegExp.exec(source);
  4423. if (match) {
  4424. source = source.substring(match[0].length);
  4425. tokens.push({ type: 'paragraph', text: match[1].charAt(match[1].length - 1) === '\n' ? match[1].slice(0, -1) : match[1] });
  4426. continue;
  4427. }
  4428. }
  4429. match = this._textRegExp.exec(source);
  4430. if (match) {
  4431. source = source.substring(match[0].length);
  4432. const lastToken = tokens[tokens.length - 1];
  4433. if (lastToken && lastToken.type === 'text') {
  4434. lastToken.text += `\n${match[0]}`;
  4435. } else {
  4436. tokens.push({ type: 'text', text: match[0] });
  4437. }
  4438. continue;
  4439. }
  4440. throw new Error(`Unexpected '${source.charCodeAt(0)}'.`);
  4441. }
  4442. return tokens;
  4443. }
  4444. _tokenizeInline(source, links, inLink, inRawBlock, prevChar) {
  4445. const tokens = [];
  4446. let maskedSource = source;
  4447. if (links.size > 0) {
  4448. while (maskedSource) {
  4449. const match = this._reflinkSearchRegExp.exec(maskedSource);
  4450. if (match) {
  4451. if (links.has(match[0].slice(match[0].lastIndexOf('[') + 1, -1))) {
  4452. maskedSource = `${maskedSource.slice(0, match.index)}[${'a'.repeat(match[0].length - 2)}]${maskedSource.slice(this._reflinkSearchRegExp.lastIndex)}`;
  4453. }
  4454. continue;
  4455. }
  4456. break;
  4457. }
  4458. }
  4459. while (maskedSource) {
  4460. const match = this._blockSkipRegExp.exec(maskedSource);
  4461. if (match) {
  4462. maskedSource = `${maskedSource.slice(0, match.index)}[${'a'.repeat(match[0].length - 2)}]${maskedSource.slice(this._blockSkipRegExp.lastIndex)}`;
  4463. continue;
  4464. }
  4465. break;
  4466. }
  4467. while (source) {
  4468. let match = this._escapeRegExp.exec(source);
  4469. if (match) {
  4470. source = source.substring(match[0].length);
  4471. tokens.push({ type: 'escape', text: this._escape(match[1]) });
  4472. continue;
  4473. }
  4474. match = this._tagRegExp.exec(source);
  4475. if (match) {
  4476. source = source.substring(match[0].length);
  4477. if (!inLink && /^<a /i.test(match[0])) {
  4478. inLink = true;
  4479. } else if (inLink && /^<\/a>/i.test(match[0])) {
  4480. inLink = false;
  4481. }
  4482. if (!inRawBlock && /^<(pre|code|kbd|script)(\s|>)/i.test(match[0])) {
  4483. inRawBlock = true;
  4484. } else if (inRawBlock && /^<\/(pre|code|kbd|script)(\s|>)/i.test(match[0])) {
  4485. inRawBlock = false;
  4486. }
  4487. tokens.push({ type: 'html', raw: match[0], text: match[0] });
  4488. continue;
  4489. }
  4490. match = this._linkRegExp.exec(source);
  4491. if (match) {
  4492. let index = -1;
  4493. const [, , ref] = match;
  4494. if (ref.indexOf(')') !== -1) {
  4495. let level = 0;
  4496. for (let i = 0; i < ref.length; i++) {
  4497. switch (ref[i]) {
  4498. case '\\':
  4499. i++;
  4500. break;
  4501. case '(':
  4502. level++;
  4503. break;
  4504. case ')':
  4505. level--;
  4506. if (level < 0) {
  4507. index = i;
  4508. i = ref.length;
  4509. }
  4510. break;
  4511. default:
  4512. break;
  4513. }
  4514. }
  4515. }
  4516. if (index > -1) {
  4517. const length = (match[0].indexOf('!') === 0 ? 5 : 4) + match[1].length + index;
  4518. match[2] = match[2].substring(0, index);
  4519. match[0] = match[0].substring(0, length).trim();
  4520. match[3] = '';
  4521. }
  4522. const title = (match[3] ? match[3].slice(1, -1) : '').replace(this._escapesRegExp, '$1');
  4523. const href = match[2].trim().replace(/^<([\s\S]*)>$/, '$1').replace(this._escapesRegExp, '$1');
  4524. const token = this._outputLink(match, href, title);
  4525. source = source.substring(match[0].length);
  4526. if (token.type === 'link') {
  4527. token.tokens = this._tokenizeInline(token.text, links, true, inRawBlock, '');
  4528. }
  4529. tokens.push(token);
  4530. continue;
  4531. }
  4532. match = this._reflinkRegExp.exec(source) || this._nolinkRegExp.exec(source);
  4533. if (match) {
  4534. let link = (match[2] || match[1]).replace(/\s+/g, ' ');
  4535. link = links.get(link.toLowerCase());
  4536. if (!link || !link.href) {
  4537. const text = match[0].charAt(0);
  4538. source = source.substring(text.length);
  4539. tokens.push({ type: 'text', text });
  4540. } else {
  4541. source = source.substring(match[0].length);
  4542. const token = this._outputLink(match, link);
  4543. if (token.type === 'link') {
  4544. token.tokens = this._tokenizeInline(token.text, links, true, inRawBlock, '');
  4545. }
  4546. tokens.push(token);
  4547. }
  4548. continue;
  4549. }
  4550. match = this._strongStartRegExp.exec(source);
  4551. if (match && (!match[1] || (match[1] && (prevChar === '' || this._punctuationRegExp.exec(prevChar))))) {
  4552. const masked = maskedSource.slice(-1 * source.length);
  4553. const endReg = match[0] === '**' ? this._strongEndAstRegExp : this._strongEndUndRegExp;
  4554. endReg.lastIndex = 0;
  4555. let cap = '';
  4556. while ((match = endReg.exec(masked)) !== null) {
  4557. cap = this._strongMiddleRegExp.exec(masked.slice(0, match.index + 3));
  4558. if (cap) {
  4559. break;
  4560. }
  4561. }
  4562. if (cap) {
  4563. const text = source.substring(2, cap[0].length - 2);
  4564. source = source.substring(cap[0].length);
  4565. tokens.push({ type: 'strong', text, tokens: this._tokenizeInline(text, links, inLink, inRawBlock, '') });
  4566. continue;
  4567. }
  4568. }
  4569. match = this._emStartRegExp.exec(source);
  4570. if (match && (!match[1] || (match[1] && (prevChar === '' || this._punctuationRegExp.exec(prevChar))))) {
  4571. const masked = maskedSource.slice(-1 * source.length);
  4572. const endReg = match[0] === '*' ? this._emEndAstRegExp : this._emEndUndRegExp;
  4573. endReg.lastIndex = 0;
  4574. let cap = '';
  4575. while ((match = endReg.exec(masked)) !== null) {
  4576. cap = this._emMiddleRegExp.exec(masked.slice(0, match.index + 2));
  4577. if (cap) {
  4578. break;
  4579. }
  4580. }
  4581. if (cap) {
  4582. const text = source.slice(1, cap[0].length - 1);
  4583. source = source.substring(cap[0].length);
  4584. tokens.push({ type: 'em', text, tokens: this._tokenizeInline(text, links, inLink, inRawBlock, '') });
  4585. continue;
  4586. }
  4587. }
  4588. match = this._codespanRegExp.exec(source);
  4589. if (match) {
  4590. source = source.substring(match[0].length);
  4591. let content = match[2].replace(/\n/g, ' ');
  4592. if (/[^ ]/.test(content) && content.startsWith(' ') && content.endsWith(' ')) {
  4593. content = content.substring(1, content.length - 1);
  4594. }
  4595. tokens.push({ type: 'codespan', text: this._encode(content) });
  4596. continue;
  4597. }
  4598. match = this._brRegExp.exec(source);
  4599. if (match) {
  4600. source = source.substring(match[0].length);
  4601. tokens.push({ type: 'br' });
  4602. continue;
  4603. }
  4604. match = this._delRegExp.exec(source);
  4605. if (match) {
  4606. const [value, text] = match;
  4607. source = source.substring(value.length);
  4608. tokens.push({ type: 'del', text, tokens: this._tokenizeInline(text, links, inLink, inRawBlock, '') });
  4609. continue;
  4610. }
  4611. match = this._autolinkRegExp.exec(source);
  4612. if (match) {
  4613. source = source.substring(match[0].length);
  4614. const text = this._escape(match[1]);
  4615. const href = match[2] === '@' ? `mailto:${text}` : text;
  4616. tokens.push({ type: 'link', text, href, tokens: [{ type: 'text', raw: text, text }] });
  4617. continue;
  4618. }
  4619. if (!inLink) {
  4620. match = this._urlRegExp.exec(source);
  4621. if (match) {
  4622. const email = match[2] === '@';
  4623. let [value] = match;
  4624. if (!email) {
  4625. let prevCapZero = '';
  4626. do {
  4627. prevCapZero = value;
  4628. [value] = this._backpedalRegExp.exec(value);
  4629. } while (prevCapZero !== value);
  4630. }
  4631. const text = this._escape(value);
  4632. let href = text;
  4633. if (email) {
  4634. href = `mailto:${text}`;
  4635. } else if (text.startsWith('www.')) {
  4636. href = `http://${text}`;
  4637. }
  4638. source = source.substring(value.length);
  4639. tokens.push({ type: 'link', text, href, tokens: [{ type: 'text', text }] });
  4640. continue;
  4641. }
  4642. }
  4643. match = this._textspanRegExp.exec(source);
  4644. if (match) {
  4645. source = source.substring(match[0].length);
  4646. prevChar = match[0].slice(-1);
  4647. tokens.push({ type: 'text' , text: inRawBlock ? match[0] : this._escape(match[0]) });
  4648. continue;
  4649. }
  4650. throw new Error(`Unexpected '${source.charCodeAt(0)}'.`);
  4651. }
  4652. return tokens;
  4653. }
  4654. _tokenizeBlock(tokens, links) {
  4655. for (const token of tokens) {
  4656. switch (token.type) {
  4657. case 'paragraph':
  4658. case 'text':
  4659. case 'heading': {
  4660. token.tokens = this._tokenizeInline(token.text, links, false, false, '');
  4661. break;
  4662. }
  4663. case 'table': {
  4664. token.tokens = {};
  4665. token.tokens.header = token.header.map((header) => this._tokenizeInline(header, links, false, false, ''));
  4666. token.tokens.cells = token.cells.map((cell) => cell.map((row) => this._tokenizeInline(row, links, false, false, '')));
  4667. break;
  4668. }
  4669. case 'blockquote': {
  4670. this._tokenizeBlock(token.tokens, links);
  4671. break;
  4672. }
  4673. case 'list': {
  4674. for (const item of token.items) {
  4675. this._tokenizeBlock(item.tokens, links);
  4676. }
  4677. break;
  4678. }
  4679. default: {
  4680. break;
  4681. }
  4682. }
  4683. }
  4684. }
  4685. _render(tokens, top) {
  4686. let html = '';
  4687. while (tokens.length > 0) {
  4688. const token = tokens.shift();
  4689. switch (token.type) {
  4690. case 'space': {
  4691. continue;
  4692. }
  4693. case 'hr': {
  4694. html += '<hr>\n';
  4695. continue;
  4696. }
  4697. case 'heading': {
  4698. const level = token.depth;
  4699. html += `<h${level}">${this._renderInline(token.tokens)}</h${level}>\n`;
  4700. continue;
  4701. }
  4702. case 'code': {
  4703. const code = token.text;
  4704. const [language] = (token.language || '').match(/\S*/);
  4705. html += `<pre><code${language ? ` class="language-${this._encode(language)}"` : ''}>${token.escaped ? code : this._encode(code)}</code></pre>\n`;
  4706. continue;
  4707. }
  4708. case 'table': {
  4709. let header = '';
  4710. let cell = '';
  4711. for (let j = 0; j < token.header.length; j++) {
  4712. const content = this._renderInline(token.tokens.header[j]);
  4713. const align = token.align[j];
  4714. cell += `<th${align ? ` align="${align}"` : ''}>${content}</th>\n`;
  4715. }
  4716. header += `<tr>\n${cell}</tr>\n`;
  4717. let body = '';
  4718. for (let j = 0; j < token.cells.length; j++) {
  4719. const row = token.tokens.cells[j];
  4720. cell = '';
  4721. for (let k = 0; k < row.length; k++) {
  4722. const content = this._renderInline(row[k]);
  4723. const align = token.align[k];
  4724. cell += `<td${align ? ` align="${align}"` : ''}>${content}</td>\n`;
  4725. }
  4726. body += `<tr>\n${cell}</tr>\n`;
  4727. }
  4728. html += `<table>\n<thead>\n${header}</thead>\n${body ? `<tbody>${body}</tbody>` : body}</table>\n`;
  4729. continue;
  4730. }
  4731. case 'blockquote': {
  4732. html += `<blockquote>\n${this._render(token.tokens, true)}</blockquote>\n`;
  4733. continue;
  4734. }
  4735. case 'list': {
  4736. const ordered = token.ordered;
  4737. const start = token.start;
  4738. const loose = token.loose;
  4739. let body = '';
  4740. for (const item of token.items) {
  4741. let itemBody = '';
  4742. if (item.task) {
  4743. const checkbox = `<input ${item.checked ? 'checked="" ' : ''}disabled="" type="checkbox"> `;
  4744. if (loose) {
  4745. if (item.tokens.length > 0 && item.tokens[0].type === 'text') {
  4746. item.tokens[0].text = `${checkbox} ${item.tokens[0].text}`;
  4747. if (item.tokens[0].tokens && item.tokens[0].tokens.length > 0 && item.tokens[0].tokens[0].type === 'text') {
  4748. item.tokens[0].tokens[0].text = `${checkbox} ${item.tokens[0].tokens[0].text}`;
  4749. }
  4750. } else {
  4751. item.tokens.unshift({ type: 'text', text: checkbox });
  4752. }
  4753. } else {
  4754. itemBody += checkbox;
  4755. }
  4756. }
  4757. itemBody += this._render(item.tokens, loose);
  4758. body += `<li>${itemBody}</li>\n`;
  4759. }
  4760. const type = (ordered ? 'ol' : 'ul');
  4761. html += `<${type}${ordered && start !== 1 ? (` start="${start}"`) : ''}>\n${body}</${type}>\n`;
  4762. continue;
  4763. }
  4764. case 'html': {
  4765. html += token.text;
  4766. continue;
  4767. }
  4768. case 'paragraph': {
  4769. html += `<p>${this._renderInline(token.tokens)}</p>\n`;
  4770. continue;
  4771. }
  4772. case 'text': {
  4773. html += top ? '<p>' : '';
  4774. html += token.tokens ? this._renderInline(token.tokens) : token.text;
  4775. while (tokens.length > 0 && tokens[0].type === 'text') {
  4776. const token = tokens.shift();
  4777. html += `\n${token.tokens ? this._renderInline(token.tokens) : token.text}`;
  4778. }
  4779. html += top ? '</p>\n' : '';
  4780. continue;
  4781. }
  4782. default: {
  4783. throw new Error(`Unexpected token type '${token.type}'.`);
  4784. }
  4785. }
  4786. }
  4787. return html;
  4788. }
  4789. _renderInline(tokens) {
  4790. let html = '';
  4791. for (const token of tokens) {
  4792. switch (token.type) {
  4793. case 'escape':
  4794. case 'html':
  4795. case 'text': {
  4796. html += token.text;
  4797. break;
  4798. }
  4799. case 'link': {
  4800. const text = this._renderInline(token.tokens);
  4801. html += `<a href="${token.href}"${token.title ? ` title="${token.title}"` : ''} target="_blank">${text}</a>`;
  4802. break;
  4803. }
  4804. case 'image': {
  4805. html += `<img src="${token.href}" alt="${token.text}"${token.title ? ` title="${token.title}"` : ''}>`;
  4806. break;
  4807. }
  4808. case 'strong': {
  4809. const text = this._renderInline(token.tokens);
  4810. html += `<strong>${text}</strong>`;
  4811. break;
  4812. }
  4813. case 'em': {
  4814. const text = this._renderInline(token.tokens);
  4815. html += `<em>${text}</em>`;
  4816. break;
  4817. }
  4818. case 'codespan': {
  4819. html += `<code>${token.text}</code>`;
  4820. break;
  4821. }
  4822. case 'br': {
  4823. html += '<br>';
  4824. break;
  4825. }
  4826. case 'del': {
  4827. const text = this._renderInline(token.tokens);
  4828. html += `<del>${text}</del>`;
  4829. break;
  4830. }
  4831. default: {
  4832. throw new Error(`Unexpected token type '${token.type}'.`);
  4833. }
  4834. }
  4835. }
  4836. return html;
  4837. }
  4838. _outputLink(match, href, title) {
  4839. title = title ? this._escape(title) : null;
  4840. const text = match[1].replace(/\\([[\]])/g, '$1');
  4841. return match[0].charAt(0) === '!' ?
  4842. { type: 'image', href, title, text: this._escape(text) } :
  4843. { type: 'link', href, title, text };
  4844. }
  4845. _splitCells(tableRow, count) {
  4846. const row = tableRow.replace(/\|/g, (match, offset, str) => {
  4847. let escaped = false;
  4848. let position = offset;
  4849. while (--position >= 0 && str[position] === '\\') {
  4850. escaped = !escaped;
  4851. }
  4852. return escaped ? '|' : ' |';
  4853. });
  4854. const cells = row.split(/ \|/);
  4855. if (cells.length > count) {
  4856. cells.splice(count);
  4857. } else {
  4858. while (cells.length < count) {
  4859. cells.push('');
  4860. }
  4861. }
  4862. return cells.map((cell) => cell.trim().replace(/\\\|/g, '|'));
  4863. }
  4864. _encode(content) {
  4865. if (this._escapeTestRegExp.test(content)) {
  4866. return content.replace(this._escapeReplaceRegExp, (ch) => this._escapeReplacementsMap[ch]);
  4867. }
  4868. return content;
  4869. }
  4870. _escape(content) {
  4871. if (this._escapeTestNoEncodeRegExp.test(content)) {
  4872. return content.replace(this._escapeReplaceNoEncodeRegExp, (ch) => this._escapeReplacementsMap[ch]);
  4873. }
  4874. return content;
  4875. }
  4876. };
  4877. view.Context = class {
  4878. constructor(context, identifier, stream) {
  4879. this._context = context;
  4880. this._tags = new Map();
  4881. this._content = new Map();
  4882. this._identifier = typeof identifier === 'string' ? identifier : context.identifier;
  4883. this._stream = stream || context.stream;
  4884. }
  4885. get identifier() {
  4886. return this._identifier;
  4887. }
  4888. get stream() {
  4889. return this._stream;
  4890. }
  4891. async request(file) {
  4892. return this._context.request(file, 'utf-8', null);
  4893. }
  4894. async fetch(file) {
  4895. const stream = await this._context.request(file, null);
  4896. return new view.Context(this, file, stream, new Map());
  4897. }
  4898. async require(id) {
  4899. return this._context.require(id);
  4900. }
  4901. error(error, fatal) {
  4902. if (error && this.identifier) {
  4903. error.context = this.identifier;
  4904. }
  4905. this._context.error(error, fatal);
  4906. }
  4907. peek(type) {
  4908. if (!this._content.has(type)) {
  4909. this._content.set(type, undefined);
  4910. const stream = this.stream;
  4911. if (stream) {
  4912. const position = stream.position;
  4913. const match = (buffer, signature) => {
  4914. return signature.length <= buffer.length && buffer.every((value, index) => signature[index] === undefined || signature[index] === value);
  4915. };
  4916. const buffer = stream.peek(Math.min(stream.length, 16));
  4917. const skip =
  4918. match(buffer, [0x80, undefined, 0x8a, 0x0a, 0x6c, 0xfc, 0x9c, 0x46, 0xf9, 0x20, 0x6a, 0xa8, 0x50, 0x19]) || // PyTorch
  4919. (type !== 'npz' && type !== 'zip' && match(buffer, [0x50, 0x4B, 0x03, 0x04])) || // Zip
  4920. (type !== 'hdf5' && match(buffer, [0x89, 0x48, 0x44, 0x46, 0x0D, 0x0A, 0x1A, 0x0A])) || // \x89HDF\r\n\x1A\n
  4921. Array.from(this._tags).some(([key, value]) => key !== 'flatbuffers' && value.size > 0) ||
  4922. Array.from(this._content.values()).some((obj) => obj !== undefined);
  4923. if (!skip) {
  4924. switch (type) {
  4925. case 'json': {
  4926. try {
  4927. const buffer = stream.peek(Math.min(this.stream.length, 0x1000));
  4928. if (stream.length < 0x7ffff000 &&
  4929. (buffer.length < 8 || String.fromCharCode.apply(null, buffer.slice(0, 8)) !== '\x89HDF\r\n\x1A\n') &&
  4930. (buffer.some((v) => v === 0x22 || v === 0x5b || v === 0x5d || v === 0x7b || v === 0x7d))) {
  4931. const reader = json.TextReader.open(stream);
  4932. if (reader) {
  4933. const obj = reader.read();
  4934. this._content.set(type, obj);
  4935. }
  4936. }
  4937. } catch {
  4938. // continue regardless of error
  4939. }
  4940. break;
  4941. }
  4942. case 'json.gz': {
  4943. try {
  4944. const entries = this.peek('gzip');
  4945. if (entries && entries.size === 1) {
  4946. const stream = entries.values().next().value;
  4947. const reader = json.TextReader.open(stream);
  4948. if (reader) {
  4949. const obj = reader.read();
  4950. this._content.set(type, obj);
  4951. }
  4952. }
  4953. } catch {
  4954. // continue regardless of error
  4955. }
  4956. break;
  4957. }
  4958. case 'pkl': {
  4959. let unpickler = null;
  4960. const types = new Set();
  4961. try {
  4962. const archive = zip.Archive.open(stream, 'zlib');
  4963. const data = archive ? archive.entries.get('') : stream;
  4964. let condition = false;
  4965. if (data.length > 2) {
  4966. const head = data.peek(2);
  4967. condition = head[0] === 0x80 && head[1] < 7;
  4968. if (!condition) {
  4969. data.seek(-1);
  4970. const tail = data.peek(1);
  4971. data.seek(0);
  4972. condition = tail[0] === 0x2e;
  4973. }
  4974. }
  4975. if (condition) {
  4976. const execution = new python.Execution();
  4977. execution.on('resolve', (_, name) => types.add(name));
  4978. const pickle = execution.__import__('pickle');
  4979. unpickler = new pickle.Unpickler(data);
  4980. }
  4981. } catch {
  4982. // continue regardless of error
  4983. }
  4984. if (unpickler) {
  4985. const storages = new Map();
  4986. unpickler.persistent_load = (saved_id) => {
  4987. if (Array.isArray(saved_id) && saved_id.length > 3) {
  4988. switch (saved_id[0]) {
  4989. case 'storage': {
  4990. const [, storage_type, key, , size] = saved_id;
  4991. if (!storages.has(key)) {
  4992. const storage = new storage_type(size);
  4993. storages.set(key, storage);
  4994. }
  4995. return storages.get(key);
  4996. }
  4997. default: {
  4998. throw new python.Error(`Unsupported persistent load type '${saved_id[0]}'.`);
  4999. }
  5000. }
  5001. }
  5002. throw new view.Error("Unsupported 'persistent_load'.");
  5003. };
  5004. try {
  5005. const obj = unpickler.load();
  5006. this._content.set(type, obj);
  5007. } catch (error) {
  5008. this._content.set(type, error);
  5009. }
  5010. if (Array.from(types).every((name) => !name.startsWith('__torch__.'))) {
  5011. for (const name of types) {
  5012. this.error(new view.Error(`Unknown type name '${name}'.`));
  5013. }
  5014. } else {
  5015. this._content.set(type, new view.Error("PyTorch standalone 'data.pkl' format not supported."));
  5016. }
  5017. }
  5018. break;
  5019. }
  5020. case 'hdf5': {
  5021. const file = hdf5.File.open(stream);
  5022. if (file) {
  5023. try {
  5024. this._content.set(type, file.read());
  5025. } catch (error) {
  5026. this._content.set(type, error);
  5027. }
  5028. }
  5029. break;
  5030. }
  5031. case 'zip':
  5032. case 'tar':
  5033. case 'gzip': {
  5034. this._content.set('zip', undefined);
  5035. this._content.set('tar', undefined);
  5036. this._content.set('gzip', undefined);
  5037. let stream = this._stream;
  5038. try {
  5039. const archive = zip.Archive.open(this._stream, 'gzip');
  5040. if (archive) {
  5041. let entries = archive.entries;
  5042. if (entries.size === 1) {
  5043. const key = entries.keys().next().value;
  5044. stream = entries.values().next().value;
  5045. const name = key === '' ? this.identifier.replace(/\.gz$/, '') : key;
  5046. entries = new Map([[name, stream]]);
  5047. }
  5048. this._content.set('gzip', entries);
  5049. }
  5050. } catch (error) {
  5051. this._content.set('gzip', error);
  5052. }
  5053. let skipTar = false;
  5054. try {
  5055. const archive = zip.Archive.open(stream, 'zip');
  5056. if (archive) {
  5057. this._content.set('zip', archive.entries);
  5058. skipTar = true;
  5059. }
  5060. } catch (error) {
  5061. this._content.set('zip', error);
  5062. }
  5063. if (!skipTar) {
  5064. try {
  5065. const archive = tar.Archive.open(stream);
  5066. if (archive) {
  5067. this._content.set('tar', archive.entries);
  5068. }
  5069. } catch (error) {
  5070. this._content.set('tar', error);
  5071. }
  5072. }
  5073. break;
  5074. }
  5075. case 'flatbuffers.binary': {
  5076. try {
  5077. const reader = flatbuffers.BinaryReader.open(this._stream);
  5078. if (reader) {
  5079. this._content.set('flatbuffers.binary', reader);
  5080. }
  5081. } catch (error) {
  5082. this._content.set('flatbuffers.binary', error);
  5083. }
  5084. break;
  5085. }
  5086. case 'npz': {
  5087. try {
  5088. const content = new Map();
  5089. const entries = this.peek('zip');
  5090. if (entries instanceof Map && entries.size > 0 &&
  5091. Array.from(entries.keys()).every((name) => name.endsWith('.npy'))) {
  5092. const execution = new python.Execution();
  5093. for (const [name, stream] of entries) {
  5094. const buffer = stream.peek();
  5095. const bytes = execution.invoke('io.BytesIO', [buffer]);
  5096. const array = execution.invoke('numpy.load', [bytes]);
  5097. content.set(name, array);
  5098. }
  5099. this._content.set(type, content);
  5100. }
  5101. } catch {
  5102. // continue regardless of error
  5103. }
  5104. break;
  5105. }
  5106. default: {
  5107. throw new view.Error(`Unsupported open format type '${type}'.`);
  5108. }
  5109. }
  5110. }
  5111. if (stream.position !== position) {
  5112. stream.seek(0);
  5113. }
  5114. }
  5115. }
  5116. return this._content.get(type);
  5117. }
  5118. read(type) {
  5119. if (!this._content.has(type)) {
  5120. switch (type) {
  5121. case 'json': {
  5122. const reader = json.TextReader.open(this._stream);
  5123. if (reader) {
  5124. const obj = reader.read();
  5125. this._content.set('json', obj);
  5126. return obj;
  5127. }
  5128. throw new view.Error('Invalid JSON content.');
  5129. }
  5130. case 'bson': {
  5131. const reader = json.BinaryReader.open(this._stream);
  5132. if (reader) {
  5133. return reader.read();
  5134. }
  5135. throw new view.Error('Invalid BSON content.');
  5136. }
  5137. case 'flatbuffers.binary': {
  5138. const reader = flatbuffers.BinaryReader.open(this._stream);
  5139. if (reader) {
  5140. this._content.set('flatbuffers.reader', reader);
  5141. return reader;
  5142. }
  5143. throw new view.Error('Invalid FlatBuffers content.');
  5144. }
  5145. case 'flatbuffers.text': {
  5146. const obj = this.peek('json');
  5147. return flatbuffers.TextReader.open(obj);
  5148. }
  5149. case 'protobuf.binary': {
  5150. return protobuf.BinaryReader.open(this._stream);
  5151. }
  5152. case 'protobuf.text': {
  5153. return protobuf.TextReader.open(this._stream);
  5154. }
  5155. case 'binary': {
  5156. return base.BinaryReader.open(this._stream);
  5157. }
  5158. case 'binary.big-endian': {
  5159. return base.BinaryReader.open(this._stream, false);
  5160. }
  5161. default: {
  5162. break;
  5163. }
  5164. }
  5165. }
  5166. return this.peek(type);
  5167. }
  5168. tags(type) {
  5169. if (!this._tags.has(type)) {
  5170. let tags = new Map();
  5171. const stream = this.stream;
  5172. if (stream) {
  5173. const position = stream.position;
  5174. const signatures = [
  5175. [0x89, 0x48, 0x44, 0x46, 0x0D, 0x0A, 0x1A, 0x0A], // HDF5
  5176. [0x80, undefined, 0x8a, 0x0a, 0x6c, 0xfc, 0x9c, 0x46, 0xf9, 0x20, 0x6a, 0xa8, 0x50, 0x19], // PyTorch
  5177. [0x50, 0x4b], // Zip
  5178. [0x1f, 0x8b] // Gzip
  5179. ];
  5180. const skip =
  5181. signatures.some((signature) => signature.length <= stream.length && stream.peek(signature.length).every((value, index) => signature[index] === undefined || signature[index] === value)) ||
  5182. (Array.from(this._tags).some(([key, value]) => key !== 'flatbuffers' && value.size > 0) && type !== 'pb+') ||
  5183. Array.from(this._content.values()).some((obj) => obj !== undefined) ||
  5184. (stream.length < 0x7ffff000 && json.TextReader.open(stream));
  5185. if (!skip && stream.length < 0x7ffff000) {
  5186. try {
  5187. switch (type) {
  5188. case 'pbtxt': {
  5189. const reader = protobuf.TextReader.open(stream);
  5190. tags = reader ? reader.signature() : tags;
  5191. break;
  5192. }
  5193. case 'pb': {
  5194. const reader = protobuf.BinaryReader.open(stream);
  5195. tags = reader.signature();
  5196. break;
  5197. }
  5198. case 'pb+': {
  5199. const reader = protobuf.BinaryReader.open(stream);
  5200. tags = reader.decode();
  5201. break;
  5202. }
  5203. case 'xml': {
  5204. const reader = xml.TextReader.open(stream);
  5205. if (reader) {
  5206. const document = reader.peek();
  5207. const element = document.documentElement;
  5208. const namespaceURI = element.namespaceURI;
  5209. const localName = element.localName;
  5210. const name = namespaceURI ? `${namespaceURI}:${localName}` : localName;
  5211. tags.set(name, element);
  5212. }
  5213. break;
  5214. }
  5215. default: {
  5216. throw new view.Error(`Unsupported tags format type '${type}'.`);
  5217. }
  5218. }
  5219. } catch {
  5220. tags.clear();
  5221. }
  5222. }
  5223. if (stream.position !== position) {
  5224. stream.seek(position);
  5225. }
  5226. }
  5227. this._tags.set(type, tags);
  5228. }
  5229. return this._tags.get(type);
  5230. }
  5231. metadata(name) {
  5232. return view.Metadata.open(this, name);
  5233. }
  5234. };
  5235. view.EntryContext = class {
  5236. constructor(host, entries) {
  5237. this._host = host;
  5238. this._entries = entries;
  5239. }
  5240. async request(file, encoding, base) {
  5241. if (base === undefined) {
  5242. const stream = this._entries.get(file);
  5243. if (!stream) {
  5244. throw new view.Error('File not found.');
  5245. }
  5246. if (encoding) {
  5247. const decoder = new TextDecoder(encoding);
  5248. const buffer = stream.peek();
  5249. const value = decoder.decode(buffer);
  5250. return value;
  5251. }
  5252. return stream;
  5253. }
  5254. return this._host.request(file, encoding, base);
  5255. }
  5256. async require(id) {
  5257. return this._host.require(id);
  5258. }
  5259. error(error, fatal) {
  5260. this._host.exception(error, fatal);
  5261. }
  5262. };
  5263. view.ArchiveError = class extends Error {
  5264. constructor(message) {
  5265. super(message);
  5266. this.name = 'Error loading archive.';
  5267. }
  5268. };
  5269. view.ModelFactoryService = class {
  5270. constructor(host) {
  5271. this._host = host;
  5272. this._patterns = new Set(['.zip', '.tar', '.tar.gz', '.tgz', '.gz']);
  5273. this._factories = [];
  5274. this.register('./server', ['.netron']);
  5275. this.register('./pytorch', ['.pt', '.pth', '.ptl', '.pt1', '.pyt', '.pyth', '.pkl', '.pickle', '.h5', '.t7', '.model', '.dms', '.tar', '.ckpt', '.chkpt', '.tckpt', '.bin', '.pb', '.zip', '.nn', '.torchmodel', '.torchscript', '.pytorch', '.ot', '.params', '.trt', '.ff', '.ptmf', '.jit', '.pte', '.bin.index.json', 'serialized_exported_program.json'], ['.model', '.pt2']);
  5276. this.register('./onnx', ['.onnx', '.onnx.data', '.onn', '.pb', '.onnxtxt', '.pbtxt', '.prototxt', '.txt', '.model', '.pt', '.pth', '.pkl', '.ort', '.ort.onnx', '.ngf', '.json', '.bin', 'onnxmodel']);
  5277. this.register('./tflite', ['.tflite', '.lite', '.tfl', '.bin', '.pb', '.tmfile', '.h5', '.model', '.json', '.txt', '.dat', '.nb', '.ckpt']);
  5278. this.register('./mxnet', ['.json', '.params'], ['.mar']);
  5279. this.register('./coreml', ['.mlmodel', '.bin', 'manifest.json', 'metadata.json', 'featuredescriptions.json', '.pb', '.pbtxt', '.mil'], ['.mlpackage', '.mlmodelc']);
  5280. this.register('./caffe', ['.caffemodel', '.pbtxt', '.prototxt', '.pt', '.txt']);
  5281. this.register('./caffe2', ['.pb', '.pbtxt', '.prototxt']);
  5282. this.register('./torch', ['.t7', '.net']);
  5283. this.register('./tf', ['.pb', '.meta', '.pbtxt', '.prototxt', '.txt', '.pt', '.json', '.index', '.ckpt', '.graphdef', '.pbmm', /.data-[0-9][0-9][0-9][0-9][0-9]-of-[0-9][0-9][0-9][0-9][0-9]$/, /^events.out.tfevents./], ['.zip']);
  5284. this.register('./tensorrt', ['.trt', '.trtmodel', '.engine', '.model', '.txt', '.uff', '.pb', '.tmfile', '.onnx', '.pth', '.dnn', '.plan', '.pt', '.dat']);
  5285. this.register('./keras', ['.h5', '.hd5', '.hdf5', '.keras', '.json', '.cfg', '.model', '.pb', '.pth', '.weights', '.pkl', '.lite', '.tflite', '.ckpt', '.pb', 'model.weights.npz'], ['.zip']);
  5286. this.register('./numpy', ['.npz', '.npy', '.pkl', '.pickle', '.model', '.model2', '.mge', '.joblib']);
  5287. this.register('./lasagne', ['.pkl', '.pickle', '.joblib', '.model', '.pkl.z', '.joblib.z']);
  5288. this.register('./lightgbm', ['.txt', '.pkl', '.model']);
  5289. this.register('./sklearn', ['.pkl', '.pickle', '.joblib', '.model', '.meta', '.pb', '.pt', '.h5', '.pkl.z', '.joblib.z', '.pickle.dat', '.bin']);
  5290. this.register('./megengine', ['.tm', '.mge', '.pkl']);
  5291. this.register('./pickle', ['.pkl', '.pickle', '.joblib', '.model', '.meta', '.pb', '.pt', '.h5', '.pkl.z', '.joblib.z', '.pdstates', '.mge', '.bin']);
  5292. this.register('./cntk', ['.model', '.cntk', '.cmf', '.dnn']);
  5293. this.register('./uff', ['.uff', '.pb', '.pbtxt', '.uff.txt', '.trt', '.engine']);
  5294. this.register('./paddle', ['.pdmodel', '.pdiparams', '.pdparams', '.pdopt', '.paddle', '__model__', '.__model__', '.pbtxt', '.txt', '.tar', '.tar.gz', '.nb']);
  5295. this.register('./bigdl', ['.model', '.bigdl']);
  5296. this.register('./darknet', ['.cfg', '.model', '.txt', '.weights']);
  5297. this.register('./mediapipe', ['.pbtxt']);
  5298. this.register('./rknn', ['.rknn', '.nb', '.onnx', '.json', '.bin']);
  5299. this.register('./dlc', ['.dlc', 'model', '.params']);
  5300. this.register('./armnn', ['.armnn', '.json']);
  5301. this.register('./mnn', ['.mnn']);
  5302. this.register('./ncnn', ['.param', '.bin', '.cfg.ncnn', '.weights.ncnn', '.ncnnmodel']);
  5303. this.register('./tnn', ['.tnnproto', '.tnnmodel']);
  5304. this.register('./tengine', ['.tmfile']);
  5305. this.register('./mslite', ['.ms', '.bin']);
  5306. this.register('./barracuda', ['.nn']);
  5307. this.register('./circle', ['.circle']);
  5308. this.register('./dnn', ['.dnn']);
  5309. this.register('./xmodel', ['.xmodel']);
  5310. this.register('./kmodel', ['.kmodel']);
  5311. this.register('./flux', ['.bson']);
  5312. this.register('./dl4j', ['.json', '.bin']);
  5313. this.register('./openvino', ['.xml', '.bin']);
  5314. this.register('./mlnet', ['.zip', '.mlnet']);
  5315. this.register('./acuity', ['.json']);
  5316. this.register('./imgdnn', ['.dnn', 'params', '.json']);
  5317. this.register('./flax', ['.msgpack']);
  5318. this.register('./om', ['.om', '.onnx', '.pb', '.engine', '.bin']);
  5319. this.register('./gguf', ['.gguf', /^[^.]+$/]);
  5320. this.register('./nnabla', ['.nntxt'], ['.nnp']);
  5321. this.register('./hickle', ['.h5', '.hkl']);
  5322. this.register('./nnef', ['.nnef', '.dat']);
  5323. this.register('./onednn', ['.json']);
  5324. this.register('./mlir', ['.mlir']);
  5325. this.register('./sentencepiece', ['.model']);
  5326. this.register('./hailo', ['.hn', '.har', '.metadata.json']);
  5327. this.register('./nnc', ['.nnc']);
  5328. this.register('./safetensors', ['.safetensors', '.safetensors.index.json']);
  5329. this.register('./modular', ['.maxviz']);
  5330. this.register('./catboost', ['.cbm']);
  5331. this.register('./cambricon', ['.cambricon']);
  5332. this.register('./weka', ['.model']);
  5333. }
  5334. register(module, factories, containers) {
  5335. for (const pattern of factories) {
  5336. this._factories.push({ pattern, module });
  5337. this._patterns.add(pattern);
  5338. }
  5339. for (const pattern of containers || []) {
  5340. this._patterns.add(pattern);
  5341. }
  5342. }
  5343. async open(context) {
  5344. try {
  5345. await this._openSignature(context);
  5346. const content = new view.Context(context);
  5347. const model = await this._openContext(content);
  5348. if (!model) {
  5349. const check = (obj) => {
  5350. if (obj instanceof Error) {
  5351. throw obj;
  5352. }
  5353. return obj instanceof Map && obj.size > 0;
  5354. };
  5355. let entries = context.entries;
  5356. if (!check(entries)) {
  5357. entries = content.peek('zip');
  5358. if (!check(entries)) {
  5359. entries = content.peek('tar');
  5360. if (!check(entries)) {
  5361. entries = content.peek('gzip');
  5362. }
  5363. }
  5364. }
  5365. if (!check(entries)) {
  5366. this._unsupported(content);
  5367. }
  5368. const entryContext = await this._openEntries(entries);
  5369. if (!entryContext) {
  5370. this._unsupported(content);
  5371. }
  5372. return this._openContext(entryContext);
  5373. }
  5374. return model;
  5375. } catch (error) {
  5376. error.context = !error.context && context && context.identifier ? context.identifier : error.context || '';
  5377. throw error;
  5378. }
  5379. }
  5380. _unsupported(context) {
  5381. const identifier = context.identifier;
  5382. const extension = identifier.split('.').pop().toLowerCase();
  5383. const stream = context.stream;
  5384. const callbacks = [
  5385. (stream) => zip.Archive.open(stream, 'zip'),
  5386. (stream) => tar.Archive.open(stream),
  5387. (stream) => zip.Archive.open(stream, 'gzip')
  5388. ];
  5389. for (const callback of callbacks) {
  5390. let archive = null;
  5391. try {
  5392. archive = callback(stream);
  5393. } catch {
  5394. // continue regardless of error
  5395. }
  5396. if (archive) {
  5397. throw new view.Error("Archive contains no model files.");
  5398. }
  5399. }
  5400. const json = () => {
  5401. const obj = context.peek('json');
  5402. if (obj) {
  5403. const formats = [
  5404. { name: 'Netron metadata', tags: ['[].name', '[].schema'] },
  5405. { name: 'Netron metadata', tags: ['[].name', '[].attributes'] },
  5406. { name: 'Netron metadata', tags: ['[].name', '[].category'] },
  5407. { name: 'Netron test data', tags: ['[].type', '[].target', '[].source', '[].format', '[].link'] },
  5408. { name: 'Netron configuration', tags: ['recents', 'consent'] },
  5409. { name: 'Darkflow metadata', tags: ['net', 'type', 'model'] },
  5410. { name: 'keras-yolo2 configuration', tags: ['model', 'train', 'valid'] },
  5411. { name: 'Vulkan SwiftShader ICD manifest', tags: ['file_format_version', 'ICD'] },
  5412. { name: 'DeepLearningExamples configuration', tags: ['attention_probs_dropout_prob', 'hidden_act', 'hidden_dropout_prob', 'hidden_size',] },
  5413. { name: 'GitHub page data', tags: ['payload', 'title'] },
  5414. { name: 'NuGet assets', tags: ['version', 'targets', 'packageFolders'] },
  5415. { name: 'NuGet data', tags: ['format', 'restore', 'projects'] },
  5416. { name: 'NPM package', tags: ['name', 'version', 'dependencies'] },
  5417. { name: 'NetworkX adjacency_data', tags: ['directed', 'graph', 'nodes'] },
  5418. { name: 'Waifu2x data', tags: ['name', 'arch_name', 'channels'] },
  5419. { name: 'Waifu2x data', tags: ['[].nInputPlane', '[].nOutputPlane', '[].weight', '[].bias'] },
  5420. { name: 'Brain.js data', tags: ['type', 'sizes', 'layers'] },
  5421. { name: 'Custom Vision metadata', tags: ['CustomVision.Metadata.Version'] },
  5422. { name: 'W&B metadata', tags: ['program', 'host', 'executable'] },
  5423. { name: 'TypeScript configuration data', tags: ['compilerOptions'] },
  5424. { name: 'CatBoost model', tags: ['features_info', 'model_info'] },
  5425. { name: 'TPU-MLIR tensor location data', tags: ['file-line', 'subnet_id', 'core_id'] } // https://github.com/sophgo/tpu-mlir/blob/master/lib/Dialect/Tpu/Transforms/Codegen/TensorLocation.cpp
  5426. ];
  5427. const match = (obj, tag) => {
  5428. if (tag.startsWith('[].')) {
  5429. tag = tag.substring(3);
  5430. return (Array.isArray(obj) && obj.some((item) => Object.prototype.hasOwnProperty.call(item, tag)));
  5431. }
  5432. return Object.prototype.hasOwnProperty.call(obj, tag);
  5433. };
  5434. for (const format of formats) {
  5435. if (format.tags.every((tag) => match(obj, tag))) {
  5436. throw new view.Error(`Invalid file content. File contains ${format.name}.`);
  5437. }
  5438. }
  5439. const content = `${JSON.stringify(obj).substring(0, 100).replace(/\s/, '').substring(0, 48)}...`;
  5440. throw new view.Error(`Unsupported JSON content '${content.length > 64 ? `${content.substring(0, 100)}...` : content}' for extension '.${extension}'.`);
  5441. }
  5442. };
  5443. const pbtxt = () => {
  5444. const formats = [
  5445. { name: 'ImageNet LabelMap data', tags: ['entry', 'entry.target_class'] },
  5446. { name: 'StringIntLabelMapProto data', tags: ['item', 'item.id', 'item.name'] },
  5447. { name: 'caffe.LabelMap data', tags: ['item', 'item.name', 'item.label'] },
  5448. { name: 'Triton Inference Server configuration', tags: ['name', 'platform', 'input', 'output'] },
  5449. { name: 'TensorFlow OpList data', tags: ['op', 'op.name', 'op.input_arg'] },
  5450. { name: 'vitis.ai.proto.DpuModelParamList data', tags: ['model', 'model.name', 'model.kernel'] },
  5451. { name: 'object_detection.protos.DetectionModel data', tags: ['model', 'model.ssd'] },
  5452. { name: 'object_detection.protos.DetectionModel data', tags: ['model', 'model.faster_rcnn'] },
  5453. { name: 'tensorflow.CheckpointState data', tags: ['model_checkpoint_path', 'all_model_checkpoint_paths'] },
  5454. { name: 'apollo.perception.camera.traffic_light.detection.DetectionParam data', tags: ['min_crop_size', 'crop_method'] },
  5455. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: ['caffe_ssd'] }, // https://github.com/TexasInstruments/edgeai-mmdetection/blob/master/mmdet/utils/proto/mmdet_meta_arch.proto
  5456. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: ['tf_od_api_ssd'] },
  5457. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: ['tidl_ssd'] },
  5458. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: ['tidl_faster_rcnn'] },
  5459. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: ['tidl_yolo'] },
  5460. { name: 'tidl_meta_arch.TIDLMetaArch data', tags: ['tidl_retinanet'] },
  5461. { name: 'domi.InsertNewOps data', tags: ['aipp_op'] } // https://github.com/Ascend/parser/blob/development/parser/proto/insert_op.proto
  5462. ];
  5463. const tags = context.tags('pbtxt');
  5464. if (tags.size > 0) {
  5465. for (const format of formats) {
  5466. if (format.tags.every((tag) => tags.has(tag))) {
  5467. const error = new view.Error(`Invalid file content. File contains ${format.name}.`);
  5468. error.context = context.identifier;
  5469. throw error;
  5470. }
  5471. }
  5472. const entries = [];
  5473. entries.push(...Array.from(tags).filter(([key]) => key.toString().indexOf('.') === -1));
  5474. entries.push(...Array.from(tags).filter(([key]) => key.toString().indexOf('.') !== -1));
  5475. const content = entries.map(([key, value]) => value === true ? key : `${key}:${JSON.stringify(value)}`).join(',');
  5476. throw new view.Error(`Unsupported Protocol Buffers text content '${content.length > 64 ? `${content.substring(0, 100)}...` : content}' for extension '.${extension}'.`);
  5477. }
  5478. };
  5479. const pb = () => {
  5480. const tags = context.tags('pb+');
  5481. if (Object.keys(tags).length > 0) {
  5482. const formats = [
  5483. { name: 'sentencepiece.ModelProto data', tags: [[1,[[1,2],[2,5],[3,0]]],[2,[[1,2],[2,2],[3,0],[4,0],[5,2],[6,0],[7,2],[10,5],[16,0],[40,0],[41,0],[42,0],[43,0]]],[3,[]],[4,[]],[5,[]]] },
  5484. { name: 'mediapipe.BoxDetectorIndex data', tags: [[1,[[1,[[1,[[1,5],[2,5],[3,5],[4,5],[6,0],[7,5],[8,5],[10,5],[11,0],[12,0]]],[2,5],[3,[]]]],[2,false],[3,false],[4,false],[5,false]]],[2,false],[3,false]] },
  5485. { name: 'third_party.tensorflow.python.keras.protobuf.SavedMetadata data', tags: [[1,[[1,[[1,0],[2,0]]],[2,0],[3,2],[4,2],[5,2]]]] },
  5486. { name: 'pblczero.Net data', tags: [[1,5],[2,2],[3,[[1,0],[2,0],[3,0]],[10,[[1,[]],[2,[]],[3,[]],[4,[]],[5,[]],[6,[]]]],[11,[]]]] }, // https://github.com/LeelaChessZero/lczero-common/blob/master/proto/net.proto
  5487. { name: 'mind_ir.ModelProto', tags: [[1,2],[2,2],[5,2],[7,[]],[10,0],[12,[]],[13,0]] }, // https://github.com/mindspore-ai/mindspore/blob/master/mindspore/core/proto/mind_ir.proto
  5488. { name: 'mindspore.irpb.Checkpoint', tags: [[1,[[1,2],[2,[[1,0],[2,2],[3,2]]]]]] }, // https://github.com/mindspore-ai/mindspore/blob/master/mindspore/ccsrc/utils/checkpoint.proto
  5489. { name: 'optimization_guide.proto.PageTopicsOverrideList data', tags: [[1,[[1,2],[2,[]]]]] }, // https://github.com/chromium/chromium/blob/main/components/optimization_guide/proto/page_topics_override_list.proto
  5490. { name: 'optimization_guide.proto.ModelInfo data', tags: [[1,0],[2,0],[4,0],[6,[]],[7,[]],[9,0]] } // https://github.com/chromium/chromium/blob/22b0d711657b451b61d50dd2e242b3c6e38e6ef5/components/optimization_guide/proto/models.proto#L80
  5491. ];
  5492. const match = (tags, schema) => {
  5493. for (const [key, inner] of schema) {
  5494. const value = tags[key];
  5495. if (value === undefined) {
  5496. continue;
  5497. }
  5498. if (inner === false) {
  5499. return false;
  5500. }
  5501. if (Array.isArray(inner)) {
  5502. if (typeof value !== 'object' || !match(value, inner)) {
  5503. return false;
  5504. }
  5505. } else if (inner !== value) {
  5506. if (inner === 2 && !Array.isArray(value) && Object(value) === (value) && Object.keys(value).length === 0) {
  5507. return true;
  5508. }
  5509. return false;
  5510. }
  5511. }
  5512. return true;
  5513. };
  5514. for (const format of formats) {
  5515. if (match(tags, format.tags)) {
  5516. const error = new view.Error(`Invalid file content. File contains ${format.name}.`);
  5517. error.context = context.identifier;
  5518. throw error;
  5519. }
  5520. }
  5521. const format = (tags) => {
  5522. const content = Object.entries(tags).map(([key, value]) => {
  5523. return `${key}:${Object(value) === value ? `{${format(value)}}` : value}`;
  5524. });
  5525. return content.join(',');
  5526. };
  5527. const content = format(tags);
  5528. throw new view.Error(`Unsupported Protocol Buffers content '${content.length > 64 ? `${content.substring(0, 100)}...` : content}' for extension '.${extension}'.`);
  5529. }
  5530. };
  5531. const flatbuffers = () => {
  5532. const reader = context.peek('flatbuffers.binary');
  5533. if (reader) {
  5534. const file_identifier = reader.identifier;
  5535. const formats = [
  5536. { name: 'ONNX Runtime model data', identifier: 'ORTM' },
  5537. { name: 'TensorFlow Lite model data', identifier: 'TFL3' }
  5538. ];
  5539. for (const format of formats) {
  5540. if (file_identifier === format.identifier) {
  5541. throw new view.Error(`Invalid file content. File contains ${format.name}.`);
  5542. }
  5543. }
  5544. }
  5545. };
  5546. const xml = () => {
  5547. const tags = context.tags('xml');
  5548. if (tags.size > 0) {
  5549. const formats = [
  5550. { name: 'OpenCV storage data', tags: ['opencv_storage'] },
  5551. { name: 'XHTML markup', tags: ['http://www.w3.org/1999/xhtml:html'] }
  5552. ];
  5553. for (const format of formats) {
  5554. if (format.tags.some((tag) => tags.has(tag))) {
  5555. const error = new view.Error(`Invalid file content. File contains ${format.name}.`);
  5556. error.content = context.identifier;
  5557. throw error;
  5558. }
  5559. }
  5560. throw new view.Error(`Unsupported XML content '${tags.keys().next().value}'.`);
  5561. }
  5562. };
  5563. const hdf5 = () => {
  5564. const obj = context.peek('hdf5');
  5565. if (obj instanceof Error) {
  5566. throw obj;
  5567. }
  5568. if (obj) {
  5569. throw new view.Error(`Invalid file content. File contains HDF5 content.`);
  5570. }
  5571. };
  5572. const unknown = () => {
  5573. if (stream) {
  5574. stream.seek(0);
  5575. const buffer = stream.peek(Math.min(16, stream.length));
  5576. const bytes = Array.from(buffer).map((c) => (c < 16 ? '0' : '') + c.toString(16)).join('');
  5577. const content = stream.length > 268435456 ? `(${bytes}) [${stream.length}]` : `(${bytes})`;
  5578. throw new view.Error(`Unsupported file content ${content} for extension '.${extension}'.`);
  5579. }
  5580. throw new view.Error("Unsupported file directory.");
  5581. };
  5582. json();
  5583. pbtxt();
  5584. pb();
  5585. flatbuffers();
  5586. xml();
  5587. hdf5();
  5588. unknown();
  5589. }
  5590. async _require(id) {
  5591. const module = await this._host.require(id);
  5592. if (!module || !module.ModelFactory) {
  5593. throw new view.Error(`Failed to load module '${id}'.`);
  5594. }
  5595. return new module.ModelFactory();
  5596. }
  5597. async _openContext(context) {
  5598. const modules = this._filter(context).filter((module) => module && module.length > 0);
  5599. const errors = [];
  5600. for (const module of modules) {
  5601. /* eslint-disable no-await-in-loop */
  5602. const factory = await this._require(module);
  5603. /* eslint-enable no-await-in-loop */
  5604. factory.match(context);
  5605. if (context.stream && context.stream.position !== 0) {
  5606. throw new view.Error('Invalid stream position.');
  5607. }
  5608. if (context.type) {
  5609. try {
  5610. /* eslint-disable no-await-in-loop */
  5611. const model = await factory.open(context);
  5612. /* eslint-enable no-await-in-loop */
  5613. if (!model.identifier) {
  5614. model.identifier = context.identifier;
  5615. }
  5616. return model;
  5617. } catch (error) {
  5618. delete context.type;
  5619. delete context.target;
  5620. if (context.stream && context.stream.position !== 0) {
  5621. context.stream.seek(0);
  5622. }
  5623. errors.push(error);
  5624. }
  5625. }
  5626. if (context.stream && context.stream.position !== 0) {
  5627. throw new view.Error('Invalid stream position.');
  5628. }
  5629. }
  5630. if (errors.length > 0) {
  5631. if (errors.length === 1) {
  5632. throw errors[0];
  5633. }
  5634. throw new view.Error(errors.map((err) => err.message).join('\n'));
  5635. }
  5636. return null;
  5637. }
  5638. async _openEntries(entries) {
  5639. try {
  5640. const rootFolder = (files) => {
  5641. const map = files.map((file) => file.split('/').slice(0, -1));
  5642. const at = (index) => (list) => list[index];
  5643. const rotate = (list) => list.length === 0 ? [] : list[0].map((item, index) => list.map(at(index)));
  5644. const equals = (list) => list.every((item) => item === list[0]);
  5645. const folder = rotate(map).filter(equals).map(at(0)).join('/');
  5646. return folder.length === 0 ? folder : `${folder}/`;
  5647. };
  5648. const files = Array.from(entries).filter(([name]) => !(name.endsWith('/') || name.split('/').pop().startsWith('.') || (!name.startsWith('./') && name.startsWith('.'))));
  5649. const folder = rootFolder(files.map(([name]) => name));
  5650. const filter = async (queue, entries) => {
  5651. entries = new Map(Array.from(entries)
  5652. .filter(([path]) => path.startsWith(folder))
  5653. .map(([path, stream]) => [path.substring(folder.length), stream]));
  5654. const entryContext = new view.EntryContext(this._host, entries);
  5655. let matches = [];
  5656. for (const [name, stream] of queue) {
  5657. const identifier = name.substring(folder.length);
  5658. const context = new view.Context(entryContext, identifier, stream);
  5659. const modules = this._filter(context);
  5660. for (const module of modules) {
  5661. /* eslint-disable no-await-in-loop */
  5662. const factory = await this._require(module);
  5663. /* eslint-enable no-await-in-loop */
  5664. factory.match(context);
  5665. if (context.stream && context.stream.position !== 0) {
  5666. throw new view.Error('Invalid stream position.');
  5667. }
  5668. delete context.target;
  5669. if (context.type) {
  5670. matches = matches.filter((match) => !factory.filter || factory.filter(context, match.type));
  5671. if (matches.every((match) => !match.factory.filter || match.factory.filter(match, context.type))) {
  5672. context.factory = factory;
  5673. matches.push(context);
  5674. }
  5675. break;
  5676. }
  5677. }
  5678. }
  5679. if (matches.length > 1) {
  5680. const content = matches.map((context) => context.type).join(',');
  5681. throw new view.ArchiveError(`Archive contains multiple model files '${content}'.`);
  5682. }
  5683. if (matches.length > 0) {
  5684. const match = matches.shift();
  5685. delete match.type;
  5686. delete match.factory;
  5687. return match;
  5688. }
  5689. return null;
  5690. };
  5691. const queue = files.filter(([name]) => name.substring(folder.length).indexOf('/') < 0);
  5692. let context = await filter(queue, entries);
  5693. if (!context) {
  5694. const queue = files.filter(([name]) => name.substring(folder.length).indexOf('/') >= 0);
  5695. context = await filter(queue, entries);
  5696. }
  5697. return context;
  5698. } catch (error) {
  5699. throw new view.ArchiveError(error.message);
  5700. }
  5701. }
  5702. accept(identifier, size) {
  5703. const extension = identifier.indexOf('.') === -1 ? '' : identifier.split('.').pop().toLowerCase();
  5704. identifier = identifier.toLowerCase().split('/').pop();
  5705. let accept = false;
  5706. for (const extension of this._patterns) {
  5707. if ((typeof extension === 'string' && identifier.endsWith(extension)) ||
  5708. (extension instanceof RegExp && extension.exec(identifier))) {
  5709. accept = true;
  5710. break;
  5711. }
  5712. }
  5713. this._host.event('model_file', {
  5714. file_extension: extension,
  5715. file_size: size || 0,
  5716. file_accept: accept ? 1 : 0
  5717. });
  5718. return accept;
  5719. }
  5720. _filter(context) {
  5721. const identifier = context.identifier.toLowerCase().split('/').pop();
  5722. const list = this._factories.filter((entry) =>
  5723. (typeof entry.pattern === 'string' && identifier.endsWith(entry.pattern)) ||
  5724. (entry.pattern instanceof RegExp && entry.pattern.test(identifier)));
  5725. return Array.from(new Set(list.map((entry) => entry.module)));
  5726. }
  5727. async _openSignature(context) {
  5728. const stream = context.stream;
  5729. if (stream) {
  5730. let empty = true;
  5731. let position = 0;
  5732. while (position < stream.length) {
  5733. const buffer = stream.read(Math.min(4096, stream.length - position));
  5734. position += buffer.length;
  5735. if (!buffer.every((value) => value === 0x00)) {
  5736. empty = false;
  5737. break;
  5738. }
  5739. }
  5740. stream.seek(0);
  5741. if (empty) {
  5742. throw new view.Error('File has no content.');
  5743. }
  5744. /* eslint-disable no-control-regex */
  5745. const entries = [
  5746. { name: 'ELF executable', value: /^\x7FELF/ },
  5747. { name: 'PNG image', value: /^\x89PNG/ },
  5748. { name: 'Git LFS header', value: /^version https:\/\/git-lfs.github.com/ },
  5749. { name: 'Git LFS header', value: /^\s*oid sha256:/ },
  5750. { name: 'GGML data', value: /^lmgg|fmgg|tjgg|algg|fugg/ },
  5751. { name: 'HTML markup', value: /^\s*<html>/ },
  5752. { name: 'HTML markup', value: /^\s*<!doctype\s*html>/ },
  5753. { name: 'HTML markup', value: /^\s*<!DOCTYPE\s*html>/ },
  5754. { name: 'HTML markup', value: /^\s*<!DOCTYPE\s*HTML>/ },
  5755. { name: 'HTML markup', value: /^\s*<!DOCTYPE\s*HTML\s+(PUBLIC|SYSTEM)?/ },
  5756. { name: 'Unity metadata', value: /^fileFormatVersion:/ },
  5757. { name: 'Python source code', value: /^((#.*(\n|\r\n))|('''.*'''(\n|\r\n))|("""[\s\S]*""")|(\n|\r\n))*(import[ ]+[a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*([ ]+as[ ]+[a-zA-Z]\w*)?[ ]*(,|;|\n|\r\n))/ },
  5758. { name: 'Python source code', value: /^((#.*(\n|\r\n))|('''.*'''(\n|\r\n))|("""[\s\S]*""")|(\n|\r\n))*(from[ ]+([a-zA-Z_]\w*(\.[a-zA-Z_]\w*)*)[ ]+import[ ]+[a-zA-Z]\w*)/ },
  5759. { name: 'Python virtual environment configuration', value: /^home[ ]*=[ ]*/, identifier: 'pyvenv.cfg' },
  5760. { name: 'Bash script', value: /^#!\/usr\/bin\/env\s/ },
  5761. { name: 'Bash script', value: /^#!\/bin\/bash\s/ },
  5762. { name: 'TSD header', value: /^%TSD-Header-###%/ },
  5763. { name: 'AppleDouble data', value: /^\x00\x05\x16\x07/ },
  5764. { name: 'TensorFlow Hub module', value: /^\x08\x03$/, identifier: 'tfhub_module.pb' },
  5765. { name: 'V8 snapshot', value: /^.\x00\x00\x00.\x00\x00\x00/, identifier: 'snapshot_blob.bin' },
  5766. { name: 'V8 context snapshot', value: /^.\x00\x00\x00.\x00\x00\x00/, identifier: 'v8_context_snapshot.bin' },
  5767. { name: 'V8 natives blob', value: /^./, identifier: 'natives_blob.bin' },
  5768. { name: 'ViSQOL model', value: /^svm_type\s/ },
  5769. { name: 'SenseTime model', value: /^STEF/ },
  5770. { name: 'AES Crypt data', value: /^AES[\x01|\x02]\x00/ },
  5771. { name: 'BModel data', value: /^\xEE\xAA\x55\xFF/ }, // https://github.com/sophgo/tpu-mlir/blob/master/include/tpu_mlir/Builder/BM168x/bmodel.fbs
  5772. { name: 'CviModel data', value: /^CviModel/ } // https://github.com/sophgo/tpu-mlir/blob/master/include/tpu_mlir/Builder/CV18xx/proto/cvimodel.fbs
  5773. ];
  5774. /* eslint-enable no-control-regex */
  5775. const buffer = stream.peek(Math.min(4096, stream.length));
  5776. const content = String.fromCharCode.apply(null, buffer);
  5777. for (const entry of entries) {
  5778. if (content.match(entry.value) && (!entry.identifier || entry.identifier === context.identifier)) {
  5779. throw new view.Error(`Invalid file content. File contains ${entry.name}.`);
  5780. }
  5781. }
  5782. }
  5783. }
  5784. async import() {
  5785. if (this._host.type === 'Browser' || this._host.type === 'Python') {
  5786. const files = [
  5787. './server', './onnx', './pytorch', './tflite', './mlnet',
  5788. './onnx-proto', './onnx-schema', './tflite-schema',
  5789. 'onnx-metadata.json', 'pytorch-metadata.json', 'tflite-metadata.json'
  5790. ];
  5791. for (const file of files) {
  5792. /* eslint-disable no-await-in-loop */
  5793. try {
  5794. if (file.startsWith('./')) {
  5795. await this._host.require(file);
  5796. } else if (file.endsWith('.json')) {
  5797. await this._host.request(file, 'utf-8', null);
  5798. }
  5799. } catch {
  5800. // continue regardless of error
  5801. }
  5802. /* eslint-enable no-await-in-loop */
  5803. }
  5804. }
  5805. }
  5806. };
  5807. view.Metadata = class {
  5808. static async open(context, name) {
  5809. view.Metadata._metadata = view.Metadata._metadata || new Map();
  5810. const metadata = view.Metadata._metadata;
  5811. if (!metadata.has(name)) {
  5812. try {
  5813. const content = await context.request(name);
  5814. const types = JSON.parse(content);
  5815. metadata.set(name, new view.Metadata(types));
  5816. } catch {
  5817. metadata.set(name, new view.Metadata(null));
  5818. }
  5819. }
  5820. return metadata.get(name);
  5821. }
  5822. constructor(types) {
  5823. this._types = new Map();
  5824. this._attributes = new Map();
  5825. this._inputs = new Map();
  5826. if (Array.isArray(types)) {
  5827. for (const type of types) {
  5828. this._types.set(type.name, type);
  5829. if (type.identifier !== undefined) {
  5830. this._types.set(type.identifier, type);
  5831. }
  5832. }
  5833. }
  5834. }
  5835. type(name) {
  5836. if (!this._types.has(name)) {
  5837. this._types.set(name, { name: name.toString() });
  5838. }
  5839. return this._types.get(name);
  5840. }
  5841. attribute(type, name) {
  5842. const key = `${type}:${name}`;
  5843. if (!this._attributes.has(key)) {
  5844. this._attributes.set(key, null);
  5845. const metadata = this.type(type);
  5846. if (metadata && Array.isArray(metadata.attributes)) {
  5847. for (const attribute of metadata.attributes) {
  5848. this._attributes.set(`${type}:${attribute.name}`, attribute);
  5849. }
  5850. }
  5851. }
  5852. return this._attributes.get(key);
  5853. }
  5854. input(type, name) {
  5855. const key = `${type}:${name}`;
  5856. if (!this._inputs.has(key)) {
  5857. this._inputs.set(key, null);
  5858. const metadata = this.type(type);
  5859. if (metadata && Array.isArray(metadata.inputs)) {
  5860. for (const input of metadata.inputs) {
  5861. this._inputs.set(`${type}:${input.name}`, input);
  5862. }
  5863. }
  5864. }
  5865. return this._inputs.get(key);
  5866. }
  5867. };
  5868. view.Error = class extends Error {
  5869. constructor(message) {
  5870. super(message);
  5871. this.name = 'Error loading model.';
  5872. }
  5873. };
  5874. if (typeof window !== 'undefined' && window.exports) {
  5875. window.exports.view = view;
  5876. }
  5877. export const View = view.View;
  5878. export const ModelFactoryService = view.ModelFactoryService;
  5879. export const ModelSidebar = view.ModelSidebar;
  5880. export const NodeSidebar = view.NodeSidebar;
  5881. export const Documentation = view.Documentation;
  5882. export const Formatter = view.Formatter;
  5883. export const Tensor = view.Tensor;
  5884. export const Quantization = view.Quantization;