// A page whose #live element has data-live="N" is fetched again every N seconds // while it says so, and only the content is replaced (no reload, so the scroll // position and the log's place stay). A log that was at its end follows new text. (function () { function follow(root) { root.querySelectorAll("pre.log").forEach(function (pre) { pre.scrollTop = pre.scrollHeight; }); } var live = document.getElementById("live"); if (!live) return; follow(live); function poll() { var secs = parseInt(live.getAttribute("data-live"), 10); if (!secs) return; setTimeout(function () { fetch(location.pathname + location.search,{ credentials: "same-origin", headers: { "X-Live": "1" } }) .then(function (r) { // Sent elsewhere: the web UI restarted and forgot the session. Show where it leads. if (r.redirected) { location.reload(); return null; } if (!r.ok) throw new Error("not the page"); return r.text(); }) .then(function (html) { if (html === null) return; var next = new DOMParser().parseFromString(html, "text/html").getElementById("live"); if (!next) throw new Error("no content"); // Done: load the page whole, as it is when nothing is going on. if (!next.getAttribute("data-live")) { location.reload(); return; } var old = live.querySelector("pre.log"); var atEnd = !old || old.scrollTop + old.clientHeight >= old.scrollHeight - 8; var kept = old ? old.scrollTop : 0; live.innerHTML = next.innerHTML; if (next.getAttribute("data-live")) live.setAttribute("data-live", next.getAttribute("data-live")); else live.removeAttribute("data-live"); var pre = live.querySelector("pre.log"); if (pre) pre.scrollTop = atEnd ? pre.scrollHeight : kept; }) // The web UI restarts when an upgrade is switched on: keep trying. .catch(function () {}) .then(poll); }, secs * 1000); } poll(); })();