Something went wrong. Try again.
Browser extension: detect and subscribe to standard.site publications on ATProto substandard.blog
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523// Sign-in and subscribe controls for panoptiblog.//// Logged out, this draws a "sign in" button and its note, and nothing else. The// OAuth client lives in a separate chunk (panoptiblog-oauth.js), imported only// when the reader asks to sign in, when the URL is an OAuth redirect back to// this page, or when an earlier visit left a session behind.//// The ranked rows belong to panoptiblog.js. It marks each row with its// publication at-uri in data-publication and fires `panoptiblog:rows` after// every redraw; this module adds the subscribe controls to whatever is shown.
import { accountLink, accountNote, accountSeparator, accountSummary, accountWho, signInAccount,} from "../../../src/lib/signin";import { followCount, followSummary, indexSubscriptions, isOAuthCallback, isSessionGone,} from "./panoptiblog-follow.js";import { isRanked, shareHref, sharePath } from "./panoptiblog-lookup.js";import { loadLookup } from "./panoptiblog-lookup-data.js";import { announceViewer } from "./panoptiblog-viewer.js";
// Set while this browser holds a session, so a logged-out visit can skip the// OAuth chunk entirely. A stale hint only costs one restore that finds nothing.const HINT_KEY = "panoptiblog.session";const RESUME_TIMEOUT_MS = 20_000;// A tab coming back into view re-reads the records, so a change made in the// extension or another tab shows up, but not more often than this.const REFRESH_AFTER_MS = 60_000;
const host = document.getElementById("panoptiblog-account");const list = document.getElementById("panoptiblog-publications");
const state = { phase: "out", notice: "", formHandle: "", formError: "", account: undefined, handle: "", /** publication at-uri -> record keys, once read. */ subscriptions: undefined, loadedAt: 0, loadFailed: false, /** Bumped by every write, so a read that started before one is not trusted. */ writes: 0, pending: new Set(), failed: new Set(), /** The top-100 rows and total, for the signed-in share control. */ publications: [], rankedTotal: 0,};
document.addEventListener("panoptiblog:data", (event) => { state.publications = Array.isArray(event.detail?.publications) ? event.detail.publications : []; state.rankedTotal = Number(event.detail?.rankedTotal ?? 0); renderAccount();});
function make(tag, className, text) { const node = document.createElement(tag); if (className) node.className = className; if (text !== undefined) node.textContent = text; return node;}
function readHint() { try { return localStorage.getItem(HINT_KEY) !== null; } catch { return false; }}
function writeHint(did) { try { if (did) localStorage.setItem(HINT_KEY, did); else localStorage.removeItem(HINT_KEY); } catch { // Blocked storage only means the next visit starts logged out. }}
let oauthModule;
function loadOAuth() { oauthModule ??= import("./panoptiblog-oauth.js").then( (oauth) => { oauth.onSessionDeleted((sub) => { if (state.account?.did === sub) expire("session expired"); }); return oauth; }, (err) => { oauthModule = undefined; throw err; }, ); return oauthModule;}
// --- rows ------------------------------------------------------------------
function shownRows() { return list ? Array.from(list.querySelectorAll(".lb-row[data-publication]")) : [];}
function signedInWithList() { return state.phase === "in" && state.subscriptions instanceof Map;}
function isSubscribed(uri) { return (state.subscriptions?.get(uri)?.length ?? 0) > 0;}
function decorateRows() { const active = signedInWithList(); for (const row of shownRows()) { const uri = row.dataset.publication; const subscribed = active && isSubscribed(uri); row.classList.toggle("is-subscribed", subscribed); let mark = row.querySelector(".lb-subscribed"); let control = row.querySelector(".lb-follow"); if (!active) { mark?.remove(); control?.remove(); continue; }
if (subscribed && !mark) { mark = make("span", "lb-subscribed", "subscribed"); row.querySelector(".lb-name-line")?.append(mark); } else if (!subscribed) { mark?.remove(); }
if (!control) { control = make("button", "lb-follow"); control.type = "button"; const debug = row.querySelector(".lb-debug"); if (debug) debug.before(control); else row.querySelector(".lb-meta-line")?.append(control); } const pending = state.pending.has(uri); const failed = state.failed.has(uri); const name = row.querySelector(".lb-name")?.textContent || "this publication"; // aria-disabled, not disabled: a disabled button drops keyboard focus, // and toggle() already ignores a click while one is saving. control.setAttribute("aria-disabled", String(pending)); control.textContent = pending ? "saving" : subscribed ? "unsubscribe" : "subscribe"; control.classList.toggle("is-failed", failed); control.title = failed ? "That did not save. Try again." : ""; control.setAttribute( "aria-label", `${subscribed ? "Unsubscribe from" : "Subscribe to"} ${name}${failed ? " (the last try did not save)" : ""}`, ); }}
async function toggle(uri) { const account = state.account; if (!account || !signedInWithList() || state.pending.has(uri)) return; state.pending.add(uri); state.failed.delete(uri); state.writes++; decorateRows(); try { const rkeys = state.subscriptions.get(uri) ?? []; if (rkeys.length === 0) { const rkey = await account.subscribe(uri); state.subscriptions.set(uri, [rkey]); console.debug("[panoptiblog] subscribed", uri, rkey); } else { // Duplicates are all deleted, one at a time, so a failure part-way // leaves the map naming exactly the records that are still there. for (const rkey of [...rkeys]) { await account.unsubscribe(rkey); const left = (state.subscriptions.get(uri) ?? []).filter((key) => key !== rkey); if (left.length > 0) state.subscriptions.set(uri, left); else state.subscriptions.delete(uri); } console.debug("[panoptiblog] unsubscribed", uri, rkeys); } } catch (err) { if (state.account !== account) return; if (isSessionGone(err)) { expire("session expired"); return; } console.warn("[panoptiblog] subscription change did not save", uri, err); state.failed.add(uri); } finally { state.pending.delete(uri); } if (state.account !== account) return; decorateRows(); refreshSummary();}
list?.addEventListener("click", (event) => { const control = event.target instanceof Element ? event.target.closest(".lb-follow") : null; const uri = control?.closest(".lb-row")?.dataset.publication; if (uri) void toggle(uri);});
// --- header ----------------------------------------------------------------
function summaryText() { if (state.loadFailed) return "subscriptions could not be loaded"; if (!(state.subscriptions instanceof Map)) return "loading subscriptions"; const shown = shownRows().map((row) => row.dataset.publication); return followSummary(followCount(state.subscriptions, shown));}
function refreshSummary() { const node = host?.querySelector(".signin-account-summary"); if (node) node.textContent = summaryText();}
const CALLOUT = "add more subs! read new blogs!";
function accountOptions(open) { return { open, callout: CALLOUT, initialHandle: state.formHandle, error: state.formError, onOpen: openForm, onChange: (handle) => { state.formHandle = handle; }, onSubmit: (handle) => void startSignIn(handle), onCancel: () => { state.phase = "out"; state.formError = ""; render(); }, idPrefix: "panoptiblog", };}
/** The account's best-ranked publication, or undefined. */function bestPublication(rows, did) { return rows .filter( (pub) => pub?.did === did && isRanked(pub) && Number.isFinite(Number(pub.rank)), ) .sort((a, b) => Number(a.rank) - Number(b.rank))[0];}
function openFinder(query) { document.dispatchEvent( new CustomEvent("panoptiblog:find", { detail: { query } }), );}
async function shareMine(button) { const did = state.account?.did; if (!did) return; const known = bestPublication(state.publications, did); const knownHref = known ? shareHref({ ...known, path: sharePath(known.uri) }, state.rankedTotal) : undefined; if (knownHref) { window.open(knownHref, "_blank", "noopener"); return; } // Outside the top 100, the lookup dataset has every ranked publication. const win = window.open("", "_blank"); if (win) win.opener = null; const label = button.textContent; button.disabled = true; button.textContent = "finding your publication…"; try { const data = await loadLookup(); const mine = bestPublication(data.publications, did); const href = mine ? shareHref(mine, data.totals?.rankedPublications) : undefined; if (href) { if (win) win.location.href = href; else location.assign(href); } else { win?.close(); openFinder(state.handle || did); } } catch { win?.close(); openFinder(state.handle || did); } finally { button.disabled = false; button.textContent = label; }}
function shareControl() { const button = make("button", "pano-share-action", "share my publication"); button.type = "button"; button.addEventListener("click", () => void shareMine(button)); return button;}
function renderAccount() { if (!host) return; // A redraw replaces the focused control. Focus moves to the control with // the same label in the new rail, or its first one. const focused = host.contains(document.activeElement) ? document.activeElement : undefined; const label = focused?.textContent?.trim(); const nodes = []; if (state.phase === "form") { nodes.push(signInAccount(accountOptions(true))); } else if (state.phase === "resuming" || state.phase === "redirecting") { nodes.push(accountNote("signing in…")); } else if (state.phase === "in") { const identity = make("div", "pano-account-row"); identity.append( accountWho(state.handle ? `@${state.handle}` : state.account.did), shareControl(), ); nodes.push(identity, accountSeparator(), accountSummary(summaryText())); if (state.loadFailed) { nodes.push(accountLink("retry", () => void loadSubscriptions())); } nodes.push(accountSeparator(), accountLink("sign out", signOut)); } else { // Signed out only: the note is an invitation to sign in, so it goes when // the button does. nodes.push(signInAccount(accountOptions(false))); if (state.notice) nodes.push(accountNote(state.notice)); } host.replaceChildren(...nodes); if (focused && !host.contains(document.activeElement)) { const controls = [...host.querySelectorAll("button, input")]; const same = label ? controls.find((control) => control.textContent.trim() === label) : undefined; (same ?? controls[0])?.focus({ preventScroll: true }); }}
function render() { renderAccount(); decorateRows();}
// --- session ---------------------------------------------------------------
function openForm() { state.phase = "form"; state.notice = ""; render(); host?.querySelector("input")?.focus();}
async function startSignIn(value) { const handle = value.trim().replace(/^@/, ""); state.formHandle = handle; if (!handle) { state.formError = "enter your handle"; render(); host?.querySelector("input")?.focus(); return; } state.phase = "redirecting"; state.formError = ""; render(); try { const oauth = await loadOAuth(); await oauth.signIn(handle); } catch (err) { // The client rejects with this when the reader comes back from the // authorization server with the browser's back button. const back = err instanceof Error && err.message === "User navigated back"; if (!back) console.warn("[panoptiblog] could not start sign-in", err); state.phase = "form"; state.formError = back ? "" : "could not start sign-in for that handle"; render(); }}
function adopt(account) { state.account = account; state.phase = "in"; state.notice = ""; state.handle = ""; state.subscriptions = undefined; state.loadFailed = false; writeHint(account.did); announceViewer({ did: account.did }); console.debug("[panoptiblog] signed in", account.did); render(); void loadSubscriptions(); account .handle() .then((handle) => { if (state.account !== account || !handle) return; state.handle = handle; announceViewer({ did: account.did, handle }); renderAccount(); }) .catch((err) => { if (state.account === account && isSessionGone(err)) expire("session expired"); else console.debug("[panoptiblog] could not read the handle", err); });}
function expire(notice) { if (state.account) console.debug("[panoptiblog] session ended", notice || "signed out"); state.account = undefined; state.subscriptions = undefined; state.loadFailed = false; state.pending.clear(); state.failed.clear(); state.phase = "out"; state.notice = notice; state.handle = ""; writeHint(undefined); announceViewer(undefined); render();}
function signOut() { const did = state.account?.did; expire(""); if (!did) return; loadOAuth() .then((oauth) => oauth.signOut(did)) .catch((err) => console.debug("[panoptiblog] revoke failed; the session is dropped here anyway", err));}
async function loadSubscriptions() { const account = state.account; if (!account) return; state.loadFailed = false; refreshSummary(); const writes = state.writes; try { const records = await account.subscriptions(); if (state.account !== account) return; if (state.writes !== writes && state.subscriptions instanceof Map) return; state.subscriptions = indexSubscriptions(records); state.loadedAt = Date.now(); } catch (err) { if (state.account !== account) return; if (isSessionGone(err)) { expire("session expired"); return; } console.warn("[panoptiblog] could not read subscriptions", err); // Keep an earlier list if there is one: it is still the best answer. if (!(state.subscriptions instanceof Map)) state.loadFailed = true; } render();}
async function resume() { const callback = isOAuthCallback(location.hash); if (!callback && !readHint()) { render(); return; } state.phase = "resuming"; render(); const timer = setTimeout(() => { if (state.phase !== "resuming") return; state.phase = "out"; state.notice = "could not reach your account"; render(); }, RESUME_TIMEOUT_MS); try { const oauth = await loadOAuth(); const account = await oauth.resume(); if (account) { adopt(account); return; } writeHint(undefined); state.notice = ""; } catch (err) { console.warn("[panoptiblog] could not restore the session", err); if (isSessionGone(err)) { writeHint(undefined); state.notice = "session expired"; } else { state.notice = callback ? "sign-in did not finish" : "could not reach your account"; } } finally { clearTimeout(timer); } if (state.phase === "resuming" || state.phase === "out") { state.phase = "out"; render(); }}
document.addEventListener("panoptiblog:rows", () => { decorateRows(); refreshSummary();});
document.addEventListener("visibilitychange", () => { if (document.visibilityState !== "visible" || !signedInWithList()) return; if (state.pending.size > 0 || Date.now() - state.loadedAt < REFRESH_AFTER_MS) return; void loadSubscriptions();});
void resume();