robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
69e61d52e2
master
1const DEBUG = false ; 2const statusEl = document . getElementById ( "status" ); 3const setStatus = ( s ) => ( statusEl . textContent = s ); 4const log = ( ...args ) => { 5if ( ! DEBUG ) return ; 6if ( logEl ) { 7logEl . textContent += 8args 9. map (( a ) => ( typeof a === "string" ?a :JSON . stringify ( a ))) 10. join ( " " ) + "\n" ; 11} 12console . log ( ...args ); 13}; 14 15// UiState below is ported from (github.com/MuNeNiCK/nvim-wasm) 16// but, extended with win_viewport tracking. 17class UiState { 18constructor ( cols , rows ) { 19this . defaultWidth = Math . max ( 1 , cols || 80 ); 20this . defaultHeight = Math . max ( 1 , rows || 24 ); 21this . defaultGrid = 1 ; 22this . activeGrid = this . defaultGrid ; 23this . grids = new Map (); 24this . grids . set ( 25this . defaultGrid , 26this . #createGrid( this . defaultWidth , this . defaultHeight ), 27); 28this . cursor = { grid :this . defaultGrid , row :0 , col :0 }; 29this . mode = "-" ; 30this . modeIdx = 0 ; 31this . cursorStyleEnabled = false ; 32this . modeInfo = []; 33this . cursorHlId = 0 ; 34this . hls = new Map (); 35this . hls . set ( 0 , { foreground :null , background :null , reverse :false }); 36this . windows = new Map (); 37} 38 39resize ( gridId , width , height ) { 40const grid = this . #ensureGrid( gridId ); 41const w = Math . max ( 1 , width || 0 ); 42const h = Math . max ( 1 , height || 0 ); 43grid . width = w ; 44grid . height = h ; 45grid . cells = Array . from ({ length :h }, () => this . #blankRow( w )); 46} 47 48clear ( gridId ) { 49const grid = this . #ensureGrid( gridId ); 50grid . cells = Array . from ({ length :grid . height }, () => 51this . #blankRow( grid . width ), 52); 53} 54 55destroy ( gridId ) { 56this . grids . delete ( gridId ); 57this . windows . delete ( gridId ); 58if ( this . activeGrid === gridId ) this . activeGrid = this . defaultGrid ; 59} 60 61line ( gridId , row , colStart , cells ) { 62const grid = this . #ensureGrid( gridId ); 63const rowIdx = row || 0 ; 64if ( rowIdx < 0 || rowIdx >= grid . height ) return ; 65const rowCells = 66grid . cells [ rowIdx ] || ( grid . cells [ rowIdx ] = this . #blankRow( grid . width )); 67let col = colStart || 0 ; 68let currentHl = 0 ; 69for ( const cell of cells ) { 70const text = cell [ 0 ]; 71const hlId = 72cell . length > 1 && cell [ 1 ] !== undefined ?cell [ 1 ] :currentHl ; 73currentHl = hlId ; 74const repeat = cell [ 2 ] || 1 ; 75for ( let r = 0 ; r < repeat && col < grid . width ; r += 1 ) { 76rowCells [ col ] = { ch :text || " " , hl :hlId }; 77col += 1 ; 78} 79} 80} 81 82scroll ( gridId , top , bot , left , right , rows ) { 83const grid = this . #ensureGrid( gridId ); 84const height = bot - top ; 85const width = right - left ; 86const slice = []; 87for ( let i = 0 ; i < height ; i += 1 ) { 88const row = grid . cells [ top + i ] || this . #blankRow( grid . width ); 89slice . push ( row . slice ( left , right )); 90} 91if ( rows > 0 ) { 92for ( let i = 0 ; i < height - rows ; i += 1 ) { 93grid . cells [ top + i ]. splice ( left , width , ...slice [ i + rows ]); 94} 95for ( let i = height - rows ; i < height ; i += 1 ) { 96grid . cells [ top + i ]. splice ( left , width , ...this . #blankRow( width )); 97} 98} else if ( rows < 0 ) { 99for ( let i = height - 1 ; i >= - rows ; i -= 1 ) { 100grid . cells [ top + i ]. splice ( left , width , ...slice [ i + rows ]); 101} 102for ( let i = 0 ; i < - rows ; i += 1 ) { 103grid . cells [ top + i ]. splice ( left , width , ...this . #blankRow( width )); 104} 105} 106} 107 108setCursor ( gridId , row , col ) { 109this . activeGrid = gridId ; 110this . #ensureGrid( gridId ); 111this . cursor = { grid :gridId , row :row || 0 , col :col || 0 }; 112} 113 114setMode ( mode , modeIdx ) { 115this . mode = mode || "-" ; 116if ( Number . isInteger ( modeIdx )) this . modeIdx = modeIdx ; 117this . #updateCursorHl(); 118} 119 120setModeInfo ( cursorStyleEnabled , modeInfo ) { 121this . cursorStyleEnabled = Boolean ( cursorStyleEnabled ); 122this . modeInfo = Array . isArray ( modeInfo ) ?modeInfo :[]; 123this . #updateCursorHl(); 124} 125 126defineHl ( id , rgbAttr = {}) { 127this . hls . set ( id , { 128foreground :this . #toHex( rgbAttr . foreground ), 129background :this . #toHex( rgbAttr . background ), 130reverse :Boolean ( rgbAttr . reverse ), 131}); 132} 133 134setWindowViewport ( gridId , winHandle , topline , botline ) { 135this . windows . set ( gridId , { winHandle, topline, botline}); 136} 137 138snapshot () { 139const grid = 140this . grids . get ( this . activeGrid ) || this . grids . get ( this . defaultGrid ); 141if ( ! grid ) 142return { 143cells :[[{ ch :" " , hl :0 }]], 144cursor :{ row :0 , col :0 }, 145mode :this . mode , 146hls :this . hls , 147}; 148const row = Math . min ( Math . max ( this . cursor . row , 0 ), grid . height - 1 ); 149const col = Math . min ( Math . max ( this . cursor . col , 0 ), grid . width - 1 ); 150return { 151cells :grid . cells . map (( r ) => 152r . map (( c ) => ({ ch :c ?. ch ?? " " , hl :c ?. hl ?? 0 })), 153), 154cursor :{ row, col}, 155cursorHlId :this . cursorHlId , 156mode :this . mode , 157hls :this . hls , 158}; 159} 160 161 #ensureGrid( gridId ) { 162if ( ! this . grids . has ( gridId )) 163this . grids . set ( 164gridId , 165this . #createGrid( this . defaultWidth , this . defaultHeight ), 166); 167return this . grids . get ( gridId ); 168} 169 #createGrid( width , height ) { 170return { 171 width, 172 height, 173cells :Array . from ({ length :height }, () => this . #blankRow( width )), 174}; 175} 176 #blankRow( width ) { 177return Array . from ({ length :width }, () => ({ ch :" " , hl :0 })); 178} 179 #updateCursorHl() { 180if ( ! this . cursorStyleEnabled ) { 181this . cursorHlId = 0 ; 182return ; 183} 184const info = this . modeInfo [ this . modeIdx ] || null ; 185this . cursorHlId = info ?. attr_id ?? 0 ; 186} 187 #toHex( value ) { 188if ( value === undefined || value === null ) return null ; 189return `# ${( value >>> 0 ). toString ( 16 ). padStart ( 6 , "0" ). slice ( - 6 )} ` ; 190} 191} 192 193function handleRedrawEvents ( uiState , gridEl , modeEl , events ) { 194for ( const ev of events ) { 195const [ name , ...entries ] = ev ; 196switch ( name ) { 197case "grid_resize" : 198for ( const [ grid , w , h ] of entries ) uiState . resize ( grid , w , h ); 199break ; 200case "grid_clear" : 201for ( const [ grid ] of entries ) uiState . clear ( grid ); 202break ; 203case "grid_destroy" : 204for ( const [ grid ] of entries ) uiState . destroy ( grid ); 205break ; 206case "grid_line" : 207for ( const [ grid , row , col , cells ] of entries ) 208uiState . line ( grid , row , col , cells ); 209break ; 210case "grid_scroll" : 211for ( const [ grid , top , bot , left , right , rows ] of entries ) 212uiState . scroll ( grid , top , bot , left , right , rows ); 213break ; 214case "grid_cursor_goto" : 215for ( const [ grid , row , col ] of entries ) 216uiState . setCursor ( grid , row , col ); 217break ; 218case "win_viewport" : 219for ( const [ grid , win , topline , botline ] of entries ) 220uiState . setWindowViewport ( grid , win , topline , botline ); 221break ; 222case "mode_info_set" : 223for ( const [ enabled , modeInfo ] of entries ) 224uiState . setModeInfo ( enabled , modeInfo ); 225break ; 226case "mode_change" : 227for ( const [ mode , idx ] of entries ) uiState . setMode ( mode , idx ); 228break ; 229case "hl_attr_define" : 230for ( const [ id , rgbAttr ] of entries ) uiState . defineHl ( id , rgbAttr ); 231break ; 232case "flush" : 233paintGrid ( uiState , gridEl , modeEl ); 234break ; 235default : 236break ; // mouse on/off, busy start/stop, etc. 237} 238} 239} 240 241function paintGrid ( uiState , gridEl , modeEl ) { 242const { cells, cursor, cursorHlId, mode, hls} = uiState . snapshot (); 243let html = "" ; 244for ( let r = 0 ; r < cells . length ; r += 1 ) { 245for ( let c = 0 ; c < cells [ r ]. length ; c += 1 ) { 246const cell = cells [ r ][ c ]; 247const isCursor = r === cursor . row && c === cursor . col ; 248const hl = hls . get ( isCursor ?cursorHlId :cell . hl ) || {}; 249let style = "" ; 250if ( hl . reverse ) { 251style = `color: ${ hl . background || "#050912" } ;background: ${ hl . foreground || "#dfe5f1" } ` ; 252} else { 253if ( hl . foreground ) style += `color: ${ hl . foreground } ;` ; 254if ( hl . background ) style += `background: ${ hl . background } ;` ; 255} 256const ch = escapeHtml ( cell . ch || " " ); 257if ( isCursor ) { 258html += `<span class="cursor" style=" ${ style } "> ${ ch } </span>` ; 259} else if ( style ) { 260html += `<span style=" ${ style } "> ${ ch } </span>` ; 261} else { 262html += ch ; 263} 264} 265if ( r < cells . length - 1 ) html += "\n" ; 266} 267gridEl . innerHTML = html || " " ; 268if ( modeEl ) modeEl . textContent = `mode: ${ mode } ` ; 269} 270 271function escapeHtml ( ch ) { 272if ( ch === "&" ) return "&" ; 273if ( ch === "<" ) return "<" ; 274if ( ch === ">" ) return ">" ; 275return ch ; 276} 277 278function translateKey ( ev ) { 279const isCtrl = ev . ctrlKey || ev . metaKey ; 280const isAlt = ev . altKey ; 281const named = { 282Backspace :"<BS>" , 283Enter :"<CR>" , 284Escape :"<Esc>" , 285Tab :"<Tab>" , 286ArrowUp :"<Up>" , 287ArrowDown :"<Down>" , 288ArrowLeft :"<Left>" , 289ArrowRight :"<Right>" , 290Delete :"<Del>" , 291Home :"<Home>" , 292End :"<End>" , 293PageUp :"<PageUp>" , 294PageDown :"<PageDown>" , 295}; 296if ( named [ ev . key ]) return named [ ev . key ]; 297if ( ev . key . length === 1 ) { 298let char = ev . key ; 299if ( char === "<" ) char = "<lt>" ; 300if ( ! isCtrl && ! isAlt ) return char ; 301let mod = "" ; 302if ( isCtrl ) mod += "C-" ; 303if ( isAlt ) mod += "A-" ; 304return `< ${ mod } ${ char } >` ; 305} 306return null ; 307} 308 309function main () { 310const transport = new WorkerTransport ( "nvim-worker.js" , { 311cols :120 , 312rows :40 , 313}); 314// internal FS.write/stderr trace line the worker emits. 315transport . onStatus (( text ) => { 316log ( "[status]" , text ); 317if ( / ^ ( FS\.write | WRITE HOOK | \[stderr\] ) / . test ( text )) return ; 318setStatus ( text ); 319}); 320 321const nvim = new RpcClient ( transport ); 322window . nvim = nvim ; // for console debugging 323 324const uiState = new UiState ( 120 , 40 ); 325const gridEl = document . getElementById ( "grid" ); 326const modeEl = document . getElementById ( "mode" ); 327 328let apiInfoPromise = null ; 329function ensureHandleTypesRegistered () { 330if ( ! apiInfoPromise ) { 331apiInfoPromise = ( async () => { 332const result = await nvim . request ( "nvim_get_api_info" , []); 333log ( "RESPONSE nvim_get_api_info ->" , result ); 334 335const [ channelId , metadata ] = result ; 336log ( "types metadata ->" , metadata . types ); 337 338registerNvimHandleTypes ( metadata . types ); 339setStatus ( "got nvim_get_api_info response, handle types registered" ); 340 341return result ; 342})(); 343} 344return apiInfoPromise ; 345} 346 347// Auto-attach + visible failure status 348transport . onReady ( async () => { 349const maxAttempts = 5 ; 350for ( let attempt = 1 ; attempt <= maxAttempts ; attempt += 1 ) { 351try { 352await ensureHandleTypesRegistered (); 353await nvim . request ( "nvim_ui_attach" , [ 354110 , 35540 , 356{ rgb :true , ext_linegrid :true }, 357]); 358setStatus ( "UI attached" ); 359return ; 360} catch ( e ) { 361console . error ( `auto-attach attempt ${ attempt } failed` , e ); 362log ( "auto-attach failed ->" , e && e . message ?e . message :String ( e )); 363if ( attempt === maxAttempts ) { 364setStatus ( "auto-attach failed after retries, see console (F12)" ); 365} else { 366await new Promise (( r ) => setTimeout ( r , 300 * attempt )); 367} 368} 369} 370}); 371transport . onExit (( code ) => { 372setStatus ( `Neovim exited (code ${ code } ). Refresh the page to start a new session.` ); 373gridEl . style . opacity = "0.5" ; 374}); 375nvim . on ( "redraw" , ( params ) => 376handleRedrawEvents ( uiState , gridEl , modeEl , params ), 377); 378 379gridEl . addEventListener ( "click" , () => gridEl . focus ()); 380gridEl . addEventListener ( "keydown" , ( ev ) => { 381const isPasteShortcut = 382( ev . ctrlKey && ev . shiftKey && ev . key . toLowerCase () === "v" ) || // Linux/Win: Ctrl+Shift+V 383( ev . metaKey && ev . key . toLowerCase () === "v" ); // macOS: Cmd+V 384if ( isPasteShortcut ) { 385return ; 386} 387const keys = translateKey ( ev ); 388if ( ! keys ) return ; 389ev . preventDefault (); 390nvim 391. request ( "nvim_input" , [ keys ]) 392. catch (( e ) => console . error ( "nvim_input failed" , e )); 393}); 394gridEl . addEventListener ( "paste" , ( ev ) => { 395ev . preventDefault (); 396const text = ev . clipboardData . getData ( "text/plain" ); 397if ( ! text ) return ; 398nvim 399. request ( "nvim_paste" , [ text , true , - 1 ]) 400. catch (( e ) => console . error ( "paste nvim_input failed" , e )); 401}); 402 403} 404 405if ( ! crossOriginIsolated ) { 406setStatus ( 407"NOT cross-origin isolated -- SharedArrayBuffer unavailable. Serve with COOP/COEP headers." , 408); 409} else { 410main (); 411}