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