╭ script.js ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const grid = document.getElementById("grid"); 2 const overlay = document.getElementById("overlay"); 3 const pageJson = document.getElementById("page-data").textContent; 4 5 let wasmInstance; 6 const decoder = new TextDecoder(); 7 const encoder = new TextEncoder(); 8 let currentHtml = ""; 9 // each scroll div's wasm-side offset (in cells) as of the last render, keyed by 10 // scroll id. when a new render's offset differs, the wasm moved the scroll on 11 // purpose and its offset is applied; otherwise the browser position (the user's 12 // scrolling) is preserved. 13 const wasmOffsets = {}; 14 // seeded from the server-rendered overlay so the first wasm tick can no-op 15 // when its layout happens to match the server's. otherwise the first tick 16 // always rebuilds and any pre-load focus state is lost. 17 let currentOverlay = overlay.innerHTML; 18 19 const MIN_COLS = 30; 20 21 // measured once after the font is loaded. recomputed lazily if either reads 22 // back as zero (e.g. measured before the font was actually ready). 23 let cellWidth = null; 24 let cellHeight = null; 25 26 function measureCell() { 27 const probe = document.createElement("span"); 28 probe.style.position = "absolute"; 29 probe.style.visibility = "hidden"; 30 probe.style.whiteSpace = "pre"; 31 probe.textContent = "X".repeat(100); 32 grid.appendChild(probe); 33 const rect = probe.getBoundingClientRect(); 34 probe.remove(); 35 cellWidth = rect.width / 100; 36 cellHeight = rect.height; 37 } 38 39 function maxCols() { 40 if (!cellWidth) measureCell(); 41 return Math.max(MIN_COLS, Math.floor(document.body.clientWidth / cellWidth)); 42 } 43 44 // minimum row count for the wasm build — the TUI fills at least the 45 // viewport height, longer content extends past it and the browser scrolls. 46 function minRows() { 47 if (!cellHeight) measureCell(); 48 return Math.max(1, Math.floor(document.documentElement.clientHeight / cellHeight)); 49 } 50 51 function readWasmString(ptr, len) { 52 const memory = wasmInstance.exports.memory; 53 return decoder.decode(new Uint8Array(memory.buffer, ptr, len)); 54 } 55 56 const importObject = { 57 env: { 58 _consoleLog: function (ptr, len) { 59 console.log(readWasmString(ptr, len)); 60 }, 61 _setHtml: function (ptr, len) { 62 const html = readWasmString(ptr, len); 63 if (html === currentHtml) return; 64 currentHtml = html; 65 // each web-native Scroll renders as a .scroll div; replacing 66 // innerHTML recreates them and would reset their scroll position 67 // every tick, so snapshot scrollTop/Left by their stable id and 68 // restore it after the swap. (mouse-wheel scrolling happens with no 69 // tick, so it isn't affected.) 70 const positions = {}; 71 for (const el of grid.querySelectorAll(".scroll[data-scroll-id]")) { 72 positions[el.dataset.scrollId] = { top: el.scrollTop, left: el.scrollLeft }; 73 } 74 grid.innerHTML = html; 75 for (const el of grid.querySelectorAll(".scroll[data-scroll-id]")) { 76 const id = el.dataset.scrollId; 77 const offset = { top: Number(el.dataset.scrollY || 0), left: Number(el.dataset.scrollX || 0) }; 78 const prev = wasmOffsets[id]; 79 const p = positions[id]; 80 if (p && prev && prev.top === offset.top && prev.left === offset.left) { 81 el.scrollTop = p.top; 82 el.scrollLeft = p.left; 83 } else { 84 // the wasm's offset changed (or this div is new — a fresh 85 // page load or a bumped content version): apply it, 86 // converted from cells to pixels. 87 if (!cellWidth || !cellHeight) measureCell(); 88 el.scrollTop = offset.top * cellHeight; 89 el.scrollLeft = offset.left * cellWidth; 90 } 91 wasmOffsets[id] = offset; 92 } 93 }, 94 _replaceState: function (ptr, len) { 95 const url = readWasmString(ptr, len); 96 // passive same-page URL changes. replaceState changes the URL 97 // without adding a history entry, so the back button isn't 98 // cluttered with unnecessary entries. 99 if (window.location.pathname !== url) { 100 history.replaceState({}, "", url); 101 } 102 }, 103 _setOverlay: function (ptr, len) { 104 const html = readWasmString(ptr, len); 105 // diff against the previous overlay HTML; an unchanged overlay 106 // means no layout/structure has shifted (typing alone doesn't 107 // produce a diff because we deliberately omit the `value` 108 // attribute on inputs — the browser tracks that). skipping the 109 // innerHTML assignment keeps the live <form> alive across the 110 // mousedown→focusin→tick→click sequence, which is what lets 111 // the very first click on the submit button actually submit. 112 if (html === currentOverlay) return; 113 currentOverlay = html; 114 overlay.innerHTML = html; 115 }, 116 _focusInput: function (id) { 117 const target = overlay.querySelector(`[data-focus-id="${id}"]`); 118 if (target && document.activeElement !== target) target.focus(); 119 }, 120 _navigate: function (ptr, len) { 121 // a real browser navigation to another top-level page (the wasm 122 // can't render it client-side without server data). 123 window.location.assign(readWasmString(ptr, len)); 124 }, 125 _scrollToFocus: function (id) { 126 // bring the focused widget into view within its own .scroll div. it's 127 // several spans (one per row) sharing this id, in top-to-bottom order, 128 // so the first gives its top/left edge and the last its bottom. 129 const els = grid.querySelectorAll(`[data-focus-id="${id}"]`); 130 if (els.length === 0) return; 131 const container = els[0].closest(".scroll"); 132 if (!container) return; 133 134 const c = container.getBoundingClientRect(); 135 const first = els[0].getBoundingClientRect(); 136 const last = els[els.length - 1].getBoundingClientRect(); 137 const top = first.top - c.top + container.scrollTop; 138 const bottom = last.bottom - c.top + container.scrollTop; 139 const left = first.left - c.left + container.scrollLeft; 140 141 // vertical is the priority axis: fit the widget, preferring its top 142 // when it's taller than the viewport. 143 if (top < container.scrollTop || bottom - top > container.clientHeight) { 144 container.scrollTop = top; 145 } else if (bottom > container.scrollTop + container.clientHeight) { 146 container.scrollTop = bottom - container.clientHeight; 147 } 148 // horizontal: only reveal the row's start, never chase the right edge, 149 // so moving down through varying-width rows doesn't yank the view 150 // sideways. (a hidden-overflow x axis stays at 0, so this no-ops.) 151 if (left < container.scrollLeft) container.scrollLeft = left; 152 }, 153 }, 154 }; 155 156 function sendTextInputValue(focusId, value) { 157 const bytes = encoder.encode(value); 158 const ptr = wasmInstance.exports._alloc(bytes.length); 159 new Uint8Array(wasmInstance.exports.memory.buffer, ptr, bytes.length).set(bytes); 160 wasmInstance.exports._setTextInputValue(focusId, ptr, bytes.length); 161 wasmInstance.exports._tick(minRows(), maxCols()); 162 } 163 164 function sendEnter(form) { 165 const btn = form.querySelector("button[type=submit][data-focus-id]"); 166 if (!btn) return; 167 wasmInstance.exports._onMouseClick(Number(btn.dataset.focusId)); 168 wasmInstance.exports._onKeyDown(13); 169 wasmInstance.exports._tick(minRows(), maxCols()); 170 } 171 172 WebAssembly.instantiateStreaming(fetch("/haxy.wasm"), importObject).then(async (result) => { 173 wasmInstance = result.instance; 174 175 // wait for the @font-face to load before measuring cell width, otherwise 176 // we get the fallback font's metrics. 177 if (document.fonts && document.fonts.ready) { 178 await document.fonts.ready; 179 } 180 181 // the page is embedded as raw json in a script tag. 182 // encode to utf-8 bytes and hand it to the wasm. 183 const jsonBytes = encoder.encode(pageJson); 184 const ptr = wasmInstance.exports._alloc(jsonBytes.length); 185 new Uint8Array(wasmInstance.exports.memory.buffer, ptr, jsonBytes.length).set(jsonBytes); 186 wasmInstance.exports._init(ptr, jsonBytes.length, minRows(), maxCols()); 187 188 document.addEventListener("keydown", (event) => { 189 // let the browser handle modifier combos. the TUI only uses unmodified keys, 190 // so intercepting these would just break normal browser navigation. 191 if (event.altKey || event.ctrlKey || event.metaKey) return; 192 // when a form element (text input or submit button) owns focus, the 193 // browser handles typing and Tab natively (and Enter on the button 194 // submits). we only forward keys into the TUI when focus is elsewhere. 195 // exception: arrow up/down on an input unfocuses it and forwards 196 // the event so the TUI can move focus between widgets. 197 if (document.activeElement) { 198 const tag = document.activeElement.tagName; 199 const isArrow = event.key === "ArrowUp" || event.key === "ArrowDown" || 200 event.key === "ArrowLeft" || event.key === "ArrowRight"; 201 if (tag === "INPUT" && event.key === "Enter") { 202 // enter in a text input never submits the form; only the 203 // submit button does 204 event.preventDefault(); 205 return; 206 } 207 if (tag === "INPUT" && (event.key === "ArrowUp" || event.key === "ArrowDown")) { 208 // up/down moves between widgets; left/right stay in the input 209 document.activeElement.blur(); 210 } else if (tag === "BUTTON" && isArrow) { 211 // arrows navigate away from a focused submit button 212 document.activeElement.blur(); 213 } else if (tag === "INPUT" || tag === "BUTTON" || tag === "TEXTAREA") { 214 // Enter (submit / newline), typing, Tab, and a textarea's 215 // arrows — handled natively by the browser 216 return; 217 } 218 } 219 if (["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "PageUp", "PageDown", "Home", "End"].includes(event.key)) { 220 event.preventDefault(); 221 } 222 wasmInstance.exports._onKeyDown(event.keyCode); 223 wasmInstance.exports._tick(minRows(), maxCols()); 224 }); 225 226 // listeners on document (not #grid) since the form lives outside #grid; 227 // input/focus events from form elements still bubble up to document. 228 document.addEventListener("input", (event) => { 229 const t = event.target; 230 if (!t || (t.tagName !== "INPUT" && t.tagName !== "TEXTAREA") || !t.dataset.focusId) return; 231 sendTextInputValue(Number(t.dataset.focusId), t.value); 232 }); 233 234 document.addEventListener("focusin", (event) => { 235 const t = event.target; 236 if (!t || !t.dataset || !t.dataset.focusId) return; 237 // sync the wasm focus to wherever the browser moved focus 238 wasmInstance.exports._setFocus(Number(t.dataset.focusId)); 239 // a click's mousedown fires this focusin before the click event. ticking 240 // here would rebuild #grid and destroy the node before its click lands, 241 // swallowing the navigation and forcing a second click — so don't 242 // re-render for a grid element. overlay controls live outside #grid and 243 // survive the diff, so they still tick. 244 if (!grid.contains(t)) wasmInstance.exports._tick(minRows(), maxCols()); 245 }); 246 247 grid.addEventListener("click", (event) => { 248 const span = event.target.closest(".clickable"); 249 if (!span) return; 250 // leave modified / non-left clicks (open-in-new-tab, etc.) to the browser 251 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; 252 // wasm routes the click: an in-page link just moves focus and re-renders, 253 // a cross-page one calls _navigate. suppress the <a>'s own navigation so 254 // an in-page link doesn't also trigger a redundant full page load. 255 event.preventDefault(); 256 const focusId = Number(span.dataset.focusId); 257 wasmInstance.exports._onMouseClick(focusId); 258 wasmInstance.exports._tick(minRows(), maxCols()); 259 }); 260 261 let resizeTimer = null; 262 window.addEventListener("resize", () => { 263 clearTimeout(resizeTimer); 264 resizeTimer = setTimeout(() => { 265 wasmInstance.exports._tick(minRows(), maxCols()); 266 }, 100); 267 }); 268 }); 269