Something went wrong. Try again.
Monorepo for the nibling.run platform
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867// Demo harness: a VS Code-style Explorer over the VFS (host fs CRUD) plus a// guest runner in an OUTPUT panel. All page logic, no dependencies. Every fs// operation goes through runtime.fs (async port RPC to the kernel's pid-0 host// process) and every tree update rides runtime.onFsChanged — the kernel is the// single writer, so guest writeFileSync and page Save light up the same tree// within the host's ~25 ms coalesce window.//// Editor model: one tab per open file. Each tab owns an in-memory buffer;// switching tabs never touches the disk, so unsaved edits survive tab// switches and are discarded only when their tab closes. The dirty dot// (● in the tab and in its tooltip) shows buffer ≠ saved.//// No window.prompt/confirm/alert anywhere: create/rename run through the// inline row, recursive directory deletion through the inline confirm row.//// Editor surface: files type into #content with a microlighter highlight// mirror painted behind it (CSS Custom Highlight API).import { highlightAll } from "/dist/demo/vendor.js";import { boot } from "@nibling/kernel";
const $ = (id) => document.getElementById(id);
const el = { app: $("app"), status: $("status"), // sidebar sidebar: $("sidebar"), tree: $("tree"), inlineRow: $("inline-row"), inlineLabel: $("inline-label"), inlineInput: $("inline-input"), inlineOk: $("inline-ok"), inlineCancel: $("inline-cancel"), confirmRow: $("confirm-row"), confirmText: $("confirm-text"), confirmYes: $("confirm-yes"), confirmNo: $("confirm-no"), // editor area tabs: $("tabs"), btnSave: $("btn-save"), btnEditorDelete: $("btn-editor-delete"), editorBody: $("editor-body"), editorEmpty: $("editor-empty"), emptyTitle: $("empty-title"), gutter: $("gutter"), gutterInner: $("gutter-inner"), hlWrap: $("hl-wrap"), hlMirror: $("hl-mirror"), content: $("content"), fileNote: $("file-note"), // output panel entry: $("entry"), btnRun: $("btn-run"), exit: $("exit"), output: $("output"), outputLog: $("output-log"), stdout: $("stdout"), stderr: $("stderr"), // status bar sbBoot: $("sb-boot"), sbExit: $("sb-exit"), sbSelected: $("sb-selected"), // activity bar + context menu btnViewExplorer: $("btn-view-explorer"), btnViewOutput: $("btn-view-output"), contextMenu: $("context-menu"),};
const utf8 = new TextDecoder("utf-8", { fatal: true }); // throws on non-UTF-8 → treated as binaryconst INDENT = 10; // tree indent per level (px); the twisty column adds 16px
// ---- state ----const state = { runtime: null, // Tree root, configurable: ?root=/ in the URL (the old root input is gone — // the Explorer reads like VS Code's, which has no editable root). root: new URLSearchParams(location.search).get("root") || "/app", selected: null, // { path, kind } | null — tree highlight + status bar inlineMode: null, // "new-file" | "new-folder" | "rename" inlineTarget: null, // row the inline flow was opened from (context menu target) // Editor tabs: path → { saved, buffer, binary, bytes }. `saved` mirrors what // the fs last returned or was written; `buffer` is the live (possibly // unsaved) text. Switching tabs never touches disk. tabs: new Map(), activePath: null, // path of the active tab | null // Expansion state survives every tree re-render: renderTree re-applies it. // Seeded below with root + first-level dirs (node_modules stays collapsed); // a folder created at runtime is not in the set → starts collapsed. expanded: new Set(), contextTarget: null, // row the context menu was opened on confirmTarget: null, // dir awaiting recursive-delete confirmation};
// ---- path helpers (lexical; the kernel walks physically) ----const dirnameOf = (p) => { const i = p.lastIndexOf("/"); return i <= 0 ? "/" : p.slice(0, i); };const basenameOf = (p) => p.slice(p.lastIndexOf("/") + 1);const joinPath = (dir, name) => (dir.endsWith("/") ? dir : dir + "/") + name;
// File icon class by extension (one colored dot per family; folders get a// folder glyph instead — see harness.css).function extClass(name) { const m = /\.([a-z0-9]+)$/i.exec(name); switch (m ? m[1].toLowerCase() : "") { case "js": case "cjs": case "mjs": return "ext-js"; case "ts": case "mts": return "ext-ts"; case "json": return "ext-json"; case "md": return "ext-md"; case "txt": return "ext-txt"; default: return "ext-other"; }}
// Editor surface by extension: microlighter grammar name (null = plain// textarea, no mirror). Languages mirror microlighter's bundled grammars.// Unsupported extensions stay plain.const EXT_LANG = { js: "javascript", cjs: "javascript", mjs: "javascript", ts: "typescript", mts: "typescript", json: "json", css: "css", html: "html", md: "markdown",};function langFor(path) { const m = /\.([a-z0-9]+)$/i.exec(path); return m ? EXT_LANG[m[1].toLowerCase()] ?? null : null;}
// ---- status channels ----// #status is the single notification element (errors with their Node code,// never silent, never alert()). The status bar's left segment carries only// the boot state; the right carries exit code / selection / encoding.function showStatus(text, isError = false) { el.status.textContent = text; el.status.classList.toggle("error", isError); el.status.hidden = false;}function describeError(e) { const err = e ?? {}; const code = err.code ? `[${err.code}] ` : ""; return code + (err.message ?? String(e));}function setBootState(text, isError = false) { el.sbBoot.textContent = text; document.getElementById("statusbar").classList.toggle("error", isError);}function updateStatusbar() { el.sbSelected.textContent = state.selected ? state.selected.path : "";}
// ---- tree ----// Refreshes serialize (busy/queued latch) so concurrent walks can't interleave;// a generation token drops superseded renders mid-walk. readdir is read-only, so// refreshing never feeds the fsChanged event back into itself.let renderGen = 0;let refreshBusy = false;let refreshQueued = false;let visiblePaths = new Set(); // paths rendered in the last completed render
function refreshTree() { if (refreshBusy) { refreshQueued = true; return; } refreshBusy = true; renderTree() .catch((e) => showStatus(describeError(e), true)) .finally(() => { refreshBusy = false; if (refreshQueued) { refreshQueued = false; refreshTree(); } });}
async function renderTree() { const stale = ++renderGen; const root = state.root; const rows = []; const visible = new Set([root]); // the root row always renders
// Depth-first walk, but only through EXPANDED dirs: a collapsed dir still // renders its own row (with a closed twisty) while its children stay out of // the DOM until the twisty expands it. Dir rows render whether or not they // have children, so empty directories stay visible. async function walk(dir, depth) { let entries; try { entries = await state.runtime.fs.readdir(dir); } catch (e) { if (stale === renderGen) showStatus(describeError(e), true); return; } const sorted = [...entries].sort((a, b) => a.kind === b.kind ? a.name.localeCompare(b.name) : a.kind === "dir" ? -1 : 1); for (const entry of sorted) { const childPath = dir === "/" ? "/" + entry.name : dir + "/" + entry.name; rows.push({ path: childPath, name: entry.name, kind: entry.kind, depth: depth + 1 }); visible.add(childPath); if (entry.kind === "dir" && state.expanded.has(childPath)) { await walk(childPath, depth + 1); } } }
const frag = document.createDocumentFragment(); frag.appendChild(makeRow({ path: root, name: root, kind: "dir", depth: 0 }, true)); if (state.expanded.has(root)) await walk(root, 0); if (stale !== renderGen) return; // a newer refresh superseded this walk
for (const row of rows) frag.appendChild(makeRow(row, false)); el.tree.replaceChildren(frag); visiblePaths = visible; syncSelectionAfterRender();}
function makeRow(row, isRoot) { const div = document.createElement("div"); div.className = `tree-row ${row.kind}`; div.dataset.path = row.path; div.dataset.kind = row.kind; div.setAttribute("role", "treeitem"); div.setAttribute("aria-selected", "false"); div.style.paddingLeft = `${row.depth * INDENT}px`;
// Indentation guides: one 1px vertical line per ancestor level, drawn as // stacked gradients — no extra DOM per level. if (row.depth > 0) { const lines = []; for (let i = 1; i <= row.depth; i++) { const x = i * INDENT; lines.push(`linear-gradient(90deg, transparent ${x - 1}px, var(--tree-guide) ${x - 1}px, var(--tree-guide) ${x}px, transparent ${x}px)`); } div.style.backgroundImage = lines.join(","); }
// Twisty: ▸ closed, rotated to ▾ when open. Files get an invisible spacer // so their icons align under the folders'. const twisty = document.createElement("span"); twisty.className = "twisty"; if (row.kind === "dir") { const open = state.expanded.has(row.path); twisty.classList.toggle("open", open); twisty.textContent = "▸"; twisty.title = open ? "Collapse folder" : "Expand folder"; twisty.addEventListener("click", (e) => { e.stopPropagation(); toggleDir(row.path); }); div.setAttribute("aria-expanded", String(open)); } else { twisty.classList.add("empty"); } div.appendChild(twisty);
const icon = document.createElement("span"); icon.className = row.kind === "dir" ? "row-icon icon-folder" : `row-icon dot ${extClass(row.name)}`; icon.setAttribute("aria-hidden", "true"); div.appendChild(icon);
const label = document.createElement("span"); label.className = "tree-label"; label.textContent = isRoot ? row.path : row.name; div.appendChild(label);
div.title = row.kind === "dir" ? `${row.path} (directory)` : row.path; div.addEventListener("click", () => select({ path: row.path, kind: row.kind })); div.addEventListener("dblclick", () => { if (row.kind === "dir") toggleDir(row.path); }); div.addEventListener("contextmenu", (e) => { e.preventDefault(); openContextMenu({ path: row.path, kind: row.kind }, e.clientX, e.clientY); }); return div;}
// Collapse/expand one folder and re-render; the Set keeps the choice stable// across every later onFsChanged re-render.function toggleDir(path) { if (state.expanded.has(path)) state.expanded.delete(path); else state.expanded.add(path); refreshTree();}
// The tree re-renders on every fs change. If the selection's row vanished from// the render, either it was deleted/renamed away (clear the editor — never// edit a ghost) or an ancestor folder is simply collapsed (keep everything;// the row is hidden, not gone).function syncSelectionAfterRender() { const sel = state.selected; if (!sel) return; const row = [...el.tree.children].find((r) => r.dataset.path === sel.path); if (row) { row.classList.add("selected"); row.setAttribute("aria-selected", "true"); return; } if (!hiddenByCollapse(sel.path)) select(null);}
// True when `path` exists but its row is hidden because some ancestor folder// is collapsed. Walk from the parent upward: a rendered-but-collapsed ancestor// explains the hiding; a rendered-and-expanded one passes; an unrendered one// delegates to ITS ancestor. Reaching the tree root means nothing hides it.function hiddenByCollapse(path) { for (let p = dirnameOf(path); p !== "/" && p !== path; p = dirnameOf(p)) { if (p === state.root) return !state.expanded.has(p); if (visiblePaths.has(p) && !state.expanded.has(p)) return true; } return false;}
// ---- selection + editor ----let openGen = 0; // stale-load guard: only the newest open paints the editor
// Highlight + status bar only (no editor side effects) — used by right-click,// which must not open tabs.function setSelection(sel) { state.selected = sel; for (const row of el.tree.children) { const on = !!sel && row.dataset.path === sel.path; row.classList.toggle("selected", on); row.setAttribute("aria-selected", String(on)); } updateStatusbar();}
function select(sel) { hideInline(); hideConfirm(); setSelection(sel); if (sel?.kind === "file") { openFile(sel.path); return; } // Dirs (and clearing the selection) only blank the editor when no tab is // open — like VS Code, clicking a folder never disturbs the open editor. if (!state.activePath) showEditorPlaceholder(sel?.kind === "dir" ? sel.path : undefined);}
function showEditorPlaceholder(dirPath) { el.editorBody.hidden = true; el.gutter.hidden = false; el.content.hidden = false; el.hlWrap.hidden = true; el.editorBody.classList.remove("hl-on"); el.fileNote.hidden = true; el.editorEmpty.hidden = false; el.emptyTitle.textContent = dirPath ? `${dirPath}/` : "no editor open"; el.btnSave.disabled = true; el.btnEditorDelete.disabled = true;}
// Clicking a tree file opens OR reuses its tab (buffer preserved).async function openFile(path) { if (state.tabs.has(path)) { activateTab(path); return; } const token = ++openGen; try { const bytes = await state.runtime.fs.readFile(path); let tab; try { const text = utf8.decode(bytes); // fatal: invalid UTF-8 → binary tab, not garbage tab = { saved: text, buffer: text, binary: false, bytes: bytes.length }; } catch { tab = { saved: "", buffer: "", binary: true, bytes: bytes.length }; } state.tabs.set(path, tab); renderTabs(); // Only the newest request may repoint the editor; a slower older read // still lands its tab in the bar for the user to click. if (token === openGen) activateTab(path); } catch (e) { if (token !== openGen) return; el.fileNote.textContent = describeError(e); el.fileNote.hidden = false; showStatus(describeError(e), true); }}
function activateTab(path) { const prev = state.activePath; const prevTab = prev ? state.tabs.get(prev) : undefined; // Belt and braces: the input handler keeps the buffer synced; this covers // programmatic value changes too. Binary tabs have no buffer to stash. if (prevTab && prev !== path && !prevTab.binary) { prevTab.buffer = el.content.value; } const tab = state.tabs.get(path); if (!tab) return; state.activePath = path; renderTabs(); el.editorEmpty.hidden = true; el.editorBody.hidden = false; el.fileNote.hidden = true; el.content.disabled = tab.binary; el.btnSave.disabled = tab.binary; el.btnEditorDelete.disabled = false; el.content.value = tab.binary ? "" : tab.buffer; if (tab.binary) { el.fileNote.textContent = `(binary, ${tab.bytes} bytes) — not editable here; Delete and Rename still work`; el.fileNote.hidden = false; } updateGutter(); syncMirror(); el.content.scrollTop = 0; el.hlWrap.scrollTop = 0; el.hlWrap.scrollLeft = 0; el.gutterInner.style.transform = "translateY(0px)";}
function isDirty(tab) { return !tab.binary && tab.buffer !== tab.saved;}
function renderTabs() { const frag = document.createDocumentFragment(); for (const [path, tab] of state.tabs) { const t = document.createElement("div"); t.className = "tab"; t.dataset.path = path; t.setAttribute("role", "tab"); const active = path === state.activePath; const dirty = isDirty(tab); t.classList.toggle("active", active); t.classList.toggle("dirty", dirty); t.setAttribute("aria-selected", String(active)); t.dataset.dirty = String(dirty); t.title = dirty ? `${path} — unsaved changes` : path;
const label = document.createElement("span"); label.className = "tab-label"; label.textContent = basenameOf(path); t.appendChild(label);
const dot = document.createElement("span"); dot.className = "tab-dirty-dot"; dot.title = "unsaved changes"; t.appendChild(dot);
const close = document.createElement("button"); close.className = "tab-close"; close.textContent = "✕"; close.setAttribute("aria-label", `Close ${basenameOf(path)}`); close.title = "Close"; close.addEventListener("click", (e) => { e.stopPropagation(); closeTab(path); }); t.appendChild(close);
t.addEventListener("click", () => { if (state.activePath !== path) select({ path, kind: "file" }); }); frag.appendChild(t); } el.tabs.replaceChildren(frag);}
// Dirty flags change on every keystroke/save — update the existing tabs in// place instead of rebuilding the bar.function syncDirtyUI() { for (const t of el.tabs.children) { const tab = state.tabs.get(t.dataset.path); if (!tab) continue; const dirty = isDirty(tab); t.classList.toggle("dirty", dirty); t.dataset.dirty = String(dirty); t.title = dirty ? `${t.dataset.path} — unsaved changes` : t.dataset.path; }}
// Close a tab. Closing the ACTIVE tab selects its neighbor (the tab to the// right, else the last tab — VS Code's rule) and moves the editor + tree// highlight with it. Closing discards that tab's unsaved edits; the fs copy// is untouched. Returns the neighbor path (or null).function closeTab(path) { const order = [...state.tabs.keys()]; const idx = order.indexOf(path); const neighbor = order[idx + 1] ?? order[idx - 1] ?? null; state.tabs.delete(path); if (state.activePath === path) { state.activePath = null; if (neighbor) { activateTab(neighbor); setSelection({ path: neighbor, kind: "file" }); } else { showEditorPlaceholder(); } } renderTabs(); return neighbor;}
// ---- gutter + highlight mirror ----function updateGutter() { const lines = Math.max(1, el.content.value.split("\n").length); let text = ""; for (let i = 1; i <= lines; i++) text += `${i}\n`; el.gutterInner.textContent = text;}
// Sync the microlighter mirror behind #content: copy the text, point// data-language at the active tab's grammar, and re-highlight on the next// frame (single rAF latch — files are small, keystrokes are bursty). The// bare highlightAll export is async (grammar loads resolve inside the// bundle); calling it after every sync is the integration contract.let hlQueued = false;function syncMirror() { const path = state.activePath; const tab = path ? state.tabs.get(path) : null; const lang = tab && !tab.binary ? langFor(path) : null; const on = !!lang; // .txt/binary/unknown = plain el.hlWrap.hidden = !on; el.editorBody.classList.toggle("hl-on", on); if (!on) { el.hlMirror.textContent = ""; return; } el.hlMirror.dataset.language = lang; el.hlMirror.textContent = el.content.value; el.hlWrap.scrollTop = el.content.scrollTop; el.hlWrap.scrollLeft = el.content.scrollLeft; if (!hlQueued) { hlQueued = true; requestAnimationFrame(() => { hlQueued = false; try { highlightAll(); } catch (e) { console.error(e); } }); }}
// ---- save / delete (tab-bar actions; they act on the ACTIVE tab) ----async function saveFile() { const path = state.activePath; const tab = state.tabs.get(path); if (!tab || tab.binary) return; tab.buffer = el.content.value; try { await state.runtime.fs.writeFile(path, tab.buffer); tab.saved = tab.buffer; syncDirtyUI(); // the dirty dot goes away showStatus(`saved ${path} (${tab.buffer.length} bytes)`); } catch (e) { showStatus(describeError(e), true); }}
// Delete acts on the ACTIVE tab's file. Directory deletion lives in the// tree's context menu, which owns the recursive confirm flow.async function deleteActiveFile() { const path = state.activePath; if (!path) return; await deletePath({ path, kind: "file" });}
// files rm immediately; dirs confirm inline, then rm recursive.async function deletePath(target) { if (!target) return; if (target.kind === "dir") { hideInline(); state.confirmTarget = target; el.confirmText.textContent = `delete ${target.path} and everything under it?`; el.confirmRow.hidden = false; el.confirmYes.focus(); return; } try { await state.runtime.fs.rm(target.path); // file: plain unlink under the hood const neighbor = closeTab(target.path); if (state.selected?.path === target.path && !neighbor) select(null); showStatus(`deleted ${target.path}`); } catch (e) { showStatus(describeError(e), true); }}
function hideConfirm() { state.confirmTarget = null; el.confirmRow.hidden = true; el.confirmText.textContent = "";}
async function commitConfirm() { const target = state.confirmTarget; hideConfirm(); if (!target) return; try { await state.runtime.fs.rm(target.path, { recursive: true }); // Close any tabs the recursive delete emptied (the dir itself has no tab). const wasSelected = (sel) => !!sel && (sel.path === target.path || sel.path.startsWith(target.path + "/")); const hadSelection = wasSelected(state.selected); for (const p of [...state.tabs.keys()]) { if (p === target.path || p.startsWith(target.path + "/")) closeTab(p); } if (hadSelection) select(null); showStatus(`deleted ${target.path}/ (recursive)`); } catch (e) { showStatus(describeError(e), true); }}
// ---- inline create/rename flow (no window.prompt) ----// The target comes from the context menu (or the selection): New File/Folder// create inside a targeted dir or a targeted file's parent; Rename renames// the targeted row. A bare name joins the target dir; an absolute path is// used as given (that is how "/app/nope/deep.txt" can fail honestly with// ENOENT — writeFile does not create parent dirs, like Node).function openInline(mode, target = state.selected) { hideConfirm(); state.inlineMode = mode; state.inlineTarget = target; el.inlineRow.hidden = false; if (mode === "rename") { el.inlineLabel.textContent = `rename ${target?.path} →`; el.inlineInput.value = basenameOf(target?.path ?? ""); // pre-filled with the current name } else { const dir = target ? (target.kind === "dir" ? target.path : dirnameOf(target.path)) : state.root; el.inlineLabel.textContent = mode === "new-file" ? `new file in ${dir}:` : `new folder in ${dir}:`; el.inlineInput.value = ""; } el.inlineOk.textContent = mode === "rename" ? "Rename" : "Create"; el.inlineInput.focus(); el.inlineInput.select();}
function hideInline() { state.inlineMode = null; state.inlineTarget = null; el.inlineRow.hidden = true; el.inlineInput.value = "";}
function resolveInput(raw) { const dir = state.inlineTarget ? (state.inlineTarget.kind === "dir" ? state.inlineTarget.path : dirnameOf(state.inlineTarget.path)) : state.root; return raw.startsWith("/") ? raw : joinPath(dir, raw);}
async function commitInline() { const mode = state.inlineMode; const target = state.inlineTarget; const raw = el.inlineInput.value.trim(); if (!mode || raw === "") return; const fs = state.runtime.fs; if (mode === "rename") { if (!target) return; const to = raw.startsWith("/") ? raw : joinPath(dirnameOf(target.path), raw); try { await fs.rename(target.path, to); // Retarget an open tab instead of closing it: unsaved edits survive. const tab = state.tabs.get(target.path); if (tab) { state.tabs.delete(target.path); state.tabs.set(to, tab); } showStatus(`renamed ${target.path} → ${to}`); hideInline(); select({ path: to, kind: target.kind }); // re-open under the new path } catch (e) { showStatus(describeError(e), true); } return; } const path = resolveInput(raw); try { if (mode === "new-file") { await fs.writeFile(path, ""); showStatus(`created ${path}`); hideInline(); select({ path, kind: "file" }); // auto-open for typing } else { await fs.mkdir(path, { recursive: true }); showStatus(`created ${path}/`); hideInline(); select({ path, kind: "dir" }); // starts collapsed, like VS Code's new folders } } catch (e) { // The inline row stays open so the name can be corrected; the code shows in the status line. showStatus(describeError(e), true); }}
// ---- tree context menu ----// Position at the cursor, clamped to the viewport; dismiss on click-away and// Escape (keyboard: Shift+F10 on a focused row also fires contextmenu).function openContextMenu(target, x, y) { if (!target) return; state.contextTarget = target; setSelection(target); // highlight the row, but never open it from a right-click el.contextMenu.hidden = false; const rect = el.contextMenu.getBoundingClientRect(); el.contextMenu.style.left = `${Math.max(4, Math.min(x, window.innerWidth - rect.width - 4))}px`; el.contextMenu.style.top = `${Math.max(4, Math.min(y, window.innerHeight - rect.height - 4))}px`;}
function hideContextMenu() { el.contextMenu.hidden = true; state.contextTarget = null;}
async function copyPath(target) { if (!target) return; try { await navigator.clipboard.writeText(target.path); showStatus(`copied ${target.path}`); } catch { showStatus(`clipboard unavailable — ${target.path}`, true); }}
// ---- activity bar: view toggles ----// btn toggles a view: isVisible() reads the current state, apply() writes the// flipped state; aria-pressed and the active indicator follow.function wireViewToggle(btn, isVisible, apply) { btn.addEventListener("click", () => { const show = !isVisible(); apply(show); btn.setAttribute("aria-pressed", String(show)); btn.classList.toggle("active", show); });}
// ---- guest runner ----// NOTE: the Kernel API has no kill, so there is no Stop button — a started// guest runs until it exits or the tab closes (an infinite-loop guest keeps// the badge saying "running…"; that is shown honestly rather than faked).// Starting a new run supersedes the old one in the log pane; the old process// keeps running underneath and its output is dropped from the display.let runSeq = 0;
function setExit(text, running) { el.exit.textContent = text; el.exit.classList.toggle("running", running); el.sbExit.textContent = text; // the status bar mirrors the panel badge}
function runGuest() { if (!state.runtime) return; // boot failed — nothing to exec with const entry = el.entry.value.trim(); if (!entry) return; const id = ++runSeq; el.stdout.replaceChildren(); el.stderr.replaceChildren(); setExit("running…", true); const proc = state.runtime.exec(entry); const soDec = new TextDecoder(); const seDec = new TextDecoder(); const scroll = () => { el.outputLog.scrollTop = el.outputLog.scrollHeight; }; const pipe = (stream, sink, dec) => stream.pipeTo(new WritableStream({ write(chunk) { if (id === runSeq) { sink.textContent += dec.decode(chunk, { stream: true }); scroll(); // auto-scroll to the newest line } }, })); pipe(proc.stdout, el.stdout, soDec); pipe(proc.stderr, el.stderr, seDec); proc.exited.then((code) => { if (id === runSeq) { setExit(String(code), false); scroll(); } });}
// ---- wiring ----el.btnSave.addEventListener("click", saveFile);el.btnEditorDelete.addEventListener("click", deleteActiveFile);el.inlineOk.addEventListener("click", commitInline);el.inlineCancel.addEventListener("click", hideInline);el.inlineInput.addEventListener("keydown", (e) => { if (e.key === "Enter") commitInline(); else if (e.key === "Escape") hideInline();});el.confirmYes.addEventListener("click", commitConfirm);el.confirmNo.addEventListener("click", hideConfirm);el.btnRun.addEventListener("click", runGuest);el.entry.addEventListener("keydown", (e) => { if (e.key === "Enter") runGuest(); });
// Editor: keystrokes sync the active tab's buffer + dirty dot + gutter +// highlight mirror; scrolling mirrors the gutter (transform) and the mirror// (its own scrollTop/scrollLeft, to match native selection rendering).el.content.addEventListener("input", () => { const tab = state.tabs.get(state.activePath); if (!tab || tab.binary) return; tab.buffer = el.content.value; syncDirtyUI(); updateGutter(); syncMirror();});el.content.addEventListener("scroll", () => { el.hlWrap.scrollTop = el.content.scrollTop; el.hlWrap.scrollLeft = el.content.scrollLeft; el.gutterInner.style.transform = `translateY(${-el.content.scrollTop}px)`;});
// Context menu items act on the row they were opened for.$("ctx-new-file").addEventListener("click", () => { const t = state.contextTarget; hideContextMenu(); openInline("new-file", t); });$("ctx-new-folder").addEventListener("click", () => { const t = state.contextTarget; hideContextMenu(); openInline("new-folder", t); });$("ctx-rename").addEventListener("click", () => { const t = state.contextTarget; hideContextMenu(); if (t) openInline("rename", t); });$("ctx-delete").addEventListener("click", () => { const t = state.contextTarget; hideContextMenu(); deletePath(t); });$("ctx-copy-path").addEventListener("click", () => { const t = state.contextTarget; hideContextMenu(); copyPath(t); });document.addEventListener("click", (e) => { if (!el.contextMenu.hidden && !el.contextMenu.contains(e.target)) hideContextMenu();});document.addEventListener("keydown", (e) => { if (e.key !== "Escape") return; if (!el.contextMenu.hidden) hideContextMenu(); else if (!el.confirmRow.hidden) hideConfirm();});
// Activity bar: Explorer toggles the sidebar, Output toggles the bottom panel.wireViewToggle(el.btnViewExplorer, () => !el.sidebar.hidden, (show) => { el.sidebar.hidden = !show; el.app.classList.toggle("sidebar-hidden", !show);});wireViewToggle(el.btnViewOutput, () => !el.output.hidden, (show) => { el.output.hidden = !show;});
// ---- boot + seed ----try { const runtime = await boot(); state.runtime = runtime; // Deliberate debug/test hook: the Kernel on window for console poking and as // a test fallback where UI automation is impractical. The harness tests drive // the real UI; nothing in them needs this. window.__runtime = runtime;
// Seed the standard demo tree (same files as demo/index.js, fetched the same // way), plus harness extras: two demo guests and notes.md. writeTree cannot // express empty dirs, so /app/scratch is created through the host fs — an // awaited op that lands after the seed message (same worker queue, in order). const read = async (p) => await (await fetch(p)).text(); runtime.writeTree({ "/app/main.cjs": await read("/demo/app/main.cjs"), "/app/greet.js": await read("/demo/app/greet.js"), "/app/name.txt": await read("/demo/app/name.txt"), "/app/node_modules/leftpad/package.json": await read("/demo/app/node_modules/leftpad/package.json"), "/app/node_modules/leftpad/index.js": await read("/demo/app/node_modules/leftpad/index.js"), "/app/node_modules/shouty/package.json": await read("/demo/app/node_modules/shouty/package.json"), "/app/node_modules/shouty/lib/loud.js": await read("/demo/app/node_modules/shouty/lib/loud.js"), "/app/notes.md": "# scratch\n", "/app/echo.cjs": [ "// Guest demo: prints the current bytes of /app/hello.txt.", "// Create /app/hello.txt in the editor, then Run this — the guest reads", "// what the page wrote.", `const fs = require("node:fs");`, `console.log(fs.readFileSync("/app/hello.txt", "utf8"));`, ].join("\n"), "/app/writer.cjs": [ "// Guest demo: writes a file the page's tree should pick up on its own,", "// via onFsChanged — no manual refresh needed.", `const fs = require("node:fs");`, `fs.writeFileSync("/app/scratch/from-guest.txt", "written by writer.cjs\\n");`, `console.log("wrote /app/scratch/from-guest.txt");`, ].join("\n"), }); await runtime.fs.mkdir("/app/scratch");
// Default expansion, VS Code-calm: the root and its first-level dirs start // expanded, except node_modules which starts collapsed so the default view // stays quiet. Anything created later is not in the set → starts collapsed. state.expanded.add(state.root); try { const entries = await runtime.fs.readdir(state.root); for (const entry of entries) { if (entry.kind === "dir" && entry.name !== "node_modules") { state.expanded.add(joinPath(state.root, entry.name)); } } } catch { // Root unreadable → the refresh below surfaces the error honestly. }
// Any mutation from any writer (host fs ops, guest syscalls, seed) lands here; // the host coalesces ~25 ms so a burst renders the tree once. Attached after // the expansion seed so the first render already has its final shape. runtime.onFsChanged(refreshTree); await refreshTree(); setBootState(`VFS ready (root ${state.root})`); showStatus(`VFS ready (root ${state.root})`);} catch (e) { // boot() refuses without cross-origin isolation (IsolationError) — show it, don't hide it. const err = e ?? {}; setBootState(err.name ?? "boot failed", true); showStatus("BOOT FAILED: " + describeError(e), true); console.error(e);}