4.5 KiB · text History 84bfe6e
// Live updates (src/live.rs). Signed-in pages carry
// <div id="live" hx-ext="ws" ws-connect="/ws"> outside #content; the htmx
// ws extension keeps it connected (reconnecting with jittered backoff after
// a drop) and swaps the server's #live-signal in: which categories have new
// activity the user can see. The lists on the page marked
//   data-live="latest"                                 (landing, /p/latest)
//   data-live="category" data-live-category="<id>"     (a category page)
// then refetch this page, as this user, through the ordinary route, and
// swap themselves for the fresh copy; rows that are new or moved up flash.
//
// Never under the reader, mid-typing, or while the list's top is scrolled
// past: then the fresh copy waits behind a "N new — show" pill.
//
// Popular sections poll on their own (hx-trigger="every 300s
// [window.livePollOk()]" in the templates); livePollOk is the condition.

import htmx from "htmx.org";
import "htmx-ext-ws";

const readerOpen = () => !!document.querySelector("#reader [data-reader]");

// Popular's periodic refresh: only for a visible tab with the reader shut.
window.livePollOk = () => document.visibilityState === "visible" && !readerOpen();

const typing = () => {
  const a = document.activeElement;
  return !!a && a.matches("input, textarea, select, [contenteditable], [contenteditable] *");
};

const busy = el => readerOpen() || typing() || el.getBoundingClientRect().top < 0;

// Lists waiting to be shown: element id -> { fresh copy, how many new }, for
// the page at `waitingFor`.
const waiting = new Map();
let waitingFor = location.href;

function ids(el) {
  return [...el.querySelectorAll("[data-topic]")].map(e => e.dataset.topic);
}

function swap(el, fresh) {
  const before = ids(el);
  const rank = new Map(before.map((id, i) => [id, i]));
  el.replaceWith(fresh);
  htmx.process(fresh);
  fresh.querySelectorAll("[data-topic]").forEach((row, i) => {
    const was = rank.get(row.dataset.topic);
    if (was === undefined || was > i) {
      row.classList.add("live-new");
      setTimeout(() => row.classList.remove("live-new"), 4000);
    }
  });
}

function pill() {
  let p = document.getElementById("live-pill");
  const n = [...waiting.values()].reduce((sum, w) => sum + w.added, 0);
  if (!waiting.size) {
    p?.remove();
    return;
  }
  if (!p) {
    p = document.createElement("button");
    p.id = "live-pill";
    p.type = "button";
    p.className = "btn btn-primary btn-sm shadow-lg fixed bottom-4 left-1/2 -translate-x-1/2 z-30";
    p.addEventListener("click", showWaiting);
    document.body.appendChild(p);
  }
  p.textContent = n > 0 ? `${n} new — show` : "Updated — show";
}

function showWaiting() {
  let first = null;
  for (const [id, w] of waiting) {
    const el = document.getElementById(id);
    if (el) {
      swap(el, w.fresh);
      first ??= w.fresh;
    }
  }
  waiting.clear();
  pill();
  first?.scrollIntoView({ block: "start", behavior: "smooth" });
}

let inflight = false;
let again = false;

async function refresh(targets) {
  if (inflight) {
    again = true;
    return;
  }
  inflight = true;
  try {
    const res = await fetch(location.href, { credentials: "same-origin", headers: { Accept: "text/html" } });
    if (!res.ok) return;
    const doc = new DOMParser().parseFromString(await res.text(), "text/html");
    for (const el of targets) {
      const fresh = doc.getElementById(el.id);
      if (!fresh || !el.isConnected) continue;
      if (busy(el)) {
        waitingFor = location.href;
        const have = new Set(ids(el));
        const added = ids(fresh).filter(id => !have.has(id)).length;
        waiting.set(el.id, { fresh, added });
      } else {
        waiting.delete(el.id);
        swap(el, fresh);
      }
    }
    pill();
  } catch (e) {
    console.debug("live refresh:", e);
  } finally {
    inflight = false;
    if (again) {
      again = false;
      onSignal();
    }
  }
}

function onSignal() {
  const signal = document.getElementById("live-signal");
  const cats = new Set((signal?.dataset.categories || "").split(" ").filter(Boolean));
  if (!cats.size) return;
  const targets = [...document.querySelectorAll("#content [data-live]")].filter(
    el => el.id && (el.dataset.live === "latest" || cats.has(el.dataset.liveCategory)),
  );
  if (targets.length) refresh(targets);
}

document.addEventListener("htmx:wsAfterMessage", onSignal);
// A new page: what was waiting belonged to the old one.
document.addEventListener("htmx:afterSettle", () => {
  if (waiting.size && location.href !== waitingFor) {
    waiting.clear();
    pill();
  }
});