╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ script.js ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
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 function focusedNativeScroll() { 57 const id = grid.dataset.focusId; 58 if (!id) return null; 59 const focused = grid.querySelectorAll(`[data-focus-id="${id}"]`); 60 if (focused.length === 0) return null; 61 const container = focused[0].closest(".scroll"); 62 return container ? { focused, container } : null; 63 } 64 65 // scroll one row while the focused widget continues past the viewport edge. 66 function scrollFocusedWidget(down) { 67 const native = focusedNativeScroll(); 68 if (!native) return false; 69 const viewport = native.container.getBoundingClientRect(); 70 const edge = (down ? native.focused[native.focused.length - 1] : native.focused[0]).getBoundingClientRect(); 71 const overflow = down ? edge.bottom - viewport.bottom : viewport.top - edge.top; 72 if (overflow <= 0.5) return false; 73 if (!cellHeight) measureCell(); 74 native.container.scrollTop += (down ? 1 : -1) * Math.min(cellHeight, overflow); 75 return true; 76 } 77 78 // page the focused native scroll, then focus its leading visible widget. 79 function pageFocusedScroll(down) { 80 const native = focusedNativeScroll(); 81 if (!native) return false; 82 const container = native.container; 83 84 container.scrollTop += (down ? 1 : -1) * container.clientHeight; 85 const viewport = container.getBoundingClientRect(); 86 let chosen = null; 87 for (const el of container.querySelectorAll(".clickable[data-focus-id]")) { 88 const rect = el.getBoundingClientRect(); 89 if (rect.bottom <= viewport.top || rect.top >= viewport.bottom) continue; 90 chosen = el; 91 if (!down) break; 92 } 93 if (chosen) wasmInstance.exports._setFocus(Number(chosen.dataset.focusId)); 94 wasmInstance.exports._tick(minRows(), maxCols()); 95 return true; 96 } 97 98 const importObject = { 99 env: { 100 _consoleLog: function (ptr, len) { 101 console.log(readWasmString(ptr, len)); 102 }, 103 _setHtml: function (ptr, len) { 104 const html = readWasmString(ptr, len); 105 if (html === currentHtml) return; 106 currentHtml = html; 107 // each web-native Scroll renders as a .scroll div; replacing 108 // innerHTML recreates them and would reset their scroll position 109 // every tick, so snapshot scrollTop/Left by their stable id and 110 // restore it after the swap. (mouse-wheel scrolling happens with no 111 // tick, so it isn't affected.) 112 const positions = {}; 113 for (const el of grid.querySelectorAll(".scroll[data-scroll-id]")) { 114 positions[el.dataset.scrollId] = { top: el.scrollTop, left: el.scrollLeft }; 115 } 116 grid.innerHTML = html; 117 for (const el of grid.querySelectorAll(".scroll[data-scroll-id]")) { 118 const id = el.dataset.scrollId; 119 const offset = { top: Number(el.dataset.scrollY || 0), left: Number(el.dataset.scrollX || 0) }; 120 const prev = wasmOffsets[id]; 121 const p = positions[id]; 122 if (p && prev && prev.top === offset.top && prev.left === offset.left) { 123 el.scrollTop = p.top; 124 el.scrollLeft = p.left; 125 } else { 126 // the wasm's offset changed (or this div is new — a fresh 127 // page load or a bumped content version): apply it, 128 // converted from cells to pixels. 129 if (!cellWidth || !cellHeight) measureCell(); 130 el.scrollTop = offset.top * cellHeight; 131 el.scrollLeft = offset.left * cellWidth; 132 } 133 wasmOffsets[id] = offset; 134 } 135 }, 136 _replaceState: function (ptr, len) { 137 const url = readWasmString(ptr, len); 138 // passive same-page URL changes. replaceState changes the URL 139 // without adding a history entry, so the back button isn't 140 // cluttered with unnecessary entries. 141 if (window.location.pathname !== url) { 142 history.replaceState({}, "", url); 143 } 144 }, 145 _setOverlay: function (ptr, len) { 146 const html = readWasmString(ptr, len); 147 // diff against the previous overlay HTML; an unchanged overlay 148 // means no layout/structure has shifted (typing alone doesn't 149 // produce a diff because we deliberately omit the `value` 150 // attribute on inputs — the browser tracks that). skipping the 151 // innerHTML assignment keeps the live <form> alive across the 152 // mousedown→focusin→tick→click sequence, which is what lets 153 // the very first click on the submit button actually submit. 154 if (html === currentOverlay) return; 155 currentOverlay = html; 156 overlay.innerHTML = html; 157 }, 158 _focusInput: function (id) { 159 const target = overlay.querySelector(`[data-focus-id="${id}"]`); 160 if (target && document.activeElement !== target) target.focus(); 161 }, 162 _navigate: function (ptr, len) { 163 // a real browser navigation to another top-level page (the wasm 164 // can't render it client-side without server data). 165 window.location.assign(readWasmString(ptr, len)); 166 }, 167 _scrollToFocus: function (id) { 168 grid.dataset.focusId = id; 169 // bring the focused widget into view within its own .scroll div. it's 170 // several spans (one per row) sharing this id, in top-to-bottom order, 171 // so the first gives its top/left edge and the last its bottom. 172 const els = grid.querySelectorAll(`[data-focus-id="${id}"]`); 173 if (els.length === 0) return; 174 const container = els[0].closest(".scroll"); 175 if (!container) return; 176 177 const c = container.getBoundingClientRect(); 178 const first = els[0].getBoundingClientRect(); 179 const last = els[els.length - 1].getBoundingClientRect(); 180 const top = first.top - c.top + container.scrollTop; 181 const bottom = last.bottom - c.top + container.scrollTop; 182 const left = first.left - c.left + container.scrollLeft; 183 184 // vertical is the priority axis. keep the viewport in place when it 185 // already overlaps a tall widget; otherwise reveal its nearest edge. 186 if (bottom - top > container.clientHeight) { 187 container.scrollTop = Math.min(Math.max(container.scrollTop, top), bottom - container.clientHeight); 188 } else if (top < container.scrollTop) { 189 container.scrollTop = top; 190 } else if (bottom > container.scrollTop + container.clientHeight) { 191 container.scrollTop = bottom - container.clientHeight; 192 } 193 // horizontal: only reveal the row's start, never chase the right edge, 194 // so moving down through varying-width rows doesn't yank the view 195 // sideways. (a hidden-overflow x axis stays at 0, so this no-ops.) 196 if (left < container.scrollLeft) container.scrollLeft = left; 197 }, 198 }, 199 }; 200 201 function sendTextInputValue(focusId, value) { 202 const bytes = encoder.encode(value); 203 const ptr = wasmInstance.exports._alloc(bytes.length); 204 new Uint8Array(wasmInstance.exports.memory.buffer, ptr, bytes.length).set(bytes); 205 wasmInstance.exports._setTextInputValue(focusId, ptr, bytes.length); 206 wasmInstance.exports._tick(minRows(), maxCols()); 207 } 208 209 function sendEnter(form) { 210 const btn = form.querySelector("button[type=submit][data-focus-id]"); 211 if (!btn) return; 212 wasmInstance.exports._onMouseClick(Number(btn.dataset.focusId)); 213 wasmInstance.exports._onKeyDown(13); 214 wasmInstance.exports._tick(minRows(), maxCols()); 215 } 216 217 WebAssembly.instantiateStreaming(fetch("/haxy.wasm"), importObject).then(async (result) => { 218 wasmInstance = result.instance; 219 220 // wait for the @font-face to load before measuring cell width, otherwise 221 // we get the fallback font's metrics. 222 if (document.fonts && document.fonts.ready) { 223 await document.fonts.ready; 224 } 225 226 // the page is embedded as raw json in a script tag. 227 // encode to utf-8 bytes and hand it to the wasm. 228 const jsonBytes = encoder.encode(pageJson); 229 const ptr = wasmInstance.exports._alloc(jsonBytes.length); 230 new Uint8Array(wasmInstance.exports.memory.buffer, ptr, jsonBytes.length).set(jsonBytes); 231 wasmInstance.exports._init(ptr, jsonBytes.length, minRows(), maxCols()); 232 233 document.addEventListener("keydown", (event) => { 234 // let the browser handle modifier combos. the TUI only uses unmodified keys, 235 // so intercepting these would just break normal browser navigation. 236 if (event.altKey || event.ctrlKey || event.metaKey) return; 237 // when a form element (text input or submit button) owns focus, the 238 // browser handles typing and Tab natively (and Enter on the button 239 // submits). we only forward keys into the TUI when focus is elsewhere. 240 // exception: arrow up/down on an input unfocuses it and forwards 241 // the event so the TUI can move focus between widgets. 242 if (document.activeElement) { 243 const tag = document.activeElement.tagName; 244 const isArrow = event.key === "ArrowUp" || event.key === "ArrowDown" || 245 event.key === "ArrowLeft" || event.key === "ArrowRight"; 246 if (tag === "INPUT" && document.activeElement.readOnly && 247 ["Enter", "ArrowLeft", "ArrowRight"].includes(event.key)) { 248 event.preventDefault(); 249 if (event.key === "Enter") { 250 document.activeElement.select(); 251 return; 252 } 253 wasmInstance.exports._onKeyDown(event.keyCode); 254 wasmInstance.exports._tick(minRows(), maxCols()); 255 return; 256 } 257 if (tag === "INPUT" && event.key === "Enter") { 258 // enter in a text input never submits the form; only the 259 // submit button does 260 event.preventDefault(); 261 return; 262 } 263 if (tag === "INPUT" && (event.key === "ArrowUp" || event.key === "ArrowDown")) { 264 // up/down moves between widgets; left/right stay in the input 265 document.activeElement.blur(); 266 } else if (tag === "BUTTON" && isArrow) { 267 // arrows navigate away from a focused submit button 268 document.activeElement.blur(); 269 } else if (tag === "INPUT" || tag === "BUTTON" || tag === "TEXTAREA") { 270 // Enter (submit / newline), typing, Tab, and a textarea's 271 // arrows — handled natively by the browser 272 return; 273 } 274 } 275 if ((event.key === "ArrowUp" || event.key === "ArrowDown") && scrollFocusedWidget(event.key === "ArrowDown")) { 276 event.preventDefault(); 277 return; 278 } 279 if ((event.key === "PageUp" || event.key === "PageDown") && pageFocusedScroll(event.key === "PageDown")) { 280 event.preventDefault(); 281 return; 282 } 283 if (["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "PageUp", "PageDown", "Home", "End"].includes(event.key)) { 284 event.preventDefault(); 285 } 286 wasmInstance.exports._onKeyDown(event.keyCode); 287 wasmInstance.exports._tick(minRows(), maxCols()); 288 }); 289 290 // submit on mousedown rather than waiting for click: the focusin this 291 // same mousedown fires ticks the wasm, and a resulting overlay rebuild 292 // would detach the button before its click could land. the form is 293 // guaranteed live at mousedown time. 294 document.addEventListener("mousedown", (event) => { 295 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; 296 const btn = event.target.closest ? event.target.closest("button[type=submit][data-focus-id]") : null; 297 if (!btn || !btn.form) return; 298 // empty-action forms are handled by their onsubmit on the click path 299 if (!btn.form.getAttribute("action")) return; 300 // if the button survives to receive the click, don't submit twice 301 btn.addEventListener("click", (e) => e.preventDefault(), { once: true }); 302 btn.form.requestSubmit(btn); 303 }); 304 305 // listeners on document (not #grid) since the form lives outside #grid; 306 // input/focus events from form elements still bubble up to document. 307 document.addEventListener("input", (event) => { 308 const t = event.target; 309 if (!t || (t.tagName !== "INPUT" && t.tagName !== "TEXTAREA") || !t.dataset.focusId) return; 310 sendTextInputValue(Number(t.dataset.focusId), t.value); 311 }); 312 313 document.addEventListener("click", (event) => { 314 const t = event.target; 315 if (t && t.tagName === "INPUT" && t.readOnly) t.select(); 316 }); 317 318 document.addEventListener("focusin", (event) => { 319 const t = event.target; 320 if (!t || !t.dataset || !t.dataset.focusId) return; 321 // sync the wasm focus to wherever the browser moved focus 322 wasmInstance.exports._setFocus(Number(t.dataset.focusId)); 323 // a click's mousedown fires this focusin before the click event. ticking 324 // here would rebuild #grid and destroy the node before its click lands, 325 // swallowing the navigation and forcing a second click — so don't 326 // re-render for a grid element. overlay controls live outside #grid and 327 // survive the diff, so they still tick. 328 if (!grid.contains(t)) wasmInstance.exports._tick(minRows(), maxCols()); 329 }); 330 331 grid.addEventListener("click", (event) => { 332 const span = event.target.closest(".clickable"); 333 if (!span) return; 334 // leave modified / non-left clicks (open-in-new-tab, etc.) to the browser 335 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; 336 // wasm routes the click: an in-page link just moves focus and re-renders, 337 // a cross-page one calls _navigate. suppress the <a>'s own navigation so 338 // an in-page link doesn't also trigger a redundant full page load. 339 event.preventDefault(); 340 const focusId = Number(span.dataset.focusId); 341 wasmInstance.exports._onMouseClick(focusId); 342 wasmInstance.exports._tick(minRows(), maxCols()); 343 }); 344 345 let resizeTimer = null; 346 window.addEventListener("resize", () => { 347 clearTimeout(resizeTimer); 348 resizeTimer = setTimeout(() => { 349 wasmInstance.exports._tick(minRows(), maxCols()); 350 }, 100); 351 }); 352 }); 353