// Marks the browser tab with a red dot on its favicon when new unread // articles have arrived since this page loaded — visible from a background // tab, unlike the in-page "new articles" banner. Runs on every // authenticated page; a full page load resets the baseline (and the icon), // which is exactly when the user has seen the new articles. (function () { var POLL_MS = 30000; var url = document.currentScript && document.currentScript.dataset.url; var icon = document.querySelector('link[rel="icon"]'); if (!url || !icon) return; var originalHref = icon.href; var baseline = null; var badged = null; // the dotted icon's data: URL, drawn once on first need var showing = false; function drawDot() { return new Promise(function (resolve) { var image = new Image(); image.onload = function () { var size = 64; var canvas = document.createElement("canvas"); canvas.width = canvas.height = size; var ctx = canvas.getContext("2d"); ctx.drawImage(image, 0, 0, size, size); ctx.beginPath(); ctx.arc(size * 0.74, size * 0.26, size * 0.23, 0, 2 * Math.PI); ctx.fillStyle = "#e53935"; ctx.fill(); ctx.lineWidth = size * 0.07; ctx.strokeStyle = "#ffffff"; ctx.stroke(); resolve(canvas.toDataURL("image/png")); }; image.onerror = function () { resolve(null); }; image.src = originalHref; }); } // Replace the rather than editing href: some browsers ignore an // in-place change to an existing favicon element. function setIcon(href) { var fresh = icon.cloneNode(); fresh.href = href; icon.parentNode.replaceChild(fresh, icon); icon = fresh; } function showDot(on) { if (on === showing) return Promise.resolve(); showing = on; if (!on) { setIcon(originalHref); return Promise.resolve(); } var ready = badged ? Promise.resolve(badged) : drawDot(); return ready.then(function (href) { badged = href; if (href && showing) setIcon(href); }); } function poll() { var query = baseline === null ? "" : "?since=" + baseline; fetch(url + query, { credentials: "same-origin", headers: { Accept: "application/json" } }) .then(function (response) { // A redirect means the session ended (we'd be reading the login // page) — stop polling instead of hammering it. if (!response.ok || response.redirected) throw new Error("stop"); return response.json(); }) .then(function (data) { if (baseline === null) baseline = data.latest_id; else showDot(data.new_count > 0); setTimeout(poll, POLL_MS); }) .catch(function (error) { if (error.message !== "stop") setTimeout(poll, POLL_MS); }); } poll(); })();