Live updates: pages refresh themselves in place

This commit is contained in:
claude committed 2026-10-11 17:39:43 +02:00
1 parent 05275645f5
commit c367dd761a
1 file changed
+309
+309
View File
@@ -0,0 +1,309 @@
/* OpenBench live updates: the pages keep themselves current.
Every few seconds the page asks the server for its own HTML, and only the
parts that changed are swapped in. Scroll position, text selection, open
forms and the LLR history graph are left alone. Polling pauses in a hidden
tab, backs off when the server is unreachable, and can be switched off with
the pill in the corner. No dependencies, and the pages work without it. */
(function () {
'use strict';
var PAGES = /^\/(?:(?:index|greens|machines|events|errors)(?:\/\d+)?|user\/[^\/]+(?:\/\d+)?|(?:test|tune|datagen)\/\d+)?\/?$/;
if (!PAGES.test(window.location.pathname)) return;
var content = document.getElementById('content');
if (!content || !window.fetch || !window.DOMParser) return;
var FULL = { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false };
var DAY = { month: 'short', day: '2-digit' };
// Never replaced: forms keep what is typed, banners can be dismissed, the graph loads itself
var PROTECT = 'form, .banner, .llr-history-panel, [data-live-skip], script, style';
// Attributes that other scripts add after the page loads
var KEEP = { 'data-href': true, 'data-epoch': true };
/* ---------- Timestamps ----------
The pages print raw epochs and the browser formats them. Remember the
epoch before that happens, so that two versions can be compared. */
function stash(root) {
Array.prototype.forEach.call(root.querySelectorAll('.timestamp, .datestamp'), function (el) {
var text = el.textContent.trim();
if (!el.hasAttribute('data-epoch') && /^\d+(\.\d+)?$/.test(text)) el.setAttribute('data-epoch', text);
});
}
function formatStamp(el) {
var epoch = parseFloat(el.getAttribute('data-epoch'));
if (isNaN(epoch)) return;
el.textContent = new Date(1000 * epoch).toLocaleString(undefined, el.classList.contains('datestamp') ? DAY : FULL);
}
function isStamp(el) {
return el.classList.contains('timestamp') || el.classList.contains('datestamp');
}
stash(content);
/* ---------- Patching ---------- */
function flash(el) {
if (!el || el.nodeType !== 1) return;
el.classList.remove('live-flash');
void el.offsetWidth;
el.classList.add('live-flash');
setTimeout(function () { el.classList.remove('live-flash'); }, 1500);
}
function protectedNode(node) {
return node.nodeType === 1 && node.matches(PROTECT);
}
function kids(el) {
return Array.prototype.filter.call(el.childNodes, function (child) {
if (child.nodeType === 3) return child.nodeValue.trim() !== '';
return child.nodeType === 1 && !protectedNode(child);
});
}
function same(a, b) {
if (a.nodeType !== b.nodeType) return false;
return a.nodeType !== 1 || a.tagName === b.tagName;
}
function syncAttributes(o, n) {
var i, attr;
for (i = 0; i < n.attributes.length; i++) {
attr = n.attributes[i];
if (attr.name === 'class') continue;
if (o.getAttribute(attr.name) !== attr.value) o.setAttribute(attr.name, attr.value);
}
for (i = o.attributes.length - 1; i >= 0; i--) {
attr = o.attributes[i];
if (attr.name === 'class' || KEEP[attr.name]) continue;
if (!n.hasAttribute(attr.name)) o.removeAttribute(attr.name);
}
// Classes come from the server, except the highlight this script adds
var wanted = (n.getAttribute('class') || '') + (o.classList.contains('live-flash') ? ' live-flash' : '');
if ((o.getAttribute('class') || '') !== wanted) {
if (wanted.trim()) o.setAttribute('class', wanted);
else o.removeAttribute('class');
}
}
function patchNode(o, n) {
if (o.nodeType === 3) {
if (o.nodeValue !== n.nodeValue) {
o.nodeValue = n.nodeValue;
flash(o.parentNode);
}
return;
}
if (o.nodeType !== 1 || protectedNode(o)) return;
if (isStamp(o)) {
if (o.getAttribute('data-epoch') !== n.getAttribute('data-epoch')) {
var fresh = document.importNode(n, true);
formatStamp(fresh);
o.parentNode.replaceChild(fresh, o);
flash(fresh);
}
return;
}
syncAttributes(o, n);
patchChildren(o, n);
}
/* Children are matched from both ends, and only what is left in the
middle is replaced. A row that appears, or a button that disappears,
leaves the rest of its parent untouched. */
function patchChildren(oldEl, newEl) {
var o = kids(oldEl), n = kids(newEl);
var start = 0, oe = o.length, ne = n.length, i;
while (start < oe && start < ne && same(o[start], n[start])) {
patchNode(o[start], n[start]);
start++;
}
while (oe > start && ne > start && same(o[oe - 1], n[ne - 1])) {
oe--; ne--;
patchNode(o[oe], n[ne]);
}
if (start === oe && start === ne) return;
var before = o[oe] || null;
for (i = start; i < oe; i++) oldEl.removeChild(o[i]);
for (i = start; i < ne; i++) {
var node = document.importNode(n[i], true);
if (node.nodeType === 1) {
Array.prototype.forEach.call(node.querySelectorAll('.timestamp, .datestamp'), formatStamp);
if (isStamp(node)) formatStamp(node);
}
oldEl.insertBefore(node, before);
flash(node.nodeType === 1 ? node : oldEl);
}
}
// ux.js makes whole rows clickable once, when the page loads
function restoreRows() {
Array.prototype.forEach.call(content.querySelectorAll('table.test-list tbody tr'), function (row) {
var link = row.querySelector('.col-test a');
if (link && !row.getAttribute('data-href')) row.setAttribute('data-href', link.getAttribute('href'));
});
}
function apply(html) {
var doc = new DOMParser().parseFromString(html, 'text/html');
var fresh = doc.getElementById('content');
if (!fresh) return false;
stash(fresh);
patchChildren(content, fresh);
restoreRows();
return true;
}
/* ---------- The indicator ---------- */
var pill = document.createElement('button');
pill.type = 'button';
pill.id = 'live-indicator';
pill.className = 'live-pill';
pill.innerHTML = '<span class="live-dot" aria-hidden="true"></span><span class="live-text">Live</span>';
document.body.appendChild(pill);
var enabled = true;
try { enabled = window.localStorage.getItem('ob:live') !== 'off'; } catch (error) { /* storage unavailable */ }
var timer = null, busy = false, failures = 0, last = Date.now(), dead = false;
function setState(state) {
var label = { live: 'Live', paused: 'Paused', retry: 'Reconnecting' }[state];
pill.setAttribute('data-state', state);
pill.setAttribute('aria-pressed', String(enabled));
pill.querySelector('.live-text').textContent = label;
pill.title = state === 'paused'
? 'Automatic updates are off. Click to turn them on.'
: 'Updated ' + new Date(last).toLocaleTimeString() + '. Click to pause.';
}
/* ---------- Polling ---------- */
function interval() {
var path = window.location.pathname, base = 10000;
if (/^\/(test|tune|datagen)\//.test(path)) base = document.querySelector('.page-head .fa-spin') ? 8000 : 45000;
else if (/^\/(events|errors)/.test(path)) base = 20000;
return base * Math.pow(2, Math.min(failures, 3));
}
// Leave the page alone while somebody is reading, selecting or typing
function occupied() {
var selection = window.getSelection && window.getSelection();
if (selection && !selection.isCollapsed && selection.anchorNode && content.contains(selection.anchorNode)) return true;
var focused = document.activeElement;
if (focused && content.contains(focused) && /^(INPUT|TEXTAREA|SELECT)$/.test(focused.tagName)) return true;
var palette = document.getElementById('palette');
return !!(palette && !palette.hidden);
}
function schedule(delay) {
clearTimeout(timer);
if (!enabled || dead || document.hidden) return;
timer = setTimeout(tick, delay === undefined ? interval() : delay);
}
function tick() {
if (document.hidden) return;
if (occupied()) { schedule(3000); return; }
poll();
}
function strip(path) { return path.replace(/\/+$/, ''); }
function poll() {
if (busy) return;
busy = true;
var path = window.location.pathname;
fetch(window.location.pathname + window.location.search, {
credentials : 'same-origin',
cache : 'no-store',
headers : { 'Accept': 'text/html' }
})
.then(function (response) {
// Sent somewhere else ( a login page, or another kind of workload ): stop quietly
if (response.redirected && strip(new URL(response.url).pathname) !== strip(path)) {
dead = true;
throw new Error('moved');
}
if (!response.ok) throw new Error('status ' + response.status);
return response.text();
})
.then(function (html) {
if (!apply(html)) throw new Error('no content');
failures = 0;
last = Date.now();
setState('live');
})
.catch(function () {
failures++;
if (dead) pill.hidden = true;
else setState('retry');
})
.then(function () {
busy = false;
schedule();
});
}
pill.addEventListener('click', function () {
enabled = !enabled;
try { window.localStorage.setItem('ob:live', enabled ? 'on' : 'off'); } catch (error) { /* ignore */ }
if (enabled) { setState('live'); poll(); }
else { clearTimeout(timer); setState('paused'); }
});
document.addEventListener('visibilitychange', function () {
if (document.hidden) { clearTimeout(timer); return; }
if (!enabled || dead) return;
// Coming back to the tab: catch up at once, unless it was just done
if (Date.now() - last > 4000) poll();
else schedule();
});
setState(enabled ? 'live' : 'paused');
schedule();
})();