robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

bfredlMerge pull request #41186 from Rawan10101/fix-wasm-browser69e61d52e2

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