╭ 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 // 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 // each web-native Scroll renders as a .scroll div; replacing 61 // innerHTML recreates them and would reset their scroll position 62 // every tick, so snapshot scrollTop/Left by their stable id and 63 // restore it after the swap. (mouse-wheel scrolling happens with no 64 // tick, so it isn't affected.) 65 const positions = {}; 66 for (const el of grid.querySelectorAll(".scroll[data-scroll-id]")) { 67 positions[el.dataset.scrollId] = { top: el.scrollTop, left: el.scrollLeft }; 68 } 69 grid.innerHTML = html; 70 for (const el of grid.querySelectorAll(".scroll[data-scroll-id]")) { 71 const p = positions[el.dataset.scrollId]; 72 if (p) { el.scrollTop = p.top; el.scrollLeft = p.left; } 73 } 74 }, 75 _replaceState: function (ptr, len) { 76 const url = readWasmString(ptr, len); 77 // passive same-page URL changes. replaceState changes the URL 78 // without adding a history entry, so the back button isn't 79 // cluttered with unnecessary entries. 80 if (window.location.pathname !== url) { 81 history.replaceState({}, "", url); 82 } 83 }, 84 _setOverlay: function (ptr, len) { 85 const html = readWasmString(ptr, len); 86 // diff against the previous overlay HTML; an unchanged overlay 87 // means no layout/structure has shifted (typing alone doesn't 88 // produce a diff because we deliberately omit the `value` 89 // attribute on inputs — the browser tracks that). skipping the 90 // innerHTML assignment keeps the live <form> alive across the 91 // mousedown→focusin→tick→click sequence, which is what lets 92 // the very first click on the submit button actually submit. 93 if (html === currentOverlay) return; 94 currentOverlay = html; 95 overlay.innerHTML = html; 96 }, 97 _focusInput: function (id) { 98 const target = overlay.querySelector(`[data-focus-id="${id}"]`); 99 if (target && document.activeElement !== target) target.focus(); 100 }, 101 _navigate: function (ptr, len) { 102 // a real browser navigation to another top-level page (the wasm 103 // can't render it client-side without server data). 104 window.location.assign(readWasmString(ptr, len)); 105 }, 106 _scrollToFocus: function (id) { 107 // bring the focused widget into view within its own .scroll div. it's 108 // several spans (one per row) sharing this id, in top-to-bottom order, 109 // so the first gives its top/left edge and the last its bottom. 110 const els = grid.querySelectorAll(`[data-focus-id="${id}"]`); 111 if (els.length === 0) return; 112 const container = els[0].closest(".scroll"); 113 if (!container) return; 114 115 const c = container.getBoundingClientRect(); 116 const first = els[0].getBoundingClientRect(); 117 const last = els[els.length - 1].getBoundingClientRect(); 118 const top = first.top - c.top + container.scrollTop; 119 const bottom = last.bottom - c.top + container.scrollTop; 120 const left = first.left - c.left + container.scrollLeft; 121 122 // vertical is the priority axis: fit the widget, preferring its top 123 // when it's taller than the viewport. 124 if (top < container.scrollTop || bottom - top > container.clientHeight) { 125 container.scrollTop = top; 126 } else if (bottom > container.scrollTop + container.clientHeight) { 127 container.scrollTop = bottom - container.clientHeight; 128 } 129 // horizontal: only reveal the row's start, never chase the right edge, 130 // so moving down through varying-width rows doesn't yank the view 131 // sideways. (a hidden-overflow x axis stays at 0, so this no-ops.) 132 if (left < container.scrollLeft) container.scrollLeft = left; 133 }, 134 }, 135 }; 136 137 function sendTextInputValue(focusId, value) { 138 const bytes = encoder.encode(value); 139 const ptr = wasmInstance.exports._alloc(bytes.length); 140 new Uint8Array(wasmInstance.exports.memory.buffer, ptr, bytes.length).set(bytes); 141 wasmInstance.exports._setTextInputValue(focusId, ptr, bytes.length); 142 wasmInstance.exports._tick(minRows(), maxCols()); 143 } 144 145 function sendEnter(form) { 146 const btn = form.querySelector("button[type=submit][data-focus-id]"); 147 if (!btn) return; 148 wasmInstance.exports._onMouseClick(Number(btn.dataset.focusId)); 149 wasmInstance.exports._onKeyDown(13); 150 wasmInstance.exports._tick(minRows(), maxCols()); 151 } 152 153 WebAssembly.instantiateStreaming(fetch("/haxy.wasm"), importObject).then(async (result) => { 154 wasmInstance = result.instance; 155 156 // wait for the @font-face to load before measuring cell width, otherwise 157 // we get the fallback font's metrics. 158 if (document.fonts && document.fonts.ready) { 159 await document.fonts.ready; 160 } 161 162 // the page is embedded as raw json in a script tag. 163 // encode to utf-8 bytes and hand it to the wasm. 164 const jsonBytes = encoder.encode(pageJson); 165 const ptr = wasmInstance.exports._alloc(jsonBytes.length); 166 new Uint8Array(wasmInstance.exports.memory.buffer, ptr, jsonBytes.length).set(jsonBytes); 167 wasmInstance.exports._init(ptr, jsonBytes.length, minRows(), maxCols()); 168 169 document.addEventListener("keydown", (event) => { 170 // let the browser handle modifier combos. the TUI only uses unmodified keys, 171 // so intercepting these would just break normal browser navigation. 172 if (event.altKey || event.ctrlKey || event.metaKey) return; 173 // when a form element (text input or submit button) owns focus, 174 // the browser handles typing, Enter-to-submit, and Tab natively. 175 // we only forward keys into the TUI when focus is elsewhere. 176 // exception: arrow up/down on an input unfocuses it and forwards 177 // the event so the TUI can move focus between widgets. 178 if (document.activeElement) { 179 const tag = document.activeElement.tagName; 180 const isArrow = event.key === "ArrowUp" || event.key === "ArrowDown" || 181 event.key === "ArrowLeft" || event.key === "ArrowRight"; 182 if (tag === "INPUT" && (event.key === "ArrowUp" || event.key === "ArrowDown")) { 183 // up/down moves between widgets; left/right stay in the input 184 document.activeElement.blur(); 185 } else if (tag === "BUTTON" && isArrow) { 186 // arrows navigate away from a focused submit button 187 document.activeElement.blur(); 188 } else if (tag === "INPUT" || tag === "BUTTON") { 189 // Enter (submit), typing, Tab — handled natively by the browser 190 return; 191 } 192 } 193 if (["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "PageUp", "PageDown", "Home", "End"].includes(event.key)) { 194 event.preventDefault(); 195 } 196 wasmInstance.exports._onKeyDown(event.keyCode); 197 wasmInstance.exports._tick(minRows(), maxCols()); 198 }); 199 200 // listeners on document (not #grid) since the form lives outside #grid; 201 // input/focus events from form elements still bubble up to document. 202 document.addEventListener("input", (event) => { 203 const t = event.target; 204 if (!t || t.tagName !== "INPUT" || !t.dataset.focusId) return; 205 sendTextInputValue(Number(t.dataset.focusId), t.value); 206 }); 207 208 document.addEventListener("focusin", (event) => { 209 const t = event.target; 210 if (!t || !t.dataset || !t.dataset.focusId) return; 211 // sync the wasm focus to wherever the browser moved focus 212 wasmInstance.exports._setFocus(Number(t.dataset.focusId)); 213 // a click's mousedown fires this focusin before the click event. ticking 214 // here would rebuild #grid and destroy the node before its click lands, 215 // swallowing the navigation and forcing a second click — so don't 216 // re-render for a grid element. overlay controls live outside #grid and 217 // survive the diff, so they still tick. 218 if (!grid.contains(t)) wasmInstance.exports._tick(minRows(), maxCols()); 219 }); 220 221 grid.addEventListener("click", (event) => { 222 const span = event.target.closest(".clickable"); 223 if (!span) return; 224 // leave modified / non-left clicks (open-in-new-tab, etc.) to the browser 225 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; 226 // wasm routes the click: an in-page link just moves focus and re-renders, 227 // a cross-page one calls _navigate. suppress the <a>'s own navigation so 228 // an in-page link doesn't also trigger a redundant full page load. 229 event.preventDefault(); 230 const focusId = Number(span.dataset.focusId); 231 wasmInstance.exports._onMouseClick(focusId); 232 wasmInstance.exports._tick(minRows(), maxCols()); 233 }); 234 235 let resizeTimer = null; 236 window.addEventListener("resize", () => { 237 clearTimeout(resizeTimer); 238 resizeTimer = setTimeout(() => { 239 wasmInstance.exports._tick(minRows(), maxCols()); 240 }, 100); 241 }); 242 }); 243