╭ script.js ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const grid = document.getElementById("grid"); 2 const pageJson = document.getElementById("page-data").textContent; 3 4 let wasmInstance; 5 const decoder = new TextDecoder(); 6 const encoder = new TextEncoder(); 7 // seed the render snapshot from the server html. if wasm produces the same 8 // first frame, the live DOM does not need even a reconciliation pass. 9 let currentHtml = grid.innerHTML; 10 11 const MIN_COLS = 30; 12 13 // measured once after the font is loaded. recomputed lazily if either reads 14 // back as zero (e.g. measured before the font was actually ready). 15 let cellWidth = null; 16 let cellHeight = null; 17 18 function measureCell() { 19 const probe = document.createElement("span"); 20 probe.style.position = "absolute"; 21 probe.style.visibility = "hidden"; 22 probe.style.whiteSpace = "pre"; 23 probe.textContent = "X".repeat(100); 24 grid.appendChild(probe); 25 const rect = probe.getBoundingClientRect(); 26 probe.remove(); 27 cellWidth = rect.width / 100; 28 cellHeight = rect.height; 29 } 30 31 function maxCols() { 32 if (!cellWidth) measureCell(); 33 return Math.max(MIN_COLS, Math.floor(document.body.clientWidth / cellWidth)); 34 } 35 36 // minimum row count for the wasm build — the TUI fills at least the 37 // viewport height, longer content extends past it and the browser scrolls. 38 function minRows() { 39 if (!cellHeight) measureCell(); 40 return Math.max(1, Math.floor(document.documentElement.clientHeight / cellHeight)); 41 } 42 43 function readWasmString(ptr, len) { 44 const memory = wasmInstance.exports.memory; 45 return decoder.decode(new Uint8Array(memory.buffer, ptr, len)); 46 } 47 48 function focusElements(id) { 49 // a native control is the authoritative geometry for its widget. the cell 50 // layer also contains spans with this id, but those are only its backdrop. 51 const control = grid.querySelector(`[data-key="control:${id}"]`); 52 return control ? [control] : Array.from(grid.querySelectorAll(`[data-focus-id="${id}"]`)); 53 } 54 55 function focusedNativeScroll() { 56 const id = grid.dataset.focusId; 57 if (!id) return null; 58 const focused = focusElements(id); 59 if (focused.length === 0) return null; 60 const container = focused[0].closest(".scroll"); 61 return container ? { focused, container } : null; 62 } 63 64 // scroll one row while the focused widget continues past the viewport edge. 65 function scrollFocusedWidget(down) { 66 const native = focusedNativeScroll(); 67 if (!native) return false; 68 const viewport = native.container.getBoundingClientRect(); 69 const edge = (down ? native.focused[native.focused.length - 1] : native.focused[0]).getBoundingClientRect(); 70 const overflow = down ? edge.bottom - viewport.bottom : viewport.top - edge.top; 71 if (overflow <= 0.5) return false; 72 if (!cellHeight) measureCell(); 73 native.container.scrollTop += (down ? 1 : -1) * Math.min(cellHeight, overflow); 74 return true; 75 } 76 77 // page the focused native scroll, then focus its leading visible widget. 78 function pageFocusedScroll(down) { 79 const native = focusedNativeScroll(); 80 if (!native) return false; 81 const container = native.container; 82 83 container.scrollTop += (down ? 1 : -1) * container.clientHeight; 84 const viewport = container.getBoundingClientRect(); 85 let chosen = null; 86 for (const el of container.querySelectorAll(".clickable[data-focus-id]")) { 87 const rect = el.getBoundingClientRect(); 88 if (rect.bottom <= viewport.top || rect.top >= viewport.bottom) continue; 89 chosen = el; 90 if (!down) break; 91 } 92 if (chosen) wasmInstance.exports._setFocus(Number(chosen.dataset.focusId)); 93 wasmInstance.exports._tick(minRows(), maxCols()); 94 return true; 95 } 96 97 // stateful controls, scroll panels, and form owners are keyed. everything 98 // unkeyed is replaced wholesale, including each panel's cell layer. 99 function nodeKey(node) { 100 if (node.nodeType !== Node.ELEMENT_NODE) return null; 101 return node.dataset.key || null; 102 } 103 104 function nodesMatch(current, desired) { 105 if (nodeKey(current) !== nodeKey(desired) || current.tagName !== desired.tagName) return false; 106 return current.tagName !== "INPUT" || current.type === desired.type; 107 } 108 109 function syncAttributes(current, desired) { 110 const preserveValue = desired.hasAttribute("data-preserve-value"); 111 for (const attr of Array.from(current.attributes)) { 112 if (!desired.hasAttribute(attr.name)) current.removeAttribute(attr.name); 113 } 114 for (const attr of Array.from(desired.attributes)) { 115 // updating the default value of a dirty input is usually harmless, but 116 // avoiding it entirely gives browsers no opportunity to disturb the 117 // live value, selection, undo stack, or an open file picker. 118 if (preserveValue && attr.name === "value") continue; 119 if (current.getAttribute(attr.name) !== attr.value) current.setAttribute(attr.name, attr.value); 120 } 121 122 if (current.tagName === "INPUT" && !preserveValue && current.type !== "file" && current.value !== desired.value) { 123 current.value = desired.value; 124 } 125 } 126 127 function patchNode(current, desired) { 128 syncAttributes(current, desired); 129 if (current.tagName === "TEXTAREA") { 130 if (!desired.hasAttribute("data-preserve-value")) { 131 if (current.value !== desired.value) current.value = desired.value; 132 if (current.defaultValue !== desired.defaultValue) current.defaultValue = desired.defaultValue; 133 } 134 return; 135 } 136 137 patchChildren(current, desired); 138 } 139 140 function patchChildren(current, desired) { 141 const keyed = new Map(); 142 for (const child of Array.from(current.childNodes)) { 143 const key = nodeKey(child); 144 if (key) keyed.set(key, child); 145 } 146 147 let cursor = current.firstChild; 148 for (const wanted of Array.from(desired.childNodes)) { 149 const key = nodeKey(wanted); 150 if (!key) { 151 const replacement = wanted.cloneNode(true); 152 if (cursor && !nodeKey(cursor)) { 153 const next = cursor.nextSibling; 154 current.replaceChild(replacement, cursor); 155 cursor = next; 156 } else { 157 current.insertBefore(replacement, cursor); 158 } 159 continue; 160 } 161 162 let found = keyed.get(key); 163 if (found && !nodesMatch(found, wanted)) found = null; 164 if (!found) { 165 found = wanted.cloneNode(true); 166 current.insertBefore(found, cursor); 167 } else { 168 keyed.delete(key); 169 while (cursor && cursor !== found && !nodeKey(cursor)) { 170 const next = cursor.nextSibling; 171 cursor.remove(); 172 cursor = next; 173 } 174 if (found !== cursor) current.insertBefore(found, cursor); 175 patchNode(found, wanted); 176 } 177 cursor = found.nextSibling; 178 } 179 180 while (cursor) { 181 const next = cursor.nextSibling; 182 cursor.remove(); 183 cursor = next; 184 } 185 } 186 187 function patchHtml(container, html) { 188 const template = document.createElement("template"); 189 template.innerHTML = html; 190 patchChildren(container, template.content); 191 } 192 193 const importObject = { 194 env: { 195 _consoleLog: function (ptr, len) { 196 console.log(readWasmString(ptr, len)); 197 }, 198 _setHtml: function (ptr, len) { 199 const html = readWasmString(ptr, len); 200 if (html === currentHtml) return; 201 currentHtml = html; 202 // snapshot browser and wasm scroll state before reconciling. a stable 203 // scroll with the same version and wasm offset keeps its browser 204 // position; new content or an intentional wasm move uses the offset. 205 const scrolls = new Map(); 206 for (const el of grid.querySelectorAll(".scroll[data-key]")) { 207 scrolls.set(el.dataset.key, { 208 id: el.dataset.scrollId, 209 offsetTop: Number(el.dataset.scrollY || 0), 210 offsetLeft: Number(el.dataset.scrollX || 0), 211 top: el.scrollTop, 212 left: el.scrollLeft, 213 }); 214 } 215 patchHtml(grid, html); 216 for (const el of grid.querySelectorAll(".scroll[data-key]")) { 217 const offset = { top: Number(el.dataset.scrollY || 0), left: Number(el.dataset.scrollX || 0) }; 218 const previous = scrolls.get(el.dataset.key); 219 if (previous && previous.id === el.dataset.scrollId && previous.offsetTop === offset.top && previous.offsetLeft === offset.left) { 220 el.scrollTop = previous.top; 221 el.scrollLeft = previous.left; 222 } else { 223 // the wasm's offset changed (or this div is new — a fresh 224 // page load or a bumped content version): apply it, 225 // converted from cells to pixels. 226 if (!cellWidth || !cellHeight) measureCell(); 227 el.scrollTop = offset.top * cellHeight; 228 el.scrollLeft = offset.left * cellWidth; 229 } 230 } 231 }, 232 _replaceState: function (ptr, len) { 233 const url = readWasmString(ptr, len); 234 // passive same-page URL changes. replaceState changes the URL 235 // without adding a history entry, so the back button isn't 236 // cluttered with unnecessary entries. 237 if (window.location.pathname !== url) { 238 history.replaceState({}, "", url); 239 } 240 }, 241 _focusInput: function (id) { 242 const target = grid.querySelector(`[data-key="control:${id}"]`); 243 if (!target) return; 244 if (document.activeElement !== target) target.focus(); 245 if (target.readOnly) target.select(); 246 }, 247 _navigate: function (ptr, len) { 248 // a real browser navigation to another top-level page (the wasm 249 // can't render it client-side without server data). 250 window.location.assign(readWasmString(ptr, len)); 251 }, 252 _scrollToFocus: function (id) { 253 grid.dataset.focusId = id; 254 // bring the focused widget into view within its own .scroll div. it's 255 // several spans (one per row) sharing this id, in top-to-bottom order, 256 // so the first gives its top/left edge and the last its bottom. 257 const els = focusElements(id); 258 if (els.length === 0) return; 259 const container = els[0].closest(".scroll"); 260 if (!container) return; 261 262 const c = container.getBoundingClientRect(); 263 const first = els[0].getBoundingClientRect(); 264 const last = els[els.length - 1].getBoundingClientRect(); 265 const top = first.top - c.top + container.scrollTop; 266 const bottom = last.bottom - c.top + container.scrollTop; 267 const left = first.left - c.left + container.scrollLeft; 268 let right = left; 269 for (const el of els) { 270 right = Math.max(right, el.getBoundingClientRect().right - c.left + container.scrollLeft); 271 } 272 273 // vertical is the priority axis. keep the viewport in place when it 274 // already overlaps a tall widget; otherwise reveal its nearest edge. 275 if (bottom - top > container.clientHeight) { 276 container.scrollTop = Math.min(Math.max(container.scrollTop, top), bottom - container.clientHeight); 277 } else if (top < container.scrollTop) { 278 container.scrollTop = top; 279 } else if (bottom > container.scrollTop + container.clientHeight) { 280 container.scrollTop = bottom - container.clientHeight; 281 } 282 // horizontal-only scrolls are rows of controls, so reveal either 283 // edge. other scrolls reveal only the row's start; chasing varying 284 // right edges while moving vertically would yank their view sideways. 285 if (left < container.scrollLeft) { 286 container.scrollLeft = left; 287 } else if (container.dataset.scrollDirection === "horiz" && right > container.scrollLeft + container.clientWidth) { 288 container.scrollLeft = right - container.clientWidth; 289 } 290 }, 291 }, 292 }; 293 294 function sendTextInputValue(focusId, value) { 295 const bytes = encoder.encode(value); 296 const ptr = wasmInstance.exports._alloc(bytes.length); 297 // an empty allocation's pointer lies outside the buffer, so a view onto it 298 // would throw and leave the wasm holding the old value 299 if (bytes.length > 0) { 300 new Uint8Array(wasmInstance.exports.memory.buffer, ptr, bytes.length).set(bytes); 301 } 302 wasmInstance.exports._setTextInputValue(focusId, ptr, bytes.length); 303 wasmInstance.exports._tick(minRows(), maxCols()); 304 } 305 306 // upload as soon as the file dialog returns, so attaching is one click. the 307 // file is the whole request body, so its name travels in a header. 308 document.addEventListener("change", (event) => { 309 const t = event.target; 310 if (!t || t.tagName !== "INPUT" || t.type !== "file" || !t.dataset.action) return; 311 const file = t.files[0]; 312 if (!file) return; 313 fetch(t.dataset.action, { 314 method: "POST", 315 headers: { "x-attachment-name": encodeURIComponent(file.name) }, 316 body: file, 317 }).then((res) => { 318 if (res.ok) window.location.reload(); 319 else res.text().then((message) => console.error("upload failed:", message)); 320 }); 321 }); 322 323 WebAssembly.instantiateStreaming(fetch("/haxy.wasm"), importObject).then(async (result) => { 324 wasmInstance = result.instance; 325 326 // wait for the @font-face to load before measuring cell width, otherwise 327 // we get the fallback font's metrics. 328 if (document.fonts && document.fonts.ready) { 329 await document.fonts.ready; 330 } 331 332 // the page is embedded as raw json in a script tag. 333 // encode to utf-8 bytes and hand it to the wasm. 334 const jsonBytes = encoder.encode(pageJson); 335 const ptr = wasmInstance.exports._alloc(jsonBytes.length); 336 new Uint8Array(wasmInstance.exports.memory.buffer, ptr, jsonBytes.length).set(jsonBytes); 337 wasmInstance.exports._init(ptr, jsonBytes.length, minRows(), maxCols()); 338 339 document.addEventListener("keydown", (event) => { 340 // let the browser handle modifier combos. the TUI only uses unmodified keys, 341 // so intercepting these would just break normal browser navigation. 342 if (event.altKey || event.ctrlKey || event.metaKey) return; 343 // when a form element (text input or submit button) owns focus, the 344 // browser handles typing and Tab natively (and Enter on the button 345 // submits). we only forward keys into the TUI when focus is elsewhere. 346 // exception: arrow up/down on an input unfocuses it and forwards 347 // the event so the TUI can move focus between widgets. 348 if (document.activeElement) { 349 const tag = document.activeElement.tagName; 350 const isArrow = event.key === "ArrowUp" || event.key === "ArrowDown" || 351 event.key === "ArrowLeft" || event.key === "ArrowRight"; 352 // a file picker is an input but behaves like a button: every key 353 // but an arrow is native (enter opens its dialog), and an arrow 354 // navigates away from it 355 if (tag === "INPUT" && document.activeElement.type === "file") { 356 if (!isArrow) return; 357 document.activeElement.blur(); 358 } else if (tag === "INPUT" && document.activeElement.readOnly && 359 ["Enter", "ArrowLeft", "ArrowRight"].includes(event.key)) { 360 event.preventDefault(); 361 if (event.key === "Enter") { 362 document.activeElement.select(); 363 return; 364 } 365 wasmInstance.exports._onKeyDown(event.keyCode); 366 wasmInstance.exports._tick(minRows(), maxCols()); 367 return; 368 } else if (tag === "INPUT" && event.key === "Enter") { 369 // enter in a form's text input never submits it; only the 370 // submit button does. an input outside a form has no submit 371 // button, so the TUI handles its enter instead. 372 event.preventDefault(); 373 if (!document.activeElement.form) { 374 wasmInstance.exports._onKeyDown(event.keyCode); 375 wasmInstance.exports._tick(minRows(), maxCols()); 376 } 377 return; 378 } else if (tag === "INPUT" && (event.key === "ArrowUp" || event.key === "ArrowDown")) { 379 // up/down moves between widgets; left/right stay in the input 380 document.activeElement.blur(); 381 } else if (tag === "BUTTON" && isArrow) { 382 // arrows navigate away from a focused submit button 383 document.activeElement.blur(); 384 } else if (tag === "INPUT" || tag === "BUTTON" || tag === "TEXTAREA") { 385 // Enter (submit / newline), typing, Tab, and a textarea's 386 // arrows — handled natively by the browser 387 return; 388 } 389 } 390 if ((event.key === "ArrowUp" || event.key === "ArrowDown") && scrollFocusedWidget(event.key === "ArrowDown")) { 391 event.preventDefault(); 392 return; 393 } 394 if ((event.key === "PageUp" || event.key === "PageDown") && pageFocusedScroll(event.key === "PageDown")) { 395 event.preventDefault(); 396 return; 397 } 398 if (["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "PageUp", "PageDown", "Home", "End"].includes(event.key)) { 399 event.preventDefault(); 400 } 401 wasmInstance.exports._onKeyDown(event.keyCode); 402 wasmInstance.exports._tick(minRows(), maxCols()); 403 }); 404 405 // delegated listeners survive cell-layer replacement. the controls 406 // themselves are retained inside #grid. 407 document.addEventListener("input", (event) => { 408 const t = event.target; 409 if (!t || (t.tagName !== "INPUT" && t.tagName !== "TEXTAREA") || !t.dataset.focusId) return; 410 sendTextInputValue(Number(t.dataset.focusId), t.value); 411 }); 412 413 document.addEventListener("focusin", (event) => { 414 const t = event.target; 415 if (!t || !t.dataset || !t.dataset.focusId) return; 416 // sync the wasm focus to wherever the browser moved focus 417 wasmInstance.exports._setFocus(Number(t.dataset.focusId)); 418 // keyed controls survive a redraw before click. cell links live in the 419 // replaceable backdrop, so their click handler redraws after activation. 420 if (nodeKey(t)?.startsWith("control:")) wasmInstance.exports._tick(minRows(), maxCols()); 421 }); 422 423 grid.addEventListener("click", (event) => { 424 if (event.target.matches("input[readonly]")) { 425 wasmInstance.exports._tick(minRows(), maxCols()); 426 return; 427 } 428 const span = event.target.closest(".clickable"); 429 if (!span) return; 430 // leave modified / non-left clicks (open-in-new-tab, etc.) to the browser 431 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; 432 // wasm routes the click: an in-page link updates focus and re-renders, 433 // a cross-page one calls _navigate. suppress the <a>'s own navigation so 434 // an in-page link doesn't also trigger a redundant full page load. 435 event.preventDefault(); 436 const focusId = Number(span.dataset.focusId); 437 wasmInstance.exports._onMouseClick(focusId); 438 wasmInstance.exports._tick(minRows(), maxCols()); 439 }); 440 441 let resizeTimer = null; 442 window.addEventListener("resize", () => { 443 clearTimeout(resizeTimer); 444 resizeTimer = setTimeout(() => { 445 wasmInstance.exports._tick(minRows(), maxCols()); 446 }, 100); 447 }); 448 }); 449