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