// /panoptiblog's renderer. // // The page is static and the dataset is not: the scheduled job replaces // /panoptiblog/data.json, and this script draws it. Records are third-party // data, so every value reaches the DOM through textContent, and a link is only // a link when its URL parses as http or https. // // This is an external module on purpose. The site's CSP allows scripts from // 'self' plus one hashed inline snippet; an inline page script would need its // hash added to the CSP on every change, and would silently do nothing in // production when someone forgot. import { sankey, sankeyLeft, sankeyLinkHorizontal } from "d3-sankey"; const DATA_URL = "/panoptiblog/data.json"; const WEIGHTS_KEY = "panoptiblog.weights"; // A row carries its publication at-uri for panoptiblog-account.js, which adds // the subscribe controls after every redraw announced by ROWS_EVENT. const PUBLICATION_URI = /^at:\/\/did:[a-z0-9]+:[^/]+\/site\.standard\.publication\/[^/?#]+$/; const ROWS_EVENT = "panoptiblog:rows"; const compact = new Intl.NumberFormat("en", { notation: "compact", maximumFractionDigits: 1, }); const exact = new Intl.NumberFormat("en"); const day = new Intl.DateTimeFormat("en", { dateStyle: "medium", timeZone: "UTC", }); const EXCLUSION_ORDER = [ "no-posts", "below-minimum-words", "undiscoverable", "language", "spam", "other", ]; const EXCLUSION_LABELS = { "no-posts": "no posts", "below-minimum-words": "below minimum words", undiscoverable: "undiscoverable", language: "not English", spam: "spam", other: "other", }; const FILTER_FALLBACKS = { "no-posts": "The publication has no posts.", "below-minimum-words": "The publication is below the minimum word count.", undiscoverable: "The publication could not be discovered through the network.", language: "The publication is not English; it is indexed but not scored yet.", spam: "The publication matched the spam checks below.", other: "The publication was excluded for another reason.", }; const state = { publications: [], tree: [], cohort: [], factorIds: [], weights: {}, rankedCount: 0, sortKey: "overall", defaultWeights: null, defaultPositions: null, }; function text(value) { return value === undefined || value === null ? "" : String(value); } function make(tag, className) { const node = document.createElement(tag); if (className) node.className = className; return node; } // Line icons for the score-tree categories. Each entry is a list of SVG child // elements and their attributes; the wrapper carries the shared stroke style. const ICONS = { eye: [ ["path", { d: "M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12Z" }], ["circle", { cx: "12", cy: "12", r: "3" }], ], reach: [ ["circle", { cx: "12", cy: "12", r: "1.5" }], ["path", { d: "M8.5 8.5a5 5 0 0 0 0 7" }], ["path", { d: "M5.5 5.5a9 9 0 0 0 0 13" }], ["path", { d: "M15.5 8.5a5 5 0 0 1 0 7" }], ["path", { d: "M18.5 5.5a9 9 0 0 1 0 13" }], ], output: [ ["path", { d: "M12 3 3 8l9 5 9-5-9-5Z" }], ["path", { d: "m3 12 9 5 9-5" }], ["path", { d: "m3 16 9 5 9-5" }], ], longevity: [ ["path", { d: "M6 3h12" }], ["path", { d: "M6 21h12" }], ["path", { d: "M7 3v4l5 5 5-5V3" }], ["path", { d: "M7 21v-4l5-5 5 5v4" }], ], voice: [ ["path", { d: "M20 4c-6 1-11 6-13 12l-2 4 4-2c6-2 11-7 11-14Z" }], ["path", { d: "M5 19c4-4 8-8 12-12" }], ], pulse: [["path", { d: "M2 12h4l3-8 4 16 3-8h6" }]], evidence: [ ["path", { d: "M10 13a5 5 0 0 0 7 0l2-2a5 5 0 0 0-7-7l-1 1" }], ["path", { d: "M14 11a5 5 0 0 0-7 0l-2 2a5 5 0 0 0 7 7l1-1" }], ], variety: [ ["path", { d: "M12 4c-4 0-7 3-7 7 0 2 .5 4 1.5 5.5" }], ["path", { d: "M19 11c0-4-3-7-7-7" }], ["path", { d: "M9 11c0-1.5 1.5-3 3-3s3 1.5 3 3c0 3-1 6-2 8" }], ["path", { d: "M9 18c.5-2 1-4 1-7" }], ], fallback: [["circle", { cx: "12", cy: "12", r: "7" }]], }; function iconSvg(name) { const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); svg.setAttribute("viewBox", "0 0 24 24"); svg.setAttribute("width", "16"); svg.setAttribute("height", "16"); svg.setAttribute("fill", "none"); svg.setAttribute("stroke", "currentColor"); svg.setAttribute("stroke-width", "1.8"); svg.setAttribute("stroke-linecap", "round"); svg.setAttribute("stroke-linejoin", "round"); svg.setAttribute("aria-hidden", "true"); for (const [tag, attributes] of ICONS[name] ?? ICONS.fallback) { const node = document.createElementNS("http://www.w3.org/2000/svg", tag); for (const [key, value] of Object.entries(attributes)) node.setAttribute(key, value); svg.append(node); } return svg; } let tipSequence = 0; /** An ⓘ button with the exact definition beside it, on hover or focus. */ function infoTip(detail, label) { if (!detail) return undefined; const wrap = make("span", "info-wrap"); const button = document.createElement("button"); button.type = "button"; button.className = "info-button"; button.textContent = "i"; button.setAttribute("aria-label", `What ${label} measures`); const tip = make("span", "info-tip"); tip.id = `panoptiblog-tip-${tipSequence++}`; tip.setAttribute("role", "tooltip"); tip.textContent = detail; button.setAttribute("aria-describedby", tip.id); wrap.append(button, tip); return wrap; } function cssColor(value) { return typeof value === "string" && /^rgb\([^)]*\)$/.test(value) ? value : undefined; } function httpUrl(value) { try { const url = new URL(value); return url.protocol === "http:" || url.protocol === "https:" ? url.toString() : undefined; } catch { return undefined; } } function truncate(value, limit) { const clean = text(value).replace(/\s+/g, " ").trim(); return clean.length > limit ? `${clean.slice(0, limit - 1).trimEnd()}…` : clean; } function readingTime(minutes) { const value = Number(minutes); if (!Number.isFinite(value) || value <= 0) return "0 min"; if (value < 60) return `${Math.round(value)} min`; const hours = Math.floor(value / 60); const remainder = Math.round(value % 60); return remainder > 0 ? `${hours}h ${remainder}m` : `${hours}h`; } const hoursFormat = new Intl.NumberFormat("en", { minimumFractionDigits: 1, maximumFractionDigits: 1, }); function hours(value) { return `${hoursFormat.format(Number(value ?? 0))} h`; } /** Total reading hours, as a span of one-hour nights; empty under an hour. */ function bedtimeReading(totalHours) { const nights = Number(totalHours ?? 0); if (!(nights >= 1)) return ""; const units = [ ["year", 365.25], ["month", 30.44], ["night", 1], ]; const [unit, size] = units.find(([, length]) => nights >= length * 1.5) ?? units[2]; const count = Math.round(nights / size); return `At an hour a night, that's ${count} ${unit}${count === 1 ? "" : "s"} of bedtime reading.`; } function percent(value) { return `${(Number(value ?? 0) * 100).toFixed(1)}%`; } function pill(value) { const span = document.createElement("span"); span.className = "panoptiblog-pill"; span.textContent = value; return span; } function statItem(label, value) { const item = make("div"); const dt = document.createElement("dt"); dt.textContent = label; const dd = document.createElement("dd"); dd.textContent = value; item.append(dt, dd); return item; } function subhead(value) { const h = make("h3", "dialog-subhead"); h.textContent = value; return h; } function sideHead(value) { const h = make("h3", "pano-side-head"); h.textContent = value; return h; } function ordinal(value) { const number = Math.round(Number(value)); if (!Number.isFinite(number)) return ""; const mod100 = number % 100; if (mod100 >= 11 && mod100 <= 13) return `${number}th`; if (number % 10 === 1) return `${number}st`; if (number % 10 === 2) return `${number}nd`; if (number % 10 === 3) return `${number}rd`; return `${number}th`; } function percentileLabel(value) { return Number.isFinite(value) ? ordinal(value) : "—"; } function profileLink(handle, did) { const key = text(handle) || text(did); return key ? `https://bsky.app/profile/${encodeURIComponent(key)}` : undefined; } function authorLine(pub) { const author = pub.author ?? {}; const handle = text(author.handle) || text(pub.handle); const did = text(author.did) || text(pub.did); const name = text(author.displayName) || handle || did || "unknown author"; const wrap = make("div", "lb-author"); const avatar = make("span", "lb-avatar"); const initial = Array.from(name.trim())[0]?.toUpperCase() ?? "?"; avatar.textContent = initial; const avatarUrl = httpUrl(author.avatar); if (avatarUrl) { const img = document.createElement("img"); img.src = avatarUrl; img.alt = ""; img.loading = "lazy"; img.referrerPolicy = "no-referrer"; img.addEventListener("error", () => img.remove()); avatar.append(img); } const body = make("span", "lb-author-body"); const nameNode = make("span", "lb-author-name"); nameNode.textContent = name; const handleNode = make("span", "lb-author-handle"); handleNode.textContent = handle ? `@${handle}` : ""; const link = profileLink(handle, did); if (link) { const anchor = document.createElement("a"); anchor.href = link; anchor.rel = "noopener noreferrer"; anchor.append(nameNode, handleNode); body.append(anchor); } else { body.append(nameNode, handleNode); } wrap.append(avatar, body); return wrap; } function percentileOf(value, sorted) { if (!Number.isFinite(value) || sorted.length === 0) return null; if (value === 0) return 0; let low = 0; let high = sorted.length; while (low < high) { const mid = (low + high) >> 1; if (sorted[mid] < value) low = mid + 1; else high = mid; } const less = low; high = sorted.length; while (low < high) { const mid = (low + high) >> 1; if (sorted[mid] <= value) low = mid + 1; else high = mid; } const equal = low - less; return (100 * (less + 0.5 * equal)) / sorted.length; } function cohortEntry(row) { const factors = {}; state.factorIds.forEach((id, index) => { factors[id] = row.f?.[index]; }); return { factors, warnings: Number(row.w) || 0 }; } function compositeViews(entries, weights = state.weights) { const views = new Map( entries.map((entry) => [entry, { categories: {}, rawCategories: {}, overallRaw: null }]), ); if (state.cohort.length === 0) { // Older snapshots do not carry cohort vectors. Their stored composite // percentiles are still full-cohort values, so show those rather than // inventing a top-100 cohort. for (const entry of entries) { for (const category of state.tree) { views.get(entry).categories[category.id] = entry.row.composites?.[category.id]?.percentile ?? null; views.get(entry).rawCategories[category.id] = entry.row.composites?.[category.id]?.raw ?? null; } views.get(entry).overall = Number.isFinite(entry.row.percentile) ? entry.row.percentile : null; views.get(entry).overallRaw = Number.isFinite(entry.row.score) ? entry.row.score : null; } return views; } const cohort = state.cohort.map(cohortEntry); for (const category of state.tree) { const raw = cohort .map((row) => categoryScore(row, category, weights)) .filter(Number.isFinite) .sort((a, b) => a - b); for (const entry of entries) { const score = categoryScore(entry.row, category, weights); views.get(entry).rawCategories[category.id] = score; views.get(entry).categories[category.id] = percentileOf(score, raw); } } const overall = cohort .map((row) => { let total = 0; let weight = 0; for (const category of state.tree) { const categoryWeight = weights[category.id]?.weight ?? 0; if (!(categoryWeight > 0)) continue; const score = categoryScore(row, category, weights); if (score === null) continue; total += categoryWeight * score; weight += categoryWeight; } if (weight === 0) return null; return Math.max(0, total / weight - 5 * row.warnings); }) .filter(Number.isFinite) .sort((a, b) => a - b); for (const entry of entries) { views.get(entry).overall = percentileOf(entry.score, overall); views.get(entry).overallRaw = entry.score; } return views; } function leaderboardRow(pub, rank, view, total, awards, move) { const row = make("article", "lb-row"); row.setAttribute("role", "listitem"); if (PUBLICATION_URI.test(text(pub.uri))) row.dataset.publication = pub.uri; row.style.setProperty("--blog-accent", cssColor(pub.theme?.accent) ?? "var(--red)"); const accent = make("span", "lb-accent"); accent.setAttribute("aria-hidden", "true"); row.append(accent); const rankNode = make("span", "lb-rank"); rankNode.textContent = `#${rank}`; row.append(rankNode); const identity = make("div", "lb-identity"); const iconBox = make("div", "lb-icon"); const fallback = make("span", "lb-initial"); fallback.textContent = Array.from(text(pub.name).trim())[0]?.toUpperCase() ?? "?"; iconBox.append(fallback); const icon = httpUrl(pub.icon); if (icon) { const img = document.createElement("img"); img.src = icon; img.alt = ""; img.loading = "lazy"; img.referrerPolicy = "no-referrer"; img.addEventListener("error", () => img.remove()); iconBox.append(img); } const textBox = make("div", "lb-text"); const nameLine = make("div", "lb-name-line"); const url = httpUrl(pub.url); const name = make(url ? "a" : "span", "lb-name"); name.textContent = text(pub.name) || "untitled publication"; if (url) { name.href = url; name.rel = "noopener noreferrer"; } nameLine.append(name); if (move) { const marker = make("span", `lb-move ${move.delta > 0 ? "is-up" : "is-down"}`); marker.title = move.label; const glyph = make("span", "lb-move-glyph"); glyph.setAttribute("aria-hidden", "true"); glyph.textContent = `${move.delta > 0 ? "▲" : "▼"}${Math.abs(move.delta)}`; const spoken = make("span", "visually-hidden"); spoken.textContent = move.label; marker.append(glyph, spoken); nameLine.append(marker); } textBox.append(nameLine, authorLine(pub)); const meta = make("div", "lb-meta"); meta.textContent = `${compact.format(pub.wordCount ?? 0)} words · ${compact.format(pub.docCount ?? 0)} posts · ${readingTime(pub.readingMinutes)}`; const details = make("button", "lb-debug"); details.type = "button"; details.textContent = "details"; details.setAttribute( "aria-label", `Show details for ${text(pub.name) || "this publication"}`, ); details.addEventListener("click", () => { const uri = text(pub.uri); if (PUBLICATION_URI.test(uri)) setPubHash(uri); openDebug(pub, details); }); const metaLine = make("div", "lb-meta-line"); metaLine.append(meta, details); textBox.append(metaLine); identity.append(iconBox, textBox); row.append(identity); const composites = make("div", "lb-composites"); for (const category of state.tree) { const value = view?.categories?.[category.id]; const raw = view?.rawCategories?.[category.id]; const display = Number.isFinite(Number(raw)) ? Number(raw).toFixed(1) : "—"; const card = make("div", "lb-composite"); card.title = `${text(category.name)}: ${display} score, ${percentileLabel(value)} percentile. ${text(category.detail)}`; card.setAttribute( "aria-label", `${text(category.name)}: ${display} score, ${percentileLabel(value)} percentile. ${text(category.detail)}`, ); const top = make("div", "lb-composite-top"); top.append(iconSvg(category.icon)); const label = make("span"); label.textContent = text(category.name) || text(category.id); top.append(label); const valueLine = make("div", "lb-composite-value-line"); const number = make("strong", "lb-composite-value"); number.textContent = display; valueLine.append(number); const place = awards?.[category.id]; if (place) { const award = make("span", "lb-award"); award.dataset.place = String(place); award.textContent = String(place); award.title = `Top ${place} ${text(category.name) || text(category.id)} score in the top 100`; award.setAttribute("role", "img"); award.setAttribute( "aria-label", `Rank ${place} for ${text(category.name) || text(category.id)}`, ); valueLine.append(award); } const bar = make("span", "lb-bar"); const fill = make("i"); fill.style.width = `${Number.isFinite(raw) ? Math.max(0, Math.min(100, raw)) : 0}%`; bar.append(fill); card.append(top, valueLine, bar); composites.append(card); } row.append(composites); const overall = make("div", "lb-overall"); const caption = make("span", "lb-overall-label"); caption.textContent = "overall"; const value = make("strong", "lb-overall-value"); const display = Number.isFinite(Number(view?.overallRaw)) ? Number(view.overallRaw).toFixed(1) : "—"; value.textContent = display; const note = make("span", "lb-overall-note"); note.textContent = "score"; const percentile = percentileLabel(view?.overall); overall.title = `Rank #${exact.format(rank)} of ${exact.format(total)} ranked publications; ${percentile} percentile`; overall.setAttribute( "aria-label", `Overall score ${display} of 100; ${percentile} percentile; rank ${rank} of ${exact.format(total)}`, ); overall.append(caption, value, note); row.append(overall); return row; } function publicationEmpty(message) { const p = make("p", "pub-empty"); p.textContent = message; return p; } function sortBy(key) { state.sortKey = key; updateRankings(); } /** * Column labels for the wide list, where each row drops its per-card labels. * The six composites and overall are sort buttons; the active one carries the * red pen mark. */ function leaderboardHead() { const head = make("div", "lb-head"); const rank = make("span", "lb-head-rank"); rank.textContent = "#"; const publication = make("span", "lb-head-pub"); publication.textContent = "publication"; head.append(rank, publication); for (const category of state.tree) { const label = make("button", "lb-head-cat lb-head-sort"); label.type = "button"; label.title = `Sort by ${text(category.name) || text(category.id)} score. ${text(category.detail)}`; label.setAttribute("aria-pressed", String(state.sortKey === category.id)); const name = make("span"); name.textContent = text(category.name) || text(category.id); label.append(iconSvg(category.icon), name); label.addEventListener("click", () => sortBy(category.id)); head.append(label); } const overall = make("button", "lb-head-overall lb-head-sort"); overall.type = "button"; overall.textContent = "overall"; overall.title = "Sort by overall score"; overall.setAttribute("aria-pressed", String(state.sortKey === "overall")); overall.addEventListener("click", () => sortBy("overall")); head.append(overall); return head; } function renderPublications(entries, defaultPositions) { const host = document.getElementById("panoptiblog-publications"); if (!host) return; if (entries.length === 0) { host.replaceChildren(publicationEmpty("no ranked publications yet")); } else { if (state.sortKey !== "overall" && !state.tree.some((c) => c.id === state.sortKey)) { state.sortKey = "overall"; } const views = compositeViews(entries); const awards = new Map(); for (const category of state.tree) { const leaders = entries .map((entry) => ({ entry, score: views.get(entry).rawCategories?.[category.id] })) .filter((row) => Number.isFinite(row.score)) .sort( (a, b) => b.score - a.score || b.entry.score - a.entry.score || a.entry.key.localeCompare(b.entry.key), ) .slice(0, 3); leaders.forEach(({ entry }, index) => { const places = awards.get(entry) ?? {}; places[category.id] = index + 1; awards.set(entry, places); }); } const overallRank = new Map(entries.map((entry, index) => [entry, index + 1])); const value = (entry) => state.sortKey === "overall" ? entry.score : views.get(entry).rawCategories?.[state.sortKey]; const sorted = [...entries].sort((a, b) => { const left = Number.isFinite(value(a)) ? value(a) : -Infinity; const right = Number.isFinite(value(b)) ? value(b) : -Infinity; if (left !== right) return right - left; if (b.score !== a.score) return b.score - a.score; return a.key.localeCompare(b.key); }); const rows = make("div", "lb-rows"); rows.setAttribute("role", "list"); rows.append( ...sorted.map((entry) => { const rank = overallRank.get(entry) ?? 1; const from = defaultPositions?.get(entry.row); const delta = from === undefined ? 0 : from - rank; return leaderboardRow( entry.row, rank, views.get(entry), state.rankedCount || entries.length, awards.get(entry), delta === 0 ? undefined : { delta, label: movementLabel(delta) }, ); }), ); host.replaceChildren(leaderboardHead(), rows); } document.dispatchEvent(new CustomEvent(ROWS_EVENT)); } function perThousand(value, population) { const amount = Number(value); const count = Number(population); return Number.isFinite(amount) && Number.isFinite(count) && count > 0 ? (amount / count) * 1000 : undefined; } function renderEcosystem(ecosystem) { const statsHost = document.getElementById("panoptiblog-ecosystem-stats"); const activityHost = document.getElementById("panoptiblog-ecosystem-activity"); const humanHost = document.getElementById("panoptiblog-ecosystem-human"); const writingHost = document.getElementById("panoptiblog-writing"); if (!statsHost || !activityHost || !writingHost) return; if (!ecosystem) { statsHost.replaceChildren(); activityHost.replaceChildren(); if (humanHost) humanHost.textContent = ""; writingHost.replaceChildren(); return; } const reading = ecosystem.reading ?? {}; const headline = statItem("written in the last day", hours(reading.hoursLast24h)); headline.className = "side-stat-lead"; statsHost.replaceChildren( headline, statItem("daily this month", hours(reading.hoursPerDay30d)), statItem("to read every post", hours(reading.hoursTotal)), ); activityHost.replaceChildren( statItem("blogs that posted this month", exact.format(reading.activePublications30d ?? 0)), statItem("posts a day", Number(reading.postsPerDay30d ?? 0).toFixed(1)), ); if (humanHost) humanHost.textContent = bedtimeReading(reading.hoursTotal); writingHost.replaceChildren( statItem( "median school grade", Number(ecosystem.readability?.fleschKincaid ?? 0).toFixed(1), ), statItem( "median reading ease", Number(ecosystem.readability?.fleschReadingEase ?? 0).toFixed(1), ), statItem("median word variety", Number(ecosystem.lexical?.mtld ?? 0).toFixed(1)), ); } function relativeAge(at) { const hours = (Date.now() - at.getTime()) / 3_600_000; if (!Number.isFinite(hours) || hours < 1) return "just now"; if (hours < 24) return `${Math.floor(hours)}h ago`; const days = Math.floor(hours / 24); return `${days} day${days === 1 ? "" : "s"} ago`; } function renderUpdated(generatedAt) { const host = document.getElementById("panoptiblog-updated"); if (!host) return; const at = new Date(generatedAt); if (Number.isNaN(at.valueOf())) { host.textContent = "unknown update"; return; } const time = make("time"); time.dateTime = at.toISOString(); time.textContent = `updated ${day.format(at)}`; host.replaceChildren(time, ` · ${relativeAge(at)}`); if (Date.now() - at.getTime() > 36 * 3_600_000) { const stale = make("span", "pano-stale"); stale.textContent = "stale"; stale.title = "The daily refresh is overdue; rankings and recency scores may be out of date."; host.append(" ", stale); } } // --- weights ------------------------------------------------------------- function clampPercent(value) { const number = Number(value); if (!Number.isFinite(number)) return 0; return Math.min(100, Math.max(0, Math.round(number))); } function defaultWeights() { const weights = {}; for (const category of state.tree) { weights[category.id] = { weight: clampPercent(Number(category.weight ?? 0) * 100), factors: {}, }; for (const factor of category.factors ?? []) { weights[category.id].factors[factor.id] = clampPercent(Number(factor.weight ?? 0) * 100); } } return weights; } function loadWeights(fallback) { let saved; try { const raw = localStorage.getItem(WEIGHTS_KEY); if (!raw) return fallback; saved = JSON.parse(raw); } catch { return fallback; } const categories = saved?.categories; if (!categories || typeof categories !== "object") return fallback; for (const [id, category] of Object.entries(fallback)) { const stored = categories[id]; if (!stored || typeof stored !== "object") continue; if (Number.isFinite(stored.weight)) category.weight = clampPercent(stored.weight); for (const factorId of Object.keys(category.factors)) { if (Number.isFinite(stored.factors?.[factorId])) { category.factors[factorId] = clampPercent(stored.factors[factorId]); } } } return fallback; } function saveWeights() { try { localStorage.setItem( WEIGHTS_KEY, JSON.stringify({ version: 1, categories: state.weights }), ); } catch { // Storage can be full or blocked; the page keeps working either way. } } // Sliders in the quick and full editors share a sync key, so moving either // one updates its twin. Each control carries its own reader because a reset // swaps state.weights for a fresh object. const weightControls = { quick: new Map(), full: new Map() }; function registerWeightControl(owner, syncKey, control) { const controls = weightControls[owner].get(syncKey) ?? []; controls.push(control); weightControls[owner].set(syncKey, controls); } function syncWeightControl(syncKey, value) { for (const controls of Object.values(weightControls)) { for (const control of controls.get(syncKey) ?? []) { control.input.value = String(value); control.output.textContent = `${value}%`; } } } function syncWeightInputs() { for (const controls of Object.values(weightControls)) { for (const list of controls.values()) { for (const control of list) { const value = control.read(); control.input.value = String(value); control.output.textContent = `${value}%`; } } } } function sameWeights(left, right) { const ids = Object.keys(left); if (ids.length !== Object.keys(right).length) return false; for (const id of ids) { if (!right[id] || left[id].weight !== right[id].weight) return false; const factorIds = Object.keys(left[id].factors ?? {}); if (factorIds.length !== Object.keys(right[id].factors ?? {}).length) return false; for (const factorId of factorIds) { if ((left[id].factors?.[factorId] ?? 0) !== (right[id].factors?.[factorId] ?? 0)) { return false; } } } return true; } function hasCustomWeights() { return !sameWeights(state.weights, state.defaultWeights ?? defaultWeights()); } function setCategoryWeight(categoryId, value) { state.weights[categoryId].weight = value; syncWeightControl(`category:${categoryId}`, value); saveWeights(); scheduleRankings(); announceRankingsUpdated(); } function setFactorWeight(categoryId, factorId, value) { state.weights[categoryId].factors[factorId] = value; syncWeightControl(`factor:${categoryId}:${factorId}`, value); saveWeights(); scheduleRankings(); announceRankingsUpdated(); } function resetWeights() { state.weights = structuredClone(state.defaultWeights ?? defaultWeights()); try { localStorage.removeItem(WEIGHTS_KEY); } catch { // Nothing to clear if storage is unavailable. } syncWeightInputs(); updateRankings(); } function availableFactors() { const available = new Set(); for (const row of state.publications) { for (const [id, value] of Object.entries(row.factors ?? {})) { if (Number.isFinite(value)) available.add(id); } } return available; } /** * A category averages the factor percentiles the row actually has. Zero or * missing factor weights are renormalised away, so absent model factors do * not drag a score down. */ function categoryScore(row, category, weights = state.weights) { const factors = weights[category.id]?.factors ?? {}; let total = 0; let weight = 0; for (const factor of category.factors ?? []) { const factorWeight = factors[factor.id] ?? 0; const value = row.factors?.[factor.id]; if (!(factorWeight > 0) || !Number.isFinite(value)) continue; total += factorWeight * value; weight += factorWeight; } return weight > 0 ? total / weight : null; } function recomputedScore(row, kind, weights = state.weights) { if (state.tree.length === 0) { return Number.isFinite(row.score) ? Number(row.score) : null; } let total = 0; let weight = 0; for (const category of state.tree) { const categoryWeight = weights[category.id]?.weight ?? 0; if (!(categoryWeight > 0)) continue; const score = categoryScore(row, category, weights); if (score === null) continue; total += categoryWeight * score; weight += categoryWeight; } if (weight === 0) return null; let score = total / weight; if (kind === "publication") { const reasons = Array.isArray(row.spam?.reasons) ? row.spam.reasons.length : 0; score = Math.max(0, score - 5 * reasons); } return score; } function ranked(items, kind, weights = state.weights) { return items .map((row) => ({ row, score: recomputedScore(row, kind, weights), key: text(row.uri ?? row.did), })) .sort((a, b) => { const left = a.score === null ? -Infinity : a.score; const right = b.score === null ? -Infinity : b.score; if (left !== right) return right - left; const words = (b.row.wordCount ?? 0) - (a.row.wordCount ?? 0); if (words !== 0) return words; return a.key.localeCompare(b.key); }); } function defaultRankPositions(weights = state.defaultWeights ?? defaultWeights()) { const positions = new Map(); ranked(state.publications, "publication", weights).forEach((entry, index) => { positions.set(entry.row, index + 1); }); return positions; } function movementLabel(delta) { const places = Math.abs(delta); return `${delta > 0 ? "up" : "down"} ${places} ${places === 1 ? "place" : "places"} from the default ranking`; } function updateRankings() { const custom = hasCustomWeights(); renderPublications( ranked(state.publications, "publication"), custom ? state.defaultPositions ?? defaultRankPositions() : undefined, ); const notice = document.getElementById("panoptiblog-weights-notice"); if (notice) notice.hidden = !custom; } let rankingsFrame = 0; function scheduleRankings() { if (rankingsFrame) return; rankingsFrame = requestAnimationFrame(() => { rankingsFrame = 0; updateRankings(); }); } const STATUS_DEBOUNCE_MS = 500; let statusTimer = 0; /** One status line after the reader stops moving a weight slider. */ function announceRankingsUpdated() { window.clearTimeout(statusTimer); const status = document.getElementById("panoptiblog-status"); if (status) status.textContent = ""; statusTimer = window.setTimeout(() => { if (status) status.textContent = "rankings updated"; }, STATUS_DEBOUNCE_MS); } let sliderSequence = 0; function sliderRow({ label, value, disabled, suffix, className, detail, onInput, owner, syncKey, read, }) { const wrap = make("div", className); const labelBox = make("div", "weight-label"); const labelNode = make("label"); labelNode.textContent = label; if (suffix) { const note = make("span", "weight-not-run"); note.textContent = ` ${suffix}`; labelNode.append(note); } const nameLine = make("div", "weight-name-line"); nameLine.append(labelNode); const tip = infoTip(detail, label); if (tip) nameLine.append(tip); const output = make("output", "weight-value"); output.textContent = `${value}%`; labelBox.append(nameLine, output); const input = document.createElement("input"); input.type = "range"; input.min = "0"; input.max = "100"; input.step = "1"; input.value = String(value); input.disabled = Boolean(disabled); input.setAttribute("aria-valuetext", `${value} percent`); input.title = detail ? `${label}: ${detail}` : label; input.id = `panoptiblog-weight-${sliderSequence++}`; labelNode.htmlFor = input.id; input.addEventListener("input", () => { const next = clampPercent(input.value); output.textContent = `${next}%`; input.setAttribute("aria-valuetext", `${next} percent`); onInput(next); }); if (owner && syncKey && read) { registerWeightControl(owner, syncKey, { input, output, read }); } wrap.append(labelBox, input); return wrap; } /** * Columns for the category cards on a wide screen: three or four, whichever * leaves the last row least empty. Six makes 3+3, seven 4+3, nine 3x3. */ function weightColumns(count) { if (count <= 4) return Math.max(1, count); const gap = (columns) => (columns - (count % columns)) % columns; return gap(4) <= gap(3) ? 4 : 3; } function renderWeightEditor() { const host = document.getElementById("panoptiblog-weights"); if (!host) return; weightControls.full.clear(); if (state.tree.length === 0) { const note = make("p", "panoptiblog-note"); note.textContent = "This snapshot has no weight tree; rankings use their published scores."; host.replaceChildren(note); return; } sliderSequence = 0; tipSequence = 0; const available = availableFactors(); const groups = make("div", "weight-groups"); groups.dataset.columns = String(weightColumns(state.tree.length)); const root = make("div", "weight-root"); const rootBody = make("div", "weight-root-body"); const rootLine = make("div", "weight-name-line"); const rootName = make("span", "weight-name"); rootName.textContent = "overall score"; rootLine.append(iconSvg("eye"), rootName); const rootTip = infoTip( "The ranking shown in the tables. A weighted average of every category; each category weight is its share of 100%.", "the overall score", ); if (rootTip) rootLine.append(rootTip); const rootVibe = make("p", "weight-vibe"); rootVibe.textContent = "One number from six signals. Move any slider to test another view."; rootBody.append(rootLine, rootVibe); const rootValue = make("span", "weight-root-value"); rootValue.textContent = "100%"; root.append(rootBody, rootValue); for (const category of state.tree) { const categoryName = text(category.name) || text(category.id); const group = make("fieldset", "weight-group"); const legend = document.createElement("legend"); const legendLine = make("span", "weight-name-line"); const name = make("span", "weight-name"); name.textContent = categoryName; legendLine.append(iconSvg(category.icon), name); const categoryTip = infoTip(category.detail, categoryName); if (categoryTip) legendLine.append(categoryTip); legend.append(legendLine); group.append(legend); const vibe = make("p", "weight-vibe"); vibe.textContent = text(category.vibe); if (vibe.textContent) group.append(vibe); group.append( sliderRow({ label: `${categoryName} weight`, value: state.weights[category.id]?.weight ?? 0, className: "weight-row is-category", detail: `The category's weight in the overall score. The categories start at 100% in total; the overall score renormalises the sum.`, owner: "full", syncKey: `category:${category.id}`, read: () => state.weights[category.id]?.weight ?? 0, onInput: (value) => setCategoryWeight(category.id, value), }), ); for (const factor of category.factors ?? []) { const hasFactor = available.has(factor.id); group.append( sliderRow({ label: text(factor.name) || text(factor.id), value: state.weights[category.id]?.factors?.[factor.id] ?? 0, disabled: !hasFactor, suffix: hasFactor ? undefined : "(not run)", className: "weight-row is-factor", detail: factor.detail, owner: "full", syncKey: `factor:${category.id}:${factor.id}`, read: () => state.weights[category.id]?.factors?.[factor.id] ?? 0, onInput: (value) => setFactorWeight(category.id, factor.id, value), }), ); } groups.append(group); } const reset = make("button", "weight-reset"); reset.type = "button"; reset.textContent = "reset weights"; reset.addEventListener("click", resetWeights); host.replaceChildren(root, groups, reset); } function renderQuickWeights() { const details = document.getElementById("panoptiblog-tune"); const host = document.getElementById("panoptiblog-quick-weights"); if (!details || !host) return; weightControls.quick.clear(); if (state.tree.length === 0) { details.hidden = true; host.replaceChildren(); return; } details.hidden = false; const list = make("div", "quick-weight-list"); for (const category of state.tree) { list.append( sliderRow({ label: text(category.name) || text(category.id), value: state.weights[category.id]?.weight ?? 0, className: "weight-row quick-weight", owner: "quick", syncKey: `category:${category.id}`, read: () => state.weights[category.id]?.weight ?? 0, onInput: (value) => setCategoryWeight(category.id, value), }), ); } host.replaceChildren(list); } // --- filter guideline ---------------------------------------------------- function fallbackUniverse(totals) { const included = Number(totals.rankedPublications ?? 0); const excludedTotal = Number( totals.unrankedPublications ?? Math.max(0, Number(totals.publications ?? 0) - included), ); const excluded = { "no-posts": Number(totals.emptyPublications ?? 0), "below-minimum-words": Number(totals.belowMinimumWordsPublications ?? 0), undiscoverable: Number(totals.undiscoverablePublications ?? 0), spam: Number(totals.spamExcludedPublications ?? 0), }; const known = Object.values(excluded).reduce((sum, count) => sum + count, 0); excluded.other = Math.max(0, excludedTotal - known); return { included, excluded, excludedTotal, spamReasons: {}, legacy: true }; } function countList(entries, descriptions) { const list = make("ul", "dialog-list"); for (const [key, count] of entries) { const item = document.createElement("li"); const detail = make("div", "dialog-item"); const name = make("span", "dialog-name"); name.textContent = EXCLUSION_LABELS[key] ?? key; const description = make("span", "dialog-desc"); description.textContent = descriptions[key] ?? "Excluded from the ranking."; detail.append(name, description); const value = make("span", "dialog-count"); value.textContent = exact.format(count ?? 0); item.append(detail, value); list.append(item); } return list; } function svgEl(tag, attrs = {}) { const node = document.createElementNS("http://www.w3.org/2000/svg", tag); for (const [key, value] of Object.entries(attrs)) node.setAttribute(key, String(value)); return node; } function sankeyLabel(svg, x, y, value, className) { const node = svgEl("text", { x, y, class: className }); node.textContent = value; svg.append(node); } /** A left-to-right Sankey: crawled -> indexed -> ranked/scored -> shown. */ function corpusFunnel(data, universe, excluded) { const crawled = Number(data.totals?.publications ?? 0); const ranked = Number(universe.included ?? data.totals?.rankedPublications ?? 0); const shown = Array.isArray(data.publications) ? data.publications.length : 0; const spam = Number(excluded.spam ?? 0); const opted = Number(excluded.undiscoverable ?? 0); const language = Number(excluded.language ?? 0); const noPosts = Number(excluded["no-posts"] ?? 0); const below = Number(excluded["below-minimum-words"] ?? 0); const hard = spam + opted + language; const indexed = Math.max(0, crawled - hard); const notShown = Math.max(0, ranked - shown); const filters = [ ["spam", "spam", spam], ["opted", "opted out", opted], ["language", "not English", language], ]; const drops = [ ["no-posts", "no posts", noPosts], ["below", "under 1k words", below], ["not-shown", "not shown", notShown], ...filters, ]; const nodes = [ { id: "crawled", label: "crawled", count: crawled }, { id: "indexed", label: "indexed", count: indexed }, ...(hard > 0 ? [{ id: "hard", label: "hard filters", count: hard, group: true }] : []), { id: "ranked", label: "ranked & scored", count: ranked }, { id: "shown", label: "shown here", count: shown }, ...drops .filter(([, , count]) => count > 0) .map(([id, label, count]) => ({ id, label, count, drop: true })), ].map((node, order) => ({ ...node, order })); const links = [ ["crawled", "indexed", indexed], ...(hard > 0 ? [["crawled", "hard", hard]] : []), ...filters.map(([id, , count]) => ["hard", id, count]), ["indexed", "ranked", ranked], ["indexed", "no-posts", noPosts], ["indexed", "below", below], ["ranked", "shown", shown], ["ranked", "not-shown", notShown], ] .filter(([, , value]) => value > 0) .map(([source, target, value]) => ({ source, target, value })); const width = 960; const height = 520; const graph = sankey() .nodeId((node) => node.id) .nodeWidth(20) .nodePadding(30) .nodeAlign(sankeyLeft) .nodeSort((a, b) => a.order - b.order) .extent([ [110, 40], [820, 490], ])({ nodes, links }); const svg = svgEl("svg", { class: "pano-sankey", viewBox: `0 0 ${width} ${height}`, role: "img", "aria-labelledby": "pano-sankey-title", }); const title = svgEl("title", { id: "pano-sankey-title" }); title.textContent = `Crawled ${exact.format(crawled)} blogs; indexed ${exact.format(indexed)}; ranked and scored ${exact.format(ranked)}; shown here ${exact.format(shown)}`; const desc = svgEl("desc"); desc.textContent = "Flow widths are blog counts, and each percentage is that branch's share of its parent. Ink nodes stay in, red nodes drop out, and the gold node is the top 100 shown here."; svg.append(title, desc); const countOf = new Map(graph.nodes.map((node) => [node.id, node.count])); const childrenOf = new Map(); for (const link of graph.links) { const children = childrenOf.get(link.source.id) ?? []; children.push(link.target.id); childrenOf.set(link.source.id, children); } const shareOf = new Map(); for (const [parent, children] of childrenOf) { const total = countOf.get(parent) ?? 0; if (!total) continue; const shares = children.map((id) => ({ id, exact: ((countOf.get(id) ?? 0) / total) * 100, })); const places = shares.map((share) => ({ ...share, percent: Math.floor(share.exact), remainder: share.exact - Math.floor(share.exact), })); let left = 100 - places.reduce((sum, place) => sum + place.percent, 0); const byRemainder = [...places].sort((a, b) => b.remainder - a.remainder); for (let index = 0; left > 0; index += 1, left -= 1) { byRemainder[index % byRemainder.length].percent += 1; } for (const place of places) shareOf.set(place.id, place.percent); } const dropIds = new Set(["hard", ...drops.map(([id]) => id)]); for (const link of graph.links) { const path = svgEl("path", { d: sankeyLinkHorizontal()(link), "stroke-width": Math.max(1, link.width), class: link.target.id === "shown" ? "sankey-link-shown" : dropIds.has(link.target.id) ? "sankey-link-drop" : "sankey-link", }); const tip = svgEl("title"); tip.textContent = `${link.source.label} to ${link.target.label}: ${exact.format(link.value)}`; path.append(tip); svg.append(path); } for (const node of graph.nodes) { const rect = svgEl("rect", { x: node.x0, y: node.y0, width: node.x1 - node.x0, height: Math.max(2, node.y1 - node.y0), rx: 2, class: node.id === "shown" ? "sankey-node-shown" : node.group ? "sankey-node-group" : node.drop ? "sankey-node-drop" : "sankey-node", }); const tip = svgEl("title"); tip.textContent = `${node.label}: ${exact.format(node.count)} blogs`; rect.append(tip); svg.append(rect); const share = shareOf.get(node.id); const shareText = share === undefined ? "" : ` · ${share}%`; const onLeft = node.id === "crawled"; const label = svgEl("text", { x: onLeft ? node.x0 - 10 : node.x1 + 8, y: onLeft ? (node.y0 + node.y1) / 2 + 4 : node.y1 + 16, "text-anchor": onLeft ? "end" : "start", class: "sankey-node-label", }); const name = svgEl("tspan", { class: "sankey-node-name" }); name.textContent = node.label; const detail = svgEl("tspan", { class: "sankey-node-count" }); detail.textContent = ` ${exact.format(node.count)}${shareText}`; label.append(name, detail); svg.append(label); } const figure = make("figure", "pano-funnel"); const caption = make("figcaption", "pano-funnel-caption"); const kicker = make("span"); kicker.textContent = "from crawl to leaderboard"; const outcome = make("span", "pano-funnel-outcome"); outcome.textContent = `${exact.format(shown)} of ${exact.format(crawled)} shown`; caption.append(kicker, outcome); const scroller = make("div", "pano-sankey-scroll"); scroller.append(svg); const note = make("p", "dialog-note"); note.textContent = "Flow widths are blog counts; each percentage compares a branch with its parent. Ink stays in, red drops out, and gold is shown here."; figure.append(caption, scroller, note); return figure; } function renderIncluded(data) { const host = document.getElementById("panoptiblog-included-body"); if (!host) return; const totals = data.totals ?? {}; const universe = totals.universe ?? fallbackUniverse(totals); const filters = data.method?.filters ?? {}; const spamDescriptions = data.method?.spamReasons ?? {}; const excluded = universe.excluded ?? {}; const nodes = []; nodes.push(corpusFunnel(data, universe, excluded)); if (universe.legacy) { const note = make("p", "dialog-note"); note.textContent = "Older counters stand in for the exclusion breakdown and can overlap."; nodes.push(note); } const scope = make("p", "dialog-note"); scope.textContent = "The scored cohort is English-only for now: the readability and word-frequency tools are English-specific. A publication can opt out by setting preferences.showInDiscover to false."; nodes.push(scope); nodes.push(subhead("excluded publications")); const keys = [ ...EXCLUSION_ORDER, ...Object.keys(excluded).filter((key) => !EXCLUSION_ORDER.includes(key)), ].filter((key) => key in excluded); const descriptions = Object.fromEntries( keys.map((key) => [key, filters[key] ?? FILTER_FALLBACKS[key] ?? "Excluded from the ranking."]), ); nodes.push(countList(keys.map((key) => [key, excluded[key]]), descriptions)); nodes.push(subhead("spam reasons")); const spamCounts = universe.spamReasons ?? {}; const spamKeys = Object.keys(spamCounts); if (spamKeys.length > 0) { nodes.push( countList( spamKeys.map((key) => [key, spamCounts[key]]), spamDescriptions, ), ); } else if (Object.keys(spamDescriptions).length > 0) { const note = make("p", "dialog-note"); note.textContent = "Reason counts are not in this snapshot."; const list = make("ul", "dialog-list"); for (const [key, description] of Object.entries(spamDescriptions)) { const item = document.createElement("li"); const detail = make("div", "dialog-item"); const name = make("span", "dialog-name"); name.textContent = key; const explanation = make("span", "dialog-desc"); explanation.textContent = description; detail.append(name, explanation); item.append(detail); list.append(item); } nodes.push(note, list); } else { const note = make("p", "dialog-note"); note.textContent = "No spam reasons were recorded for this snapshot."; nodes.push(note); } nodes.push(subhead("network totals")); const network = make("dl", "stats dialog-stats"); network.append( statItem("skipped repositories", exact.format(totals.skippedRepositories ?? 0)), statItem("failed repositories", exact.format(totals.failures ?? 0)), statItem("loose documents", exact.format(totals.looseDocuments ?? 0)), statItem("orphan documents", exact.format(totals.orphanDocuments ?? 0)), ); nodes.push(network); const zero = make("p", "dialog-note"); zero.textContent = "Zero subscribers is not an exclusion; it scores zero on the subscriber factor."; nodes.push(zero); host.replaceChildren(...nodes); } function debugList(items) { const list = make("ul", "dialog-list"); for (const [label, value] of items) { const item = make("li"); const name = make("span", "dialog-name"); name.textContent = label; const count = make("span", "dialog-count dialog-value"); count.textContent = value; item.append(name, count); list.append(item); } return list; } function debugNumber(value, places = 2) { if (value === null || value === undefined || value === "") return "—"; return Number.isFinite(Number(value)) ? Number(value).toFixed(places) : "—"; } function debugPercent(value) { if (value === null || value === undefined || value === "") return "—"; return Number.isFinite(Number(value)) ? percent(value) : "—"; } function debugDate(value) { const time = Date.parse(value ?? ""); return Number.isFinite(time) ? day.format(time) : "—"; } /** A diagnostic group that stays folded until a reader asks for it. */ function debugDetails(summary, items) { const details = document.createElement("details"); details.className = "dialog-details"; const heading = document.createElement("summary"); heading.textContent = summary; details.append(heading, debugList(items)); return details; } // The details dialog's deep link names the publication by at-uri. Only the // #pub fragment belongs to this dialog, so closing it leaves any other // fragment alone. const PUB_HASH = "#pub="; function setPubHash(uri) { history.replaceState(history.state, "", `${PUB_HASH}${encodeURIComponent(uri)}`); } function clearPubHash() { if (!location.hash.startsWith(PUB_HASH)) return; const url = new URL(location.href); url.hash = ""; history.replaceState(history.state, "", url.href); } function publicationFromHash() { if (!location.hash.startsWith(PUB_HASH)) return undefined; let uri; try { uri = decodeURIComponent(location.hash.slice(PUB_HASH.length)); } catch { return undefined; } return state.publications.find((pub) => text(pub.uri) === uri); } let detailsOpener; function openDebug(pub, opener) { const dialog = document.getElementById("panoptiblog-debug"); const body = document.getElementById("panoptiblog-debug-body"); const title = document.getElementById("panoptiblog-debug-title"); if (!dialog || !body) return; if (title) title.textContent = text(pub.name) || "publication details"; detailsOpener = opener ?? document.getElementById("panoptiblog-debug-close"); const author = pub.author ?? {}; const diagnostics = pub.diagnostics ?? {}; const audience = diagnostics.audience ?? {}; const citations = diagnostics.citations ?? {}; const pulse = diagnostics.pulse ?? {}; const network = diagnostics.network ?? {}; const nodes = []; nodes.push(subhead("standing")); nodes.push(debugList([ ["overall raw", debugNumber(pub.score)], ["overall percentile", debugNumber(pub.percentile)], ["rank", pub.rank ? `#${exact.format(pub.rank)}` : "—"], ])); for (const category of state.tree) { nodes.push(subhead(`${text(category.name)} factors`)); nodes.push(debugList( (category.factors ?? []).map((factor) => [ text(factor.name), debugNumber(pub.factors?.[factor.id], 1), ]), )); } const note = make("p", "dialog-note"); note.textContent = "Factor values are percentiles. Bluesky engagement is not collected in this release."; nodes.push(note); nodes.push(subhead("identity")); nodes.push(debugList([ ["url", text(pub.url) || "—"], ["author", text(author.displayName) || text(author.handle) || "—"], ["handle", author.handle ? `@${author.handle}` : "—"], ["did", text(author.did) || text(pub.did) || "—"], ["language", text(pub.language) || "—"], ["discoverable", pub.discoverable === false ? "no" : "yes"], ["first post", debugDate(pub.firstPublishedAt)], ["last post", debugDate(pub.lastPublishedAt)], ])); nodes.push(subhead("raw counts")); nodes.push(debugList([ ["words", exact.format(pub.wordCount ?? 0)], ["posts", exact.format(pub.docCount ?? 0)], ["median words", exact.format(pub.medianWords ?? 0)], ["reading time", readingTime(pub.readingMinutes)], ["subscribers", exact.format(pub.subscribers ?? 0)], ["recommenders", exact.format(pub.recommends ?? 0)], ["inbound citations", exact.format(pub.inboundReferences ?? 0)], ["posts last 30d", exact.format(pub.postsLast30 ?? 0)], ["posts last 90d", exact.format(pub.postsLast90 ?? 0)], ])); nodes.push(debugDetails("audience diagnostics", [ ["new subscribers / 90d", exact.format(audience.newSubscribers90 ?? 0)], ["new recommenders / 90d", exact.format(audience.newRecommenders90 ?? 0)], ["median subscriber tenure", `${debugNumber(audience.medianSubscriberTenureDays, 1)} d`], ["endorsement breadth", debugPercent(audience.endorsementBreadth)], ["subscriber–recommender overlap", debugPercent(audience.subscriberRecommenderOverlap)], ])); nodes.push(debugDetails("citation diagnostics", [ ["recent citing sources / 90d", exact.format(citations.recentSources90 ?? 0)], ["citation months", exact.format(citations.citationMonths ?? 0)], ["citation persistence", debugPercent(citations.citationPersistence)], ["reciprocal share", debugPercent(citations.reciprocalShare)], ["PageRank impact", debugNumber(citations.impact, 6)], ["citation evenness", debugPercent(citations.evenness)], ])); nodes.push(debugDetails("pulse diagnostics", [ ["posting acceleration", debugNumber(pulse.acceleration)], ["words last 90d", exact.format(pulse.recentWords90 ?? 0)], ["words prior 90d", exact.format(pulse.priorWords90 ?? 0)], ])); nodes.push(debugDetails("network diagnostics", [ ["outbound / 1kw", debugNumber(network.outboundPer1000Words)], ["ecosystem / 1kw", debugNumber(network.ecosystemPer1000Words)], ["source mix", debugPercent(network.sourceMix)], ])); body.replaceChildren(...nodes); dialog.showModal(); } function setupFrame() { const frame = document.getElementById("panoptiblog-frame"); const account = document.getElementById("panoptiblog-account"); const heroSide = account?.parentElement; const notice = document.getElementById("panoptiblog-weights-notice"); const board = document.getElementById("panoptiblog-publications"); if (!frame || !account || !heroSide || !notice || !board) return; const root = document.documentElement; const noticeAnchor = document.createComment("weights notice"); notice.before(noticeAnchor); let active = false; let docked = false; let frameHeight = 0; let left; let width; let queued = false; const apply = () => { const hero = document.querySelector(".panoptiblog-hero"); const next = hero ? hero.getBoundingClientRect().bottom <= 0 : window.scrollY > 200; const rect = board.getBoundingClientRect(); // The frame spans the leaderboard's border box, so its sides sit on the // list's sides. if (next && (rect.left !== left || rect.width !== width)) { left = rect.left; width = rect.width; frame.style.setProperty("--pano-frame-left", `${left}px`); frame.style.setProperty("--pano-frame-width", `${width}px`); } if (next !== active) { active = next; if (active) { frame.append(account, notice); frame.hidden = false; } else { heroSide.append(account); noticeAnchor.parentNode?.insertBefore(notice, noticeAnchor.nextSibling); frame.hidden = true; } root.classList.toggle("has-frame", active); } // Docked while the list runs under the frame and its column header is // shown; the narrow layout has none to pin. const headHeight = board.querySelector(".lb-head")?.offsetHeight ?? 0; const nextDocked = active && headHeight > 0 && rect.top <= frameHeight && rect.bottom > frameHeight; if (nextDocked !== docked) { docked = nextDocked; root.classList.toggle("has-docked-frame", docked); } }; const update = () => { if (queued) return; queued = true; requestAnimationFrame(() => { queued = false; apply(); }); }; // The column header pins to the frame's measured bottom, so a frame that // wraps or grows a sign-in form never covers it. new ResizeObserver(([entry]) => { frameHeight = entry.borderBoxSize[0].blockSize; board.style.setProperty("--pano-frame-height", `${frameHeight}px`); update(); }).observe(frame); new ResizeObserver(update).observe(board); window.addEventListener("scroll", update, { passive: true }); window.addEventListener("resize", update); apply(); } function setupWeightsReset() { document .getElementById("panoptiblog-weights-reset") ?.addEventListener("click", resetWeights); document.getElementById("panoptiblog-weights-jump")?.addEventListener("click", () => { const tune = document.getElementById("panoptiblog-tune"); if (!tune) return; tune.open = true; tune.scrollIntoView({ behavior: "smooth", block: "start" }); tune.querySelector("input[type=range]")?.focus({ preventScroll: true }); }); } function setupDebugDialog() { const dialog = document.getElementById("panoptiblog-debug"); const close = document.getElementById("panoptiblog-debug-close"); if (!dialog) return; close?.addEventListener("click", () => dialog.close()); dialog.addEventListener("close", () => { clearPubHash(); if (detailsOpener?.isConnected) detailsOpener.focus(); detailsOpener = undefined; }); dialog.addEventListener("click", (event) => { if (event.target !== dialog) return; const rect = dialog.getBoundingClientRect(); const outside = event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom; if (outside) dialog.close(); }); } function setupIncludedDialog() { const dialog = document.getElementById("panoptiblog-included"); const open = document.getElementById("panoptiblog-included-open"); const close = document.getElementById("panoptiblog-included-close"); if (!dialog || !open) return; open.addEventListener("click", () => dialog.showModal()); close?.addEventListener("click", () => { dialog.close(); if (location.hash === "#included") { history.replaceState(null, "", location.pathname + location.search); } }); // Deep link for sharing the filter explanation. const sync = () => { if (location.hash === "#included" && !dialog.open) dialog.showModal(); }; window.addEventListener("hashchange", sync); sync(); dialog.addEventListener("click", (event) => { if (event.target !== dialog) return; const rect = dialog.getBoundingClientRect(); const outside = event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom; if (outside) dialog.close(); }); } // Sections drawn only from the dataset. They stay out of the way until a load // succeeds, so a failure never leaves an empty heading or a stale table. const DATASET_SECTIONS = [ "panoptiblog-method", "panoptiblog-sidebar", ]; function showDatasetSections(visible) { for (const id of DATASET_SECTIONS) { const node = document.getElementById(id); if (node) node.hidden = !visible; } } function failurePanel() { const panel = make("div", "pano-failure"); const message = make("p", "pano-failure-message"); message.textContent = "rankings are unavailable right now"; const actions = make("div", "pano-failure-actions"); const retry = make("button", "pano-retry"); retry.type = "button"; retry.textContent = "try again"; retry.addEventListener("click", () => { retry.disabled = true; retry.textContent = "retrying…"; load(); }); const link = document.createElement("a"); link.href = DATA_URL; link.textContent = "view the dataset"; actions.append(retry, link); panel.append(message, actions); return panel; } function failed() { showDatasetSections(false); const pubs = document.getElementById("panoptiblog-publications"); if (pubs) pubs.replaceChildren(failurePanel()); const updated = document.getElementById("panoptiblog-updated"); if (updated) updated.textContent = ""; const included = document.getElementById("panoptiblog-included-body"); if (included) { const note = make("p", "dialog-note"); note.textContent = "Filter counts are unavailable because the dataset could not be loaded."; included.replaceChildren(note); } const notice = document.getElementById("panoptiblog-weights-notice"); if (notice) notice.hidden = true; } async function main() { const response = await fetch(DATA_URL, { headers: { accept: "application/json" } }); if (!response.ok) throw new Error(`${response.status} ${response.statusText}`); const data = await response.json(); state.publications = Array.isArray(data.publications) ? data.publications : []; state.tree = Array.isArray(data.method?.tree?.categories) ? data.method.tree.categories : []; state.factorIds = state.tree.flatMap((category) => (category.factors ?? []).map((factor) => factor.id), ); state.cohort = Array.isArray(data.cohort) ? data.cohort : []; state.defaultWeights = defaultWeights(); state.weights = structuredClone(loadWeights(state.defaultWeights)); state.defaultPositions = defaultRankPositions(); state.rankedCount = Number(data.totals?.rankedPublications ?? state.cohort.length ?? 0); renderUpdated(data.generatedAt); renderEcosystem(data.totals?.ecosystem); renderIncluded(data); renderQuickWeights(); renderWeightEditor(); updateRankings(); const deepLinked = publicationFromHash(); if (deepLinked) { const uri = text(deepLinked.uri); const opener = [...document.querySelectorAll(".lb-row")] .find((row) => row.dataset.publication === uri) ?.querySelector(".lb-debug"); openDebug(deepLinked, opener); } showDatasetSections(true); } function load() { main().catch((error) => { console.error("[panoptiblog] could not load the dataset", error); failed(); }); } setupIncludedDialog(); setupDebugDialog(); setupWeightsReset(); setupFrame(); load();