╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ script.js ────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
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 // the initial wasm render can finish while a native picker is open. 156 // keep its input connected so its change event reaches document. 157 if (overlay.contains(document.activeElement) && document.activeElement.type === "file") return; 158 currentOverlay = html; 159 overlay.innerHTML = html; 160 }, 161 _focusInput: function (id) { 162 const target = overlay.querySelector(`[data-focus-id="${id}"]`); 163 if (target && document.activeElement !== target) target.focus(); 164 }, 165 _navigate: function (ptr, len) { 166 // a real browser navigation to another top-level page (the wasm 167 // can't render it client-side without server data). 168 window.location.assign(readWasmString(ptr, len)); 169 }, 170 _scrollToFocus: function (id) { 171 grid.dataset.focusId = id; 172 // bring the focused widget into view within its own .scroll div. it's 173 // several spans (one per row) sharing this id, in top-to-bottom order, 174 // so the first gives its top/left edge and the last its bottom. 175 const els = grid.querySelectorAll(`[data-focus-id="${id}"]`); 176 if (els.length === 0) return; 177 const container = els[0].closest(".scroll"); 178 if (!container) return; 179 180 const c = container.getBoundingClientRect(); 181 const first = els[0].getBoundingClientRect(); 182 const last = els[els.length - 1].getBoundingClientRect(); 183 const top = first.top - c.top + container.scrollTop; 184 const bottom = last.bottom - c.top + container.scrollTop; 185 const left = first.left - c.left + container.scrollLeft; 186 let right = left; 187 for (const el of els) { 188 right = Math.max(right, el.getBoundingClientRect().right - c.left + container.scrollLeft); 189 } 190 191 // vertical is the priority axis. keep the viewport in place when it 192 // already overlaps a tall widget; otherwise reveal its nearest edge. 193 if (bottom - top > container.clientHeight) { 194 container.scrollTop = Math.min(Math.max(container.scrollTop, top), bottom - container.clientHeight); 195 } else if (top < container.scrollTop) { 196 container.scrollTop = top; 197 } else if (bottom > container.scrollTop + container.clientHeight) { 198 container.scrollTop = bottom - container.clientHeight; 199 } 200 // horizontal-only scrolls are rows of controls, so reveal either 201 // edge. other scrolls reveal only the row's start; chasing varying 202 // right edges while moving vertically would yank their view sideways. 203 if (left < container.scrollLeft) { 204 container.scrollLeft = left; 205 } else if (container.dataset.scrollDirection === "horiz" && right > container.scrollLeft + container.clientWidth) { 206 container.scrollLeft = right - container.clientWidth; 207 } 208 }, 209 }, 210 }; 211 212 function sendTextInputValue(focusId, value) { 213 const bytes = encoder.encode(value); 214 const ptr = wasmInstance.exports._alloc(bytes.length); 215 new Uint8Array(wasmInstance.exports.memory.buffer, ptr, bytes.length).set(bytes); 216 wasmInstance.exports._setTextInputValue(focusId, ptr, bytes.length); 217 wasmInstance.exports._tick(minRows(), maxCols()); 218 } 219 220 function sendEnter(form) { 221 const btn = form.querySelector("button[type=submit][data-focus-id]"); 222 if (!btn) return; 223 wasmInstance.exports._onMouseClick(Number(btn.dataset.focusId)); 224 wasmInstance.exports._onKeyDown(13); 225 wasmInstance.exports._tick(minRows(), maxCols()); 226 } 227 228 // upload as soon as the file dialog returns, so attaching is one click. the 229 // file is the whole request body, so its name travels in a header. 230 document.addEventListener("change", (event) => { 231 const t = event.target; 232 if (!t || t.tagName !== "INPUT" || t.type !== "file" || !t.dataset.action) return; 233 const file = t.files[0]; 234 if (!file) return; 235 fetch(t.dataset.action, { 236 method: "POST", 237 headers: { "x-attachment-name": encodeURIComponent(file.name) }, 238 body: file, 239 }).then((res) => { 240 if (res.ok) window.location.reload(); 241 else res.text().then((message) => console.error("upload failed:", message)); 242 }); 243 }); 244 245 WebAssembly.instantiateStreaming(fetch("/haxy.wasm"), importObject).then(async (result) => { 246 wasmInstance = result.instance; 247 248 // wait for the @font-face to load before measuring cell width, otherwise 249 // we get the fallback font's metrics. 250 if (document.fonts && document.fonts.ready) { 251 await document.fonts.ready; 252 } 253 254 // the page is embedded as raw json in a script tag. 255 // encode to utf-8 bytes and hand it to the wasm. 256 const jsonBytes = encoder.encode(pageJson); 257 const ptr = wasmInstance.exports._alloc(jsonBytes.length); 258 new Uint8Array(wasmInstance.exports.memory.buffer, ptr, jsonBytes.length).set(jsonBytes); 259 wasmInstance.exports._init(ptr, jsonBytes.length, minRows(), maxCols()); 260 261 document.addEventListener("keydown", (event) => { 262 // let the browser handle modifier combos. the TUI only uses unmodified keys, 263 // so intercepting these would just break normal browser navigation. 264 if (event.altKey || event.ctrlKey || event.metaKey) return; 265 // when a form element (text input or submit button) owns focus, the 266 // browser handles typing and Tab natively (and Enter on the button 267 // submits). we only forward keys into the TUI when focus is elsewhere. 268 // exception: arrow up/down on an input unfocuses it and forwards 269 // the event so the TUI can move focus between widgets. 270 if (document.activeElement) { 271 const tag = document.activeElement.tagName; 272 const isArrow = event.key === "ArrowUp" || event.key === "ArrowDown" || 273 event.key === "ArrowLeft" || event.key === "ArrowRight"; 274 // a file picker is an input but behaves like a button: every key 275 // but an arrow is native (enter opens its dialog), and an arrow 276 // navigates away from it 277 if (tag === "INPUT" && document.activeElement.type === "file") { 278 if (!isArrow) return; 279 document.activeElement.blur(); 280 } else if (tag === "INPUT" && document.activeElement.readOnly && 281 ["Enter", "ArrowLeft", "ArrowRight"].includes(event.key)) { 282 event.preventDefault(); 283 if (event.key === "Enter") { 284 document.activeElement.select(); 285 return; 286 } 287 wasmInstance.exports._onKeyDown(event.keyCode); 288 wasmInstance.exports._tick(minRows(), maxCols()); 289 return; 290 } else if (tag === "INPUT" && event.key === "Enter") { 291 // enter in a text input never submits the form; only the 292 // submit button does 293 event.preventDefault(); 294 return; 295 } else if (tag === "INPUT" && (event.key === "ArrowUp" || event.key === "ArrowDown")) { 296 // up/down moves between widgets; left/right stay in the input 297 document.activeElement.blur(); 298 } else if (tag === "BUTTON" && isArrow) { 299 // arrows navigate away from a focused submit button 300 document.activeElement.blur(); 301 } else if (tag === "INPUT" || tag === "BUTTON" || tag === "TEXTAREA") { 302 // Enter (submit / newline), typing, Tab, and a textarea's 303 // arrows — handled natively by the browser 304 return; 305 } 306 } 307 if ((event.key === "ArrowUp" || event.key === "ArrowDown") && scrollFocusedWidget(event.key === "ArrowDown")) { 308 event.preventDefault(); 309 return; 310 } 311 if ((event.key === "PageUp" || event.key === "PageDown") && pageFocusedScroll(event.key === "PageDown")) { 312 event.preventDefault(); 313 return; 314 } 315 if (["ArrowUp", "ArrowDown", "ArrowLeft", "ArrowRight", "PageUp", "PageDown", "Home", "End"].includes(event.key)) { 316 event.preventDefault(); 317 } 318 wasmInstance.exports._onKeyDown(event.keyCode); 319 wasmInstance.exports._tick(minRows(), maxCols()); 320 }); 321 322 // submit on mousedown rather than waiting for click: the focusin this 323 // same mousedown fires ticks the wasm, and a resulting overlay rebuild 324 // would detach the button before its click could land. the form is 325 // guaranteed live at mousedown time. 326 document.addEventListener("mousedown", (event) => { 327 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; 328 const btn = event.target.closest ? event.target.closest("button[type=submit][data-focus-id]") : null; 329 if (!btn || !btn.form) return; 330 // empty-action forms are handled by their onsubmit on the click path 331 if (!btn.form.getAttribute("action")) return; 332 // if the button survives to receive the click, don't submit twice 333 btn.addEventListener("click", (e) => e.preventDefault(), { once: true }); 334 btn.form.requestSubmit(btn); 335 }); 336 337 // listeners on document (not #grid) since the form lives outside #grid; 338 // input/focus events from form elements still bubble up to document. 339 document.addEventListener("input", (event) => { 340 const t = event.target; 341 if (!t || (t.tagName !== "INPUT" && t.tagName !== "TEXTAREA") || !t.dataset.focusId) return; 342 sendTextInputValue(Number(t.dataset.focusId), t.value); 343 }); 344 345 document.addEventListener("click", (event) => { 346 const t = event.target; 347 if (t && t.tagName === "INPUT" && t.readOnly) t.select(); 348 }); 349 350 document.addEventListener("focusin", (event) => { 351 const t = event.target; 352 if (!t || !t.dataset || !t.dataset.focusId) return; 353 // sync the wasm focus to wherever the browser moved focus 354 wasmInstance.exports._setFocus(Number(t.dataset.focusId)); 355 // a click's mousedown fires this focusin before the click event. ticking 356 // here would rebuild #grid and destroy the node before its click lands, 357 // swallowing the navigation and forcing a second click — so don't 358 // re-render for a grid element. a file input is also skipped because a 359 // changed overlay would replace it between mousedown and click, before 360 // the browser opens its picker. 361 if (!grid.contains(t) && !(t.tagName === "INPUT" && t.type === "file")) { 362 wasmInstance.exports._tick(minRows(), maxCols()); 363 } 364 }); 365 366 grid.addEventListener("click", (event) => { 367 const span = event.target.closest(".clickable"); 368 if (!span) return; 369 // leave modified / non-left clicks (open-in-new-tab, etc.) to the browser 370 if (event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; 371 // wasm routes the click: an in-page link just moves focus and re-renders, 372 // a cross-page one calls _navigate. suppress the <a>'s own navigation so 373 // an in-page link doesn't also trigger a redundant full page load. 374 event.preventDefault(); 375 const focusId = Number(span.dataset.focusId); 376 wasmInstance.exports._onMouseClick(focusId); 377 wasmInstance.exports._tick(minRows(), maxCols()); 378 }); 379 380 let resizeTimer = null; 381 window.addEventListener("resize", () => { 382 clearTimeout(resizeTimer); 383 resizeTimer = setTimeout(() => { 384 wasmInstance.exports._tick(minRows(), maxCols()); 385 }, 100); 386 }); 387 }); 388