view.js 229 KB

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