// /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. const DATA_URL = "/panoptiblog/data.json"; const WEIGHTS_KEY = "panoptiblog.weights"; 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: {}, }; 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 cell(value, className) { const td = document.createElement("td"); td.textContent = text(value); if (className) td.className = className; return td; } 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`; } function hours(value) { return `${Number(value ?? 0).toFixed(1)} h`; } 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 row(cells) { const tr = document.createElement("tr"); tr.append(...cells); return tr; } function emptyRow(columns, message) { const tr = document.createElement("tr"); const td = document.createElement("td"); td.colSpan = columns; td.textContent = message; tr.append(td); return tr; } function fill(id, rows, columns, empty) { const body = document.getElementById(id); if (!body) return; body.replaceChildren(...(rows.length > 0 ? rows : [emptyRow(columns, empty)])); } function renderTotals(totals) { const host = document.getElementById("panoptiblog-totals"); if (!host) return; const entries = [ ["publications", exact.format(totals.rankedPublications ?? 0)], ["authors", exact.format(totals.authors ?? 0)], ["documents", exact.format(totals.documents ?? 0)], ["words", compact.format(totals.rankedWords ?? 0)], ["reading / day", hours(totals.ecosystem?.reading?.hoursLast24h ?? 0)], ]; host.replaceChildren( ...entries.map(([label, value]) => statItem(label, value)), ); } 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) { const views = new Map(entries.map((entry) => [entry, { categories: {} }])); 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).overall = Number.isFinite(entry.row.percentile) ? entry.row.percentile : null; } return views; } const cohort = state.cohort.map(cohortEntry); for (const category of state.tree) { const raw = cohort .map((row) => categoryScore(row, category)) .filter(Number.isFinite) .sort((a, b) => a - b); for (const entry of entries) { views.get(entry).categories[category.id] = percentileOf( categoryScore(entry.row, category), raw, ); } } const overall = cohort .map((row) => { let total = 0; let weight = 0; for (const category of state.tree) { const categoryWeight = state.weights[category.id]?.weight ?? 0; if (!(categoryWeight > 0)) continue; const score = categoryScore(row, category); 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); } return views; } function leaderboardRow(pub, rank, view) { const row = make("article", "lb-row"); 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 (pub.url) { let host = text(pub.url); try { host = new URL(pub.url).host || host; } catch { /* keep raw */ } const badge = make(url ? "a" : "span", "lb-host"); badge.textContent = host; if (url) { badge.href = url; badge.rel = "noopener noreferrer"; } nameLine.append(badge); } 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 debug = make("button", "lb-debug"); debug.type = "button"; debug.textContent = "debug"; debug.setAttribute("aria-label", `Show raw metrics for ${text(pub.name) || "this publication"}`); debug.addEventListener("click", () => openDebug(pub)); const metaLine = make("div", "lb-meta-line"); metaLine.append(meta, debug); 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 card = make("div", "lb-composite"); 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 number = make("strong", "lb-composite-value"); number.textContent = percentileLabel(value); const bar = make("span", "lb-bar"); const fill = make("i"); fill.style.width = `${Number.isFinite(value) ? Math.max(0, Math.min(100, value)) : 0}%`; bar.append(fill); card.append(top, number, 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"); value.textContent = percentileLabel(view?.overall); const note = make("span", "lb-overall-note"); note.textContent = "percentile"; 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 renderPublications(entries) { const host = document.getElementById("panoptiblog-publications"); if (!host) return; if (entries.length === 0) { host.replaceChildren(publicationEmpty("no ranked publications yet")); return; } const views = compositeViews(entries); host.replaceChildren( ...entries.map((entry, index) => leaderboardRow(entry.row, index + 1, views.get(entry))), ); } function renderTopics(topics) { fill( "panoptiblog-topics", topics.map((topic) => row([ cell(topic.tag), cell(exact.format(topic.documents ?? 0)), cell(exact.format(topic.publications ?? 0)), cell(exact.format(topic.words ?? 0)), ]), ), 4, "no topics yet", ); } function renderEcosystem(ecosystem) { const statsHost = document.getElementById("panoptiblog-ecosystem-stats"); const tableHost = document.getElementById("panoptiblog-ecosystem"); const baselineHost = document.getElementById("panoptiblog-baselines"); if (!statsHost || !tableHost || !baselineHost) return; if (!ecosystem) { statsHost.replaceChildren(); tableHost.replaceChildren(); baselineHost.replaceChildren(); return; } const reading = ecosystem.reading ?? {}; statsHost.replaceChildren( statItem("last 24 hours", hours(reading.hoursLast24h)), statItem("7-day average / day", hours(reading.hoursPerDay7d)), statItem("30-day average / day", hours(reading.hoursPerDay30d)), statItem("total reading", hours(reading.hoursTotal)), statItem("active publications / 30d", exact.format(reading.activePublications30d ?? 0)), statItem("posts / day", Number(reading.postsPerDay30d ?? 0).toFixed(1)), ); const rows = []; const add = (label, value) => { const tr = document.createElement("tr"); const th = document.createElement("th"); th.scope = "row"; th.textContent = label; tr.append(th, cell(value)); rows.push(tr); }; add("median reading grade", Number(ecosystem.readability?.fleschKincaid ?? 0).toFixed(1)); add("median reading ease", Number(ecosystem.readability?.fleschReadingEase ?? 0).toFixed(1)); add("median MTLD", Number(ecosystem.lexical?.mtld ?? 0).toFixed(1)); add( "external links / kiloword", Number(ecosystem.links?.externalPer1000Words ?? 0).toFixed(2), ); add("spam share", percent(reading.spamShare)); add("duplicate share", percent(reading.duplicateRatio)); add("new publications / 30d", exact.format(reading.newPublications30d ?? 0)); tableHost.replaceChildren(...rows); const nodes = []; if (ecosystem.health) { const health = make("div", "ecosystem-health"); const score = make("strong"); score.textContent = `${Number(ecosystem.health.score ?? 0).toFixed(1)} / 100`; const caption = make("span"); caption.textContent = ` ecosystem health vs ${text(ecosystem.health.baseline)}`; health.append(score, caption); nodes.push(health); const components = make("ul", "dialog-list"); for (const [key, value] of Object.entries(ecosystem.health.components ?? {})) { const item = document.createElement("li"); const name = make("span", "dialog-name"); name.textContent = key; const amount = make("span", "dialog-count"); amount.textContent = String(Math.round(Number(value ?? 0) * 100)); item.append(name, amount); components.append(item); } nodes.push(components); } if (ecosystem.comparison) { const baseline = ecosystem.comparison; const note = make("p", "panoptiblog-note"); note.textContent = `Baseline: ${text(baseline.name)}`; nodes.push(note); const table = document.createElement("table"); const thead = document.createElement("thead"); const headRow = document.createElement("tr"); for (const label of ["measure", "atproto", text(baseline.name)]) { const th = document.createElement("th"); th.scope = "col"; th.textContent = label; headRow.append(th); } thead.append(headRow); table.append(thead); const body = document.createElement("tbody"); const metrics = baseline.metrics ?? {}; const comparisons = [ [ "reading grade", ecosystem.readability?.fleschKincaid, metrics.readability?.fleschKincaid, ], [ "reading ease", ecosystem.readability?.fleschReadingEase, metrics.readability?.fleschReadingEase, ], ["MTLD", ecosystem.lexical?.mtld, metrics.lexical?.mtld], [ "external links / kiloword", ecosystem.links?.externalPer1000Words, metrics.links?.externalPer1000Words ?? metrics.links?.per1000Words, ], [ "reading hours / day", reading.hoursPerDay30d, metrics.reading?.hoursPerDay30d ?? metrics.reading?.hoursPerDay, ], ]; for (const [label, mine, theirs] of comparisons) { const tr = document.createElement("tr"); const th = document.createElement("th"); th.scope = "row"; th.textContent = label; tr.append( th, cell(Number.isFinite(Number(mine)) ? Number(mine).toFixed(1) : "—"), cell(Number.isFinite(Number(theirs)) ? Number(theirs).toFixed(1) : "—"), ); body.append(tr); } table.append(body); const scroll = make("div", "table-scroll"); scroll.append(table); nodes.push(scroll); } else { const note = make("p", "panoptiblog-note"); note.textContent = "No baseline corpus attached. Pass --baseline with documents or metrics to compare."; nodes.push(note); } baselineHost.replaceChildren(...nodes); } function renderUpdated(generatedAt) { const host = document.getElementById("panoptiblog-updated"); if (!host) return; const at = new Date(generatedAt); host.textContent = Number.isNaN(at.valueOf()) ? "unknown update" : `updated ${day.format(at)}`; } // --- 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. } } 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) { const weights = state.weights[category.id]?.factors ?? {}; let total = 0; let weight = 0; for (const factor of category.factors ?? []) { const factorWeight = weights[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) { 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 = state.weights[category.id]?.weight ?? 0; if (!(categoryWeight > 0)) continue; const score = categoryScore(row, category); 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) { return items .map((row) => ({ row, score: recomputedScore(row, kind), 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 updateRankings() { renderPublications(ranked(state.publications, "publication")); } let rankingsFrame = 0; function scheduleRankings() { if (rankingsFrame) return; rankingsFrame = requestAnimationFrame(() => { rankingsFrame = 0; updateRankings(); }); } let sliderSequence = 0; function sliderRow({ label, value, disabled, suffix, className, detail, onInput }) { 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.id = `panoptiblog-weight-${sliderSequence++}`; labelNode.htmlFor = input.id; input.addEventListener("input", () => { const next = clampPercent(input.value); output.textContent = `${next}%`; onInput(next); }); wrap.append(labelBox, input); return wrap; } function renderWeightEditor() { const host = document.getElementById("panoptiblog-weights"); if (!host) return; 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"); 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: "category 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.`, onInput: (value) => { state.weights[category.id].weight = value; saveWeights(); scheduleRankings(); }, }), ); 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, onInput: (value) => { state.weights[category.id].factors[factor.id] = value; saveWeights(); scheduleRankings(); }, }), ); } groups.append(group); } const reset = make("button", "weight-reset"); reset.type = "button"; reset.textContent = "reset weights"; reset.addEventListener("click", () => { state.weights = defaultWeights(); try { localStorage.removeItem(WEIGHTS_KEY); } catch { // Nothing to clear if storage is unavailable. } renderWeightEditor(); updateRankings(); }); host.replaceChildren(root, groups, reset); } // --- 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 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 excludedTotal = universe.excludedTotal ?? Object.values(excluded).reduce( (sum, count) => sum + (Number.isFinite(count) ? count : 0), 0, ); const nodes = []; const summary = make("dl", "stats dialog-stats"); summary.append( statItem("included publications", exact.format(universe.included ?? 0)), statItem("excluded publications", exact.format(excludedTotal)), ); nodes.push(summary); 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) : "—"; } function openDebug(pub) { 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 debug"; 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)}` : "—"], ])); 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(subhead("audience diagnostics")); nodes.push(debugList([ ["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(subhead("citation diagnostics")); nodes.push(debugList([ ["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(subhead("pulse diagnostics")); nodes.push(debugList([ ["posting acceleration", debugNumber(pulse.acceleration)], ["words last 90d", exact.format(pulse.recentWords90 ?? 0)], ["words prior 90d", exact.format(pulse.priorWords90 ?? 0)], ])); nodes.push(subhead("network diagnostics")); nodes.push(debugList([ ["outbound / 1kw", debugNumber(network.outboundPer1000Words)], ["ecosystem / 1kw", debugNumber(network.ecosystemPer1000Words)], ["source mix", debugPercent(network.sourceMix)], ])); 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); body.replaceChildren(...nodes); dialog.showModal(); } 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("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()); // Deep link for sharing the filter explanation. if (location.hash === "#included") dialog.showModal(); 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 failed() { const message = "rankings could not be loaded"; const pubs = document.getElementById("panoptiblog-publications"); if (pubs) pubs.replaceChildren(publicationEmpty(message)); fill("panoptiblog-topics", [], 4, message); const updated = document.getElementById("panoptiblog-updated"); if (updated) updated.textContent = message; for (const id of [ "panoptiblog-ecosystem-stats", "panoptiblog-ecosystem", "panoptiblog-baselines", ]) { const node = document.getElementById(id); if (node) node.replaceChildren(); } const included = document.getElementById("panoptiblog-included-body"); if (included) { const note = make("p", "dialog-note"); note.textContent = "filter counts could not be loaded"; included.replaceChildren(note); } } 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.weights = loadWeights(defaultWeights()); renderUpdated(data.generatedAt); renderTotals(data.totals ?? {}); renderEcosystem(data.totals?.ecosystem); renderIncluded(data); renderTopics(Array.isArray(data.topics) ? data.topics : []); renderWeightEditor(); updateRankings(); } setupIncludedDialog(); setupDebugDialog(); main().catch((error) => { console.error("[panoptiblog] could not load the dataset", error); failed(); });