╭ script.js ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const grid = document.getElementById("grid"); 2 const overlay = document.getElementById("overlay"); 3 const pageJsonBase64 = document.getElementById("page-data").textContent; 4 5 let wasmInstance; 6 const decoder = new TextDecoder(); 7 const encoder = new TextEncoder(); 8 let currentHtml = ""; 9 // seeded from the server-rendered overlay so the first wasm tick can no-op 10 // when its layout happens to match the server's. otherwise the first tick 11 // always rebuilds and any pre-load focus state is lost. 12 let currentOverlay = overlay.innerHTML; 13 14 const MIN_COLS = 30; 15 16 // measured once after the font is loaded. recomputed lazily if either reads 17 // back as zero (e.g. measured before the font was actually ready). 18 let cellWidth = null; 19 let cellHeight = null; 20 21 function measureCell() { 22 const probe = document.createElement("span"); 23 probe.style.position = "absolute"; 24 probe.style.visibility = "hidden"; 25 probe.style.whiteSpace = "pre"; 26 probe.textContent = "X".repeat(100); 27 grid.appendChild(probe); 28 const rect = probe.getBoundingClientRect(); 29 probe.remove(); 30 cellWidth = rect.width / 100; 31 cellHeight = rect.height; 32 } 33 34 function maxCols() { 35 if (!cellWidth) measureCell(); 36 return Math.max(MIN_COLS, Math.floor(document.body.clientWidth / cellWidth)); 37 } 38 39 // minimum row count for the wasm build — the TUI fills at least the 40 // viewport height, longer content extends past it and the browser scrolls. 41 function minRows() { 42 if (!cellHeight) measureCell(); 43 return Math.max(1, Math.floor(document.documentElement.clientHeight / cellHeight)); 44 } 45 46 function readWasmString(ptr, len) { 47 const memory = wasmInstance.exports.memory; 48 return decoder.decode(new Uint8Array(memory.buffer, ptr, len)); 49 } 50 51 const importObject = { 52 env: { 53 _consoleLog: function (ptr, len) { 54 console.log(readWasmString(ptr, len)); 55 }, 56 _setHtml: function (ptr, len) { 57 const html = readWasmString(ptr, len); 58 if (html === currentHtml) return; 59 currentHtml = html; 60 // the grid only holds non-focusable TUI cell spans now; the 61 // form (inputs + submit button) lives in #overlay and is 62 // never touched by this wipe, so we don't need to save and 63 // restore focus across the swap. 64 grid.innerHTML = html; 65 }, 66 _pushState: function (ptr, len) { 67 const url = readWasmString(ptr, len); 68 // idempotent: wasm tells us its current page every tick after a 69 // change, but we don't want to add history entries for a URL 70 // the browser is already on (e.g., right after the page loaded 71 // from a server-side render of the same route). 72 if (window.location.pathname !== url) { 73 history.pushState({}, "", url); 74 } 75 }, 76 _setOverlay: function (ptr, len) { 77 const html = readWasmString(ptr, len); 78 // diff against the previous overlay HTML; an unchanged overlay 79 // means no layout/structure has shifted (typing alone doesn't 80 // produce a diff because we deliberately omit the `value` 81 // attribute on inputs — the browser tracks that). skipping the 82 // innerHTML assignment keeps the live <form> alive across the 83 // mousedown→focusin→tick→click sequence, which is what lets 84 // the very first click on the submit button actually submit. 85 if (html === currentOverlay) return; 86 currentOverlay = html; 87 overlay.innerHTML = html; 88 }, 89 _focusInput: function (id) { 90 const target = overlay.querySelector(`[data-focus-id="${id}"]`); 91 if (target && document.activeElement !== target) target.focus(); 92 }, 93 _navigate: function (ptr, len) { 94 // a real browser navigation to another top-level page (the wasm 95 // can't render it client-side without server data). 96 window.location.assign(readWasmString(ptr, len)); 97 }, 98 }, 99 }; 100 101 function sendTextInputValue(focusId, value) { 102 const bytes = encoder.encode(value); 103 const ptr = wasmInstance.exports._alloc(bytes.length); 104 new Uint8Array(wasmInstance.exports.memory.buffer, ptr, bytes.length).set(bytes); 105 wasmInstance.exports._setTextInputValue(focusId, ptr, bytes.length); 106 wasmInstance.exports._tick(minRows(), maxCols()); 107 } 108 109 function sendEnter(form) { 110 const btn = form.querySelector("button[type=submit][data-focus-id]"); 111 if (!btn) return; 112 wasmInstance.exports._onMouseClick(Number(btn.dataset.focusId)); 113 wasmInstance.exports._onKeyDown(13); 114 wasmInstance.exports._tick(minRows(), maxCols()); 115 } 116 117 WebAssembly.instantiateStreaming(fetch("/haxy.wasm"), importObject).then(async (result) => { 118 wasmInstance = result.instance; 119 120 // wait for the @font-face to load before measuring cell width, otherwise 121 // we get the fallback font's metrics. 122 if (document.fonts && document.fonts.ready) { 123 await document.fonts.ready; 124 } 125 126 // the page is embedded as base64 so it can sit inside the host html 127 // without worrying about characters that would terminate the script tag. 128 // decode here and hand the raw json bytes to the wasm. 129 const jsonBytes = Uint8Array.from(atob(pageJsonBase64), (c) => c.charCodeAt(0)); 130 const ptr = wasmInstance.exports._alloc(jsonBytes.length); 131 new Uint8Array(wasmInstance.exports.memory.buffer, ptr, jsonBytes.length).set(jsonBytes); 132 wasmInstance.exports._init(ptr, jsonBytes.length, minRows(), maxCols()); 133 134 document.addEventListener("keydown", (event) => { 135 // let the browser handle modifier combos. the TUI only uses unmodified keys, 136 // so intercepting these would just break normal browser navigation. 137 if (event.altKey || event.ctrlKey || event.metaKey) return; 138 // when a form element (text input or submit button) owns focus, 139 // the browser handles typing, Enter-to-submit, and Tab natively. 140 // we only forward keys into the TUI when focus is elsewhere. 141 // exception: arrow up/down on an input unfocuses it and forwards 142 // the event so the TUI can move focus between widgets. 143 if (document.activeElement) { 144 const tag = document.activeElement.tagName; 145 const isArrow = event.key === "ArrowUp" || event.key === "ArrowDown" || 146 event.key === "ArrowLeft" || event.key === "ArrowRight"; 147 if (tag === "INPUT" && (event.key === "ArrowUp" || event.key === "ArrowDown")) { 148 // up/down moves between widgets; left/right stay in the input 149 document.activeElement.blur(); 150 } else if (tag === "BUTTON" && isArrow) { 151 // arrows navigate away from a focused submit button 152 document.activeElement.blur(); 153 } else if (tag === "INPUT" || tag === "BUTTON") { 154 // Enter (submit), typing, Tab — handled natively by the browser 155 return; 156 } 157 } 158 if (["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "PageUp", "PageDown", "Home", "End"].includes(event.key)) { 159 event.preventDefault(); 160 } 161 wasmInstance.exports._onKeyDown(event.keyCode); 162 wasmInstance.exports._tick(minRows(), maxCols()); 163 }); 164 165 // listeners on document (not #grid) since the form lives outside #grid; 166 // input/focus events from form elements still bubble up to document. 167 document.addEventListener("input", (event) => { 168 const t = event.target; 169 if (!t || t.tagName !== "INPUT" || !t.dataset.focusId) return; 170 sendTextInputValue(Number(t.dataset.focusId), t.value); 171 }); 172 173 document.addEventListener("focusin", (event) => { 174 const t = event.target; 175 if (!t || !t.dataset || !t.dataset.focusId) return; 176 wasmInstance.exports._onMouseClick(Number(t.dataset.focusId)); 177 wasmInstance.exports._tick(minRows(), maxCols()); 178 }); 179 180 grid.addEventListener("click", (event) => { 181 const span = event.target.closest(".clickable"); 182 if (!span) return; 183 const focusId = Number(span.dataset.focusId); 184 wasmInstance.exports._onMouseClick(focusId); 185 wasmInstance.exports._tick(minRows(), maxCols()); 186 }); 187 188 let resizeTimer = null; 189 window.addEventListener("resize", () => { 190 clearTimeout(resizeTimer); 191 resizeTimer = setTimeout(() => { 192 wasmInstance.exports._tick(minRows(), maxCols()); 193 }, 100); 194 }); 195 }); 196