// /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"; import { categoryScore, defaultWeights, normalizeWeights, orderBy, rankPublications, treeScore, warnedScore, } from "./panoptiblog-rank.js"; import { displayHandle, sharePath } from "./panoptiblog-lookup.js"; import { clampPercent, displayShares, rebalanceVector, } from "./weight-shares.js"; 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", }); // The indexer files accounts that own a network of publications under spam, // with this reason. The page counts them apart: they are not spam. const BULK_REASON = "bulk-account"; const EXCLUSION_ORDER = [ "no-posts", "below-minimum-words", "undiscoverable", "language", BULK_REASON, "spam", "other", ]; const EXCLUSION_LABELS = { "no-posts": "no posts", "below-minimum-words": "below minimum words", undiscoverable: "undiscoverable", language: "not English", [BULK_REASON]: "bulk / network accounts", 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.", [BULK_REASON]: "The account owns a network of publications or a bulk documentation set.", spam: "The publication matched the spam checks below.", other: "The publication was excluded for another reason.", }; const FEEDBACK_URL = "https://tangled.org/permadeath.com/substandard/issues"; const CONTACT_EMAIL = "substandard@permadeath.com"; const state = { publications: [], tree: [], cohort: [], factorIds: [], weights: {}, rankedCount: 0, sortKey: "overall", defaultWeights: null, defaultPositions: null, previousGeneratedAt: undefined, }; function text(value) { return value === undefined || value === null ? "" : String(value); } function make(tag, className, content) { const node = document.createElement(tag); if (className) node.className = className; if (content !== undefined) node.textContent = content; 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; } /** Text for screen readers only, beside a visual that says it another way. */ function spoken(value) { const span = make("span", "visually-hidden"); span.textContent = value; return span; } /** Visible text that a screen reader skips, because `spoken` says it. */ function visualOnly(value, className) { const span = make("span", className); span.setAttribute("aria-hidden", "true"); span.textContent = value; return span; } 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 = displayHandle(author.handle) || displayHandle(pub.handle); const did = text(author.did) || text(pub.did); const displayName = text(author.displayName); const name = displayName || (handle ? `@${handle}` : did || "unknown author"); const wrap = make("div", "lb-author"); // The link names the author; the initial behind the picture is decoration. const avatar = make("span", "lb-avatar"); avatar.setAttribute("aria-hidden", "true"); 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 link = profileLink(handle, did); if (link) { const anchor = document.createElement("a"); anchor.href = link; anchor.rel = "noopener noreferrer"; anchor.append(nameNode); body.append(anchor); } else { body.append(nameNode); } 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) => warnedScore(treeScore(row, state.tree, weights), 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, originalRank, dailyMove) { const row = make("div", "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"); const currentRank = make("span", "lb-rank-current"); currentRank.append(visualOnly(`#${rank}`), spoken(`rank ${rank}`)); rankNode.append(currentRank); if (move && Number.isFinite(originalRank) && originalRank !== rank) { const baseline = visualOnly( `default #${originalRank}`, `lb-rank-default ${move.delta > 0 ? "is-up" : "is-down"}`, ); baseline.title = `Rank with default weights. ${move.label}.`; rankNode.append(baseline, spoken(`, default rank ${originalRank}, ${move.label}`)); } row.append(rankNode); const identity = make("div", "lb-identity"); const iconBox = make("div", "lb-icon"); iconBox.setAttribute("aria-hidden", "true"); 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 scorePath = PUBLICATION_URI.test(text(pub.uri)) ? sharePath(pub.uri) : undefined; const name = make(scorePath || url ? "a" : "span", "lb-name"); const title = text(pub.name) || "untitled publication"; name.textContent = title; if (scorePath) { name.href = scorePath; name.title = "Open the score page"; } else if (url) { name.href = url; name.rel = "noopener noreferrer"; } nameLine.append(name); if (scorePath && url) { const visit = make("a", "lb-visit"); visit.textContent = "↗"; visit.href = url; visit.rel = "noopener noreferrer"; visit.title = `Visit ${title} on its own site`; visit.setAttribute("aria-label", `Visit ${title} on its own site`); nameLine.append(visit); } if (dailyMove) { const marker = make("span", `lb-move ${dailyMove.delta > 0 ? "is-up" : "is-down"}`); marker.title = dailyMove.label; marker.append( visualOnly(`${dailyMove.delta > 0 ? "▲" : "▼"}${Math.abs(dailyMove.delta)}`, "lb-move-glyph"), spoken(dailyMove.label), ); 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)} read`; 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 scored = Number.isFinite(Number(raw)); const display = scored ? Number(raw).toFixed(1) : "—"; const name = categoryName(category); const card = make("div", "lb-composite"); card.title = `${name}: ${display} score, ${percentileLabel(value)} percentile. ${text(category.detail)}`; // A screen reader reads the card's text: name, score, percentile, medal. const top = make("div", "lb-composite-top"); top.append(iconSvg(category.icon)); const label = make("span"); label.textContent = name; top.append(label); const valueLine = make("div", "lb-composite-value-line"); const number = make("strong", "lb-composite-value"); number.append( visualOnly(display), spoken( scored ? ` score ${display}, ${percentileLabel(value)} percentile` : " no score", ), ); valueLine.append(number); const place = awards?.[category.id]; if (place) { const name = text(category.name) || text(category.id); const award = make("span", "lb-award"); award.dataset.place = String(place); award.title = `${ordinal(place)} highest ${name} score in the top 100`; award.append(visualOnly(String(place)), spoken(`, ${award.title}`)); valueLine.append(award); } const bar = make("span", "lb-bar"); bar.setAttribute("aria-hidden", "true"); 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 percentile = percentileLabel(view?.overall); const note = spoken( ` score, ${percentile} percentile, rank ${exact.format(rank)} of ${exact.format(total)}`, ); overall.title = `Rank #${exact.format(rank)} of ${exact.format(total)} ranked publications; ${percentile} 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 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.append(visualOnly("#"), spoken("rank")); const publication = make("span", "lb-head-pub"); publication.textContent = "publication"; head.append(rank, publication); const sortButton = (key, className, label, detail) => { const button = make("button", `${className} lb-head-sort`); button.type = "button"; button.dataset.sort = key; button.title = `Sort by ${label} score.${detail ? ` ${detail}` : ""}`; button.setAttribute("aria-pressed", String(state.sortKey === key)); const name = make("span"); name.textContent = label; button.append(spoken("sort by "), name); button.addEventListener("click", () => sortBy(key)); return button; }; for (const category of state.tree) { const button = sortButton( category.id, "lb-head-cat", categoryName(category), text(category.detail), ); button.prepend(iconSvg(category.icon)); head.append(button); } head.append(sortButton("overall", "lb-head-overall", "overall")); return head; } /** * Redrawing the list replaces every control in it. This finds the control * that had focus again in the new list: the same sort button, or the same * control in the same publication's row. */ function focusedListControl(host) { const active = document.activeElement; if (!(active instanceof HTMLElement) || !host.contains(active)) return undefined; if (active.dataset.sort) { const key = CSS.escape(active.dataset.sort); return () => host.querySelector(`[data-sort="${key}"]`); } const uri = active.closest(".lb-row")?.dataset.publication; if (!uri) return () => undefined; const controls = (row) => [...row.querySelectorAll("a[href], button")]; const index = controls(active.closest(".lb-row")).indexOf(active); return () => { const row = host.querySelector(`.lb-row[data-publication="${CSS.escape(uri)}"]`); return row ? controls(row)[index] : undefined; }; } function renderPublications(entries, defaultPositions) { const host = document.getElementById("panoptiblog-publications"); if (!host) return; const refocus = focusedListControl(host); 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 score = (entry) => views.get(entry).rawCategories?.[category.id]; const leaders = orderBy(entries, score) .filter((entry) => Number.isFinite(score(entry))) .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) => views.get(entry).rawCategories?.[state.sortKey]; const sorted = state.sortKey === "overall" ? entries : orderBy(entries, value); 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; const published = Number(entry.row.rank); const previous = Number(entry.row.previousRank); const dailyDelta = Number.isFinite(published) && Number.isFinite(previous) ? previous - published : 0; return leaderboardRow( entry.row, rank, views.get(entry), state.rankedCount || entries.length, awards.get(entry), delta === 0 ? undefined : { delta, label: movementLabel(delta) }, from, dailyDelta === 0 ? undefined : { delta: dailyDelta, label: dailyMovementLabel(dailyDelta) }, ); }), ); host.replaceChildren(leaderboardHead(), rows); } document.dispatchEvent(new CustomEvent(ROWS_EVENT)); // After the event, so a subscribe control the account module adds back can // take focus too. The sticky header stays put, so it does not scroll. if (refocus) { const target = refocus(); if (target) target.focus({ preventScroll: Boolean(target.dataset.sort) }); else host.focus({ preventScroll: true }); } } 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)} · refreshed daily`); 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 loadWeights(fallback) { const weights = structuredClone(fallback); let saved; try { const raw = localStorage.getItem(WEIGHTS_KEY); if (!raw) return weights; saved = JSON.parse(raw); } catch { return weights; } const categories = saved?.categories; if (!categories || typeof categories !== "object") return weights; for (const [id, category] of Object.entries(weights)) { const stored = categories[id]; if (!stored || typeof stored !== "object") continue; if (Number.isFinite(stored.weight)) category.weight = Math.max(0, stored.weight); for (const factorId of Object.keys(category.factors)) { if (Number.isFinite(stored.factors?.[factorId])) { category.factors[factorId] = Math.max(0, stored.factors[factorId]); } } } return weights; } 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. } } // The panel rebuilds its sliders when the dataset or the active composite // changes, so a registry of the visible controls is enough to sync them all. const weightControls = new Map(); function registerWeightControl(syncKey, control) { const controls = weightControls.get(syncKey) ?? []; controls.push(control); weightControls.set(syncKey, controls); } function formatWeight(value) { return Number.isInteger(value) ? String(value) : value.toFixed(1); } function setControlValue(control, value) { const label = formatWeight(value); control.input.value = label; control.input.setAttribute("aria-valuetext", `${label} percent`); control.output.textContent = `${label}%`; } function syncWeightControl(syncKey, value) { for (const control of weightControls.get(syncKey) ?? []) { setControlValue(control, value); } } function syncCategoryInputs() { const ids = state.tree.map((category) => category.id); const shares = displayShares(ids.map((id) => state.weights[id]?.weight ?? 0)); ids.forEach((id, index) => syncWeightControl(`category:${id}`, shares[index])); } function syncFactorInputs(categoryId) { const category = state.tree.find((entry) => entry.id === categoryId); const ids = (category?.factors ?? []).map((factor) => factor.id); if (ids.length === 0) return; const shares = displayShares( ids.map((id) => state.weights[categoryId].factors?.[id] ?? 0), ); ids.forEach((id, index) => { syncWeightControl(`factor:${categoryId}:${id}`, shares[index]); }); } function syncWeightInputs() { syncCategoryInputs(); if (activeWeightCategory) syncFactorInputs(activeWeightCategory); } function nearlyEqual(left, right) { return Math.abs((left ?? 0) - (right ?? 0)) < 1e-6; } 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] || !nearlyEqual(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 ( !nearlyEqual( left[id].factors?.[factorId] ?? 0, right[id].factors?.[factorId] ?? 0, ) ) { return false; } } } return true; } function hasCustomWeights() { return !sameWeights(state.weights, state.defaultWeights ?? defaultWeights(state.tree)); } function setCategoryWeight(categoryId, value) { const ids = state.tree.map((category) => category.id); const changed = ids.indexOf(categoryId); if (changed < 0) return; const next = rebalanceVector( ids.map((id) => state.weights[id]?.weight ?? 0), changed, value, ); ids.forEach((id, index) => { state.weights[id].weight = next[index]; }); syncCategoryInputs(); syncWeightVisuals(); saveWeights(); scheduleRankings(); announceRankingsUpdated(); } function setFactorWeight(categoryId, factorId, value) { const category = state.tree.find((entry) => entry.id === categoryId); if (!category) return; const ids = (category.factors ?? []).map((factor) => factor.id); const changed = ids.indexOf(factorId); if (changed < 0) return; const next = rebalanceVector( ids.map((id) => state.weights[categoryId].factors?.[id] ?? 0), changed, value, ); ids.forEach((id, index) => { state.weights[categoryId].factors[id] = next[index]; }); syncFactorInputs(categoryId); syncWeightVisuals(); saveWeights(); scheduleRankings(); announceRankingsUpdated(); } function resetWeights() { state.weights = structuredClone( state.defaultWeights ?? normalizeWeights(defaultWeights(state.tree), state.tree), ); try { localStorage.removeItem(WEIGHTS_KEY); } catch { // Nothing to clear if storage is unavailable. } syncWeightInputs(); syncWeightVisuals(); updateRankings(); announce("default weights restored"); } 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; } function defaultRankPositions(weights = state.defaultWeights ?? defaultWeights(state.tree)) { const positions = new Map(); rankPublications(state.publications, state.tree, 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 dailyMovementLabel(delta) { const places = Math.abs(delta); const date = state.previousGeneratedAt ? new Date(state.previousGeneratedAt) : undefined; const when = date && Number.isFinite(date.getTime()) ? `the ${day.format(date)} run` : "the previous run"; return `${delta > 0 ? "up" : "down"} ${places} ${places === 1 ? "place" : "places"} in the published ranking since ${when}`; } const CLIMB_LIMIT = 3; /** The run's largest published rank gains, biggest first. */ function biggestClimbs(publications) { const climbs = []; for (const pub of publications) { if (!Number.isFinite(pub?.rank) || !Number.isFinite(pub?.previousRank)) continue; const delta = pub.previousRank - pub.rank; if (delta > 0) climbs.push({ pub, rank: pub.rank, delta }); } return climbs .sort((a, b) => b.delta - a.delta || a.rank - b.rank) .slice(0, CLIMB_LIMIT); } /** * A note above the list, not a second ranking: the figures are the published * run's, so custom weights below do not move them. */ function renderClimbs(publications) { const host = document.getElementById("panoptiblog-climbs"); if (!host) return; const climbs = biggestClimbs(publications); if (climbs.length === 0) { host.replaceChildren(); host.hidden = true; return; } const head = make("p", "pano-climbs-head"); head.textContent = "biggest climbs · published ranking"; const list = make("ul", "pano-climbs-list"); for (const { pub, rank, delta } of climbs) { const item = make("li", "pano-climbs-item"); const uri = text(pub.uri); const linked = PUBLICATION_URI.test(uri); const row = make(linked ? "a" : "span", "pano-climbs-link"); if (linked) row.href = `${PUB_HASH}${encodeURIComponent(uri)}`; const rankNode = make("span", "pano-climbs-rank"); rankNode.textContent = `#${exact.format(rank)}`; const nameNode = make("span", "pano-climbs-name"); nameNode.textContent = text(pub.name) || "untitled publication"; const upNode = make("span", "pano-climbs-up"); upNode.textContent = `up ${exact.format(delta)}`; row.append(rankNode, nameNode, upNode); item.append(row); list.append(item); } host.replaceChildren(head, list); host.hidden = false; } function updateRankings() { const custom = hasCustomWeights(); renderPublications( rankPublications(state.publications, state.tree, state.weights), 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, read once the page settles: each call restarts the wait, * so a slider dragged across many steps is announced once. */ function announce(message) { window.clearTimeout(statusTimer); const status = document.getElementById("panoptiblog-status"); if (status) status.textContent = ""; statusTimer = window.setTimeout(() => { if (status) status.textContent = message; }, STATUS_DEBOUNCE_MS); } function announceRankingsUpdated() { announce("rankings updated"); } let sliderSequence = 0; let activeWeightCategory = null; let weightsOpener = null; // Fixed categorical order. Colors follow the category id, not its position in // the tree, so moving a category never repaints it. The palette is validated // for adjacent-pair CVD separation on the card surface; every segment also // carries a visible label. const CATEGORY_COLORS = { audience: "#2a78d6", output: "#eb6834", longevity: "#1baf7a", craft: "#eda100", activity: "#e87ba4", sourcing: "#008300", }; const FALLBACK_CATEGORY_COLOR = "#898781"; function categoryColor(id) { return CATEGORY_COLORS[id] ?? FALLBACK_CATEGORY_COLOR; } function categoryName(category) { return text(category.name) || text(category.id); } function weightSlider({ label, value, color, detail, disabled, syncKey, onInput }) { const row = make("div", "pano-weight-row"); const head = make("div", "pano-weight-row-head"); const labelNode = make("label"); if (color) { const dot = make("span", "pano-weight-dot"); dot.setAttribute("aria-hidden", "true"); dot.style.background = color; labelNode.append(dot); } labelNode.append(document.createTextNode(label)); if (detail) labelNode.title = detail; // The slider's aria-valuetext speaks the value. An would be a live // region, and one move rebalances every slider in the column. const output = make("span", "pano-weight-value"); output.setAttribute("aria-hidden", "true"); output.textContent = `${formatWeight(value)}%`; head.append(labelNode, output); const input = document.createElement("input"); input.type = "range"; input.min = "0"; input.max = "100"; input.step = "0.1"; input.value = String(value); input.disabled = Boolean(disabled); input.setAttribute("aria-valuetext", `${formatWeight(value)} percent`); if (detail) input.title = detail; input.id = `panoptiblog-weight-${sliderSequence++}`; labelNode.htmlFor = input.id; input.addEventListener("input", () => { const next = clampPercent(input.value); output.textContent = `${formatWeight(next)}%`; input.setAttribute("aria-valuetext", `${formatWeight(next)} percent`); onInput(next); }); if (syncKey) registerWeightControl(syncKey, { input, output }); row.append(head, input); return row; } function renderWeightShare(host, items) { if (!host) return; host.replaceChildren(); const described = []; for (const item of items) { if (!(item.value > 0)) continue; const segment = make("span", "pano-weight-seg"); segment.style.flexGrow = String(item.flex ?? item.value); segment.style.background = item.color; segment.title = `${item.label}: ${formatWeight(item.value)}%`; host.append(segment); described.push(`${item.label} ${formatWeight(item.value)}%`); } host.setAttribute( "aria-label", described.length > 0 ? `Weight shares: ${described.join(", ")}` : "No weight shares", ); } function activeWeightTreeCategory() { return state.tree.find((category) => category.id === activeWeightCategory); } function syncWeightVisuals() { const categoryIds = state.tree.map((category) => category.id); const categoryShares = displayShares( categoryIds.map((id) => state.weights[id]?.weight ?? 0), ); const categoryShareById = new Map( categoryIds.map((id, index) => [id, categoryShares[index]]), ); renderWeightShare( document.getElementById("panoptiblog-weights-share"), state.tree.map((category) => ({ label: categoryName(category), value: categoryShareById.get(category.id) ?? 0, flex: state.weights[category.id]?.weight ?? 0, color: categoryColor(category.id), })), ); for (const tab of document.querySelectorAll("[data-weight-category]")) { const share = tab.querySelector(".pano-weight-tab-share"); if (share) { share.textContent = `${formatWeight(categoryShareById.get(tab.dataset.weightCategory) ?? 0)}%`; } } const category = activeWeightTreeCategory(); const factors = category?.factors ?? []; const factorShares = displayShares( factors.map((factor) => state.weights[category.id]?.factors?.[factor.id] ?? 0), ); renderWeightShare( document.getElementById("panoptiblog-factor-share"), factors.map((factor, index) => ({ label: text(factor.name) || text(factor.id), value: factorShares[index] ?? 0, flex: state.weights[category.id]?.factors?.[factor.id] ?? 0, color: categoryColor(category.id), })), ); } function renderCategoryControls() { const host = document.getElementById("panoptiblog-weights-categories"); if (!host) return; host.replaceChildren(); const shares = displayShares( state.tree.map((category) => state.weights[category.id]?.weight ?? 0), ); state.tree.forEach((category, index) => { host.append( weightSlider({ label: categoryName(category), value: shares[index], color: categoryColor(category.id), detail: category.detail, syncKey: `category:${category.id}`, onInput: (value) => setCategoryWeight(category.id, value), }), ); }); } function selectWeightCategory(id) { const category = state.tree.find((entry) => entry.id === id) ?? state.tree[0]; if (!category) return; activeWeightCategory = category.id; for (const tab of document.querySelectorAll("[data-weight-category]")) { const selected = tab.dataset.weightCategory === category.id; tab.setAttribute("aria-selected", String(selected)); tab.tabIndex = selected ? 0 : -1; tab.classList.toggle("is-active", selected); } const factors = document.getElementById("panoptiblog-weight-factors"); if (factors) { factors.setAttribute("role", "tabpanel"); factors.setAttribute("aria-labelledby", `panoptiblog-weight-tab-${category.id}`); } renderFactorControls(category); syncWeightVisuals(); } function renderCategoryTabs() { const host = document.getElementById("panoptiblog-weight-tabs"); if (!host) return; host.replaceChildren(); for (const category of state.tree) { const tab = make("button", "pano-weight-tab"); tab.type = "button"; tab.id = `panoptiblog-weight-tab-${category.id}`; tab.dataset.weightCategory = category.id; tab.setAttribute("role", "tab"); tab.setAttribute("aria-selected", "false"); tab.setAttribute("aria-controls", "panoptiblog-weight-factors"); tab.tabIndex = -1; const dot = make("span", "pano-weight-dot"); dot.setAttribute("aria-hidden", "true"); dot.style.background = categoryColor(category.id); const name = make("span", "pano-weight-tab-name"); name.textContent = categoryName(category); const share = make("span", "pano-weight-tab-share"); share.textContent = `${formatWeight(state.weights[category.id]?.weight ?? 0)}%`; tab.append(dot, name, share); tab.addEventListener("click", () => selectWeightCategory(category.id)); tab.addEventListener("keydown", (event) => { const ids = state.tree.map((entry) => entry.id); const index = ids.indexOf(category.id); let next; if (event.key === "ArrowRight") next = (index + 1) % ids.length; else if (event.key === "ArrowLeft") next = (index - 1 + ids.length) % ids.length; else if (event.key === "Home") next = 0; else if (event.key === "End") next = ids.length - 1; else return; event.preventDefault(); selectWeightCategory(ids[next]); document.getElementById(`panoptiblog-weight-tab-${ids[next]}`)?.focus(); }); host.append(tab); } } function renderFactorControls(category) { const host = document.getElementById("panoptiblog-weight-factors"); if (!host) return; host.replaceChildren(); const factors = category.factors ?? []; if (factors.length === 0) { const note = make("p", "panoptiblog-note"); note.textContent = "This composite has no factor weights."; host.append(note); return; } const available = availableFactors(); const shares = displayShares( factors.map((factor) => state.weights[category.id]?.factors?.[factor.id] ?? 0), ); factors.forEach((factor, index) => { const hasFactor = available.has(factor.id); const only = factors.length === 1; const suffix = only ? " (only factor)" : hasFactor ? "" : " (not run)"; host.append( weightSlider({ label: `${text(factor.name) || text(factor.id)}${suffix}`, value: shares[index], color: categoryColor(category.id), detail: factor.detail, disabled: !hasFactor || only, syncKey: `factor:${category.id}:${factor.id}`, onInput: (value) => setFactorWeight(category.id, factor.id, value), }), ); }); } function renderWeightPanel() { const button = document.getElementById("panoptiblog-weights-open"); weightControls.clear(); if (state.tree.length === 0) { if (button) button.hidden = true; closeWeightsPanel(); return; } if (button) button.hidden = false; sliderSequence = 0; renderCategoryControls(); renderCategoryTabs(); selectWeightCategory(activeWeightCategory ?? state.tree[0].id); } function weightsPanelElement() { return document.getElementById("panoptiblog-weights-panel"); } function openWeightsPanel({ method = false, opener } = {}) { const panel = weightsPanelElement(); if (!panel || state.tree.length === 0) return; const wasOpen = !panel.hidden; if (!wasOpen) { weightsOpener = opener ?? document.activeElement; panel.hidden = false; document.getElementById("panoptiblog-weights-open")?.setAttribute("aria-expanded", "true"); document.getElementById("panoptiblog-layout")?.classList.add("is-weighting"); } if (method) { const details = document.getElementById("panoptiblog-weights-method"); if (details) { details.open = true; details.scrollIntoView({ block: "nearest" }); details.querySelector("summary")?.focus({ preventScroll: true }); } } else if (!wasOpen) { panel.querySelector('input[type="range"]:not(:disabled)')?.focus({ preventScroll: true }); } } function closeWeightsPanel() { const panel = weightsPanelElement(); if (!panel || panel.hidden) return; panel.hidden = true; document.getElementById("panoptiblog-weights-open")?.setAttribute("aria-expanded", "false"); document.getElementById("panoptiblog-layout")?.classList.remove("is-weighting"); const opener = weightsOpener; weightsOpener = null; if (opener?.isConnected) opener.focus({ preventScroll: true }); } function setupWeightsPanel() { const panel = weightsPanelElement(); const open = document.getElementById("panoptiblog-weights-open"); if (!panel || !open) return; open.addEventListener("click", () => { if (panel.hidden) openWeightsPanel({ opener: open }); else closeWeightsPanel(); }); document .getElementById("panoptiblog-weights-close") ?.addEventListener("click", closeWeightsPanel); document .getElementById("panoptiblog-weights-panel-reset") ?.addEventListener("click", resetWeights); document .getElementById("panoptiblog-weights-jump") ?.addEventListener("click", (event) => openWeightsPanel({ opener: event.currentTarget })); document.getElementById("panoptiblog-weights-reset")?.addEventListener("click", () => { resetWeights(); // Resetting hides the notice and the focused button with it. The list it // described is still on screen, so focus moves there. document.getElementById("panoptiblog-publications")?.focus({ preventScroll: true }); }); document .getElementById("panoptiblog-method-open") ?.addEventListener("click", (event) => openWeightsPanel({ method: true, opener: event.currentTarget }), ); document.addEventListener("keydown", (event) => { if (event.key !== "Escape" || panel.hidden) return; if (document.querySelector("dialog[open]")) return; event.preventDefault(); closeWeightsPanel(); }); } // --- 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; } /** * Exclusions with bulk-account moved out of spam. The indexer counts a spam * exclusion under its first reason and appends bulk-account last, so that * count is the publications excluded for nothing else. */ function splitBulk(universe) { const excluded = { ...(universe.excluded ?? {}) }; const spamReasons = { ...(universe.spamReasons ?? {}) }; const bulk = Number(spamReasons[BULK_REASON] ?? 0); if (bulk > 0 && "spam" in excluded) { excluded[BULK_REASON] = bulk; excluded.spam = Math.max(0, Number(excluded.spam ?? 0) - bulk); delete spamReasons[BULK_REASON]; } return { excluded, spamReasons }; } /** * The latest crawl's repository outcomes. Snapshots without totals.crawl * carry the same counters at the top level; there a repository both skipped * and failed is subtracted twice, so the read count is a floor. */ function crawlOutcomes(totals) { const crawl = totals.crawl; if (crawl && Number.isFinite(Number(crawl.repositories))) { return { repositories: Number(crawl.repositories), read: Number(crawl.readRepositories ?? 0), skipped: Number(crawl.skipped ?? 0), failed: Number(crawl.failed ?? 0), truncated: Number(crawl.truncated ?? 0), changed: Number(crawl.changedRepositories ?? 0), incremental: crawl.mode === "incremental", floor: false, }; } const repositories = Number(totals.repositories); if (!Number.isFinite(repositories) || repositories <= 0) return undefined; const skipped = Number(totals.skippedRepositories ?? 0); const failed = Number(totals.failures ?? 0); return { repositories, read: Math.max(0, repositories - skipped - failed), skipped, failed, truncated: Number(totals.truncatedRepositories ?? 0), changed: 0, incremental: false, floor: true, }; } /** Repository outcomes as one bar. They are accounts, not publications. */ function crawlStage(crawl) { const figure = make("figure", "pano-funnel pano-crawl"); const caption = make("figcaption", "pano-funnel-caption"); const kicker = make("span"); kicker.textContent = crawl.incremental ? "repositories · incremental crawl" : "repositories · latest crawl"; const outcome = make("span", "pano-funnel-outcome"); outcome.textContent = crawl.incremental ? `${exact.format(crawl.changed)} changed · ${exact.format(crawl.read)} of ${exact.format(crawl.repositories)} indexed` : `${crawl.floor ? "at least " : ""}${exact.format(crawl.read)} of ${exact.format(crawl.repositories)} read`; caption.append(kicker, outcome); const parts = crawl.incremental ? [ ["changed", "changed", crawl.changed], ["read", "unchanged", Math.max(0, crawl.read - crawl.changed)], ["skipped", "skipped", crawl.skipped], ["failed", "failed", crawl.failed], ] : [ ["read", "read", crawl.read], ["skipped", "skipped", crawl.skipped], ["failed", "failed", crawl.failed], ]; const bar = make("div", "pano-crawl-bar"); bar.setAttribute("role", "img"); bar.setAttribute( "aria-label", `${exact.format(crawl.repositories)} repositories discovered: ${parts .map(([, label, count]) => `${exact.format(count)} ${label}`) .join(", ")}`, ); const legend = make("ul", "pano-crawl-legend"); for (const [id, label, count] of parts) { if (count > 0) { const segment = make("span", `pano-crawl-seg is-${id}`); segment.style.flexGrow = String(count); segment.title = `${label}: ${exact.format(count)}`; bar.append(segment); } const item = make("li"); const swatch = make("i", `pano-crawl-swatch is-${id}`); swatch.setAttribute("aria-hidden", "true"); const name = make("span", "dialog-name"); name.textContent = label; const value = make("span", "dialog-count"); value.textContent = exact.format(count); item.append(swatch, name, value); legend.append(item); } if (crawl.truncated > 0) { const item = make("li"); const flag = make("span", "pano-flag"); flag.textContent = "partial"; const value = make("span", "dialog-count"); value.textContent = `${exact.format(crawl.truncated)} listings`; item.append(flag, value); item.title = "Record listings that stopped at the crawl's page limit. Their repositories count as read, in part."; legend.append(item); } const note = make("p", "dialog-note"); note.textContent = `${crawl.incremental ? "Incremental runs re-read repositories that changed since the last run, plus canaries and earlier failures; a full reconciliation runs every two weeks. " : ""}Skipped repositories are gone or unresolvable. Failed reads errored after retries.${crawl.truncated > 0 ? " A partial listing stopped at the crawl's page limit, so its repository was read in part." : ""} One repository can hold several publications or none, so these counts do not add up to the publication chart below.`; figure.append(caption, bar, legend, note); return figure; } function wrongExclusionNote() { const note = make("p", "dialog-note"); const issues = document.createElement("a"); issues.href = FEEDBACK_URL; issues.rel = "noopener noreferrer"; issues.textContent = "open an issue"; const mail = document.createElement("a"); mail.href = `mailto:${CONTACT_EMAIL}`; mail.textContent = CONTACT_EMAIL; note.append("Excluded by mistake? ", issues, " or email ", mail, "."); return note; } /** 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 bulk = Number(excluded[BULK_REASON] ?? 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 = bulk + spam + opted + language; const indexed = Math.max(0, crawled - hard); const notShown = Math.max(0, ranked - shown); const filters = [ ["bulk", "bulk / network", bulk], ["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: "found", 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) // The margins hold the first column's labels on the left and the last // column's on the right; the middle columns' labels run between them. .extent([ [110, 40], [810, 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 = `Found ${exact.format(crawled)} publications; 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.id = "pano-funnel-kicker"; kicker.textContent = "publications · crawl to leaderboard"; const outcome = make("span", "pano-funnel-outcome"); outcome.textContent = `${exact.format(shown)} of ${exact.format(crawled)} shown`; caption.append(kicker, outcome); // The chart scrolls sideways in a narrow dialog, so the keyboard can focus // it to scroll. const scroller = make("div", "pano-sankey-scroll"); scroller.tabIndex = 0; scroller.setAttribute("role", "region"); scroller.setAttribute("aria-labelledby", kicker.id); 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, spamReasons: spamCounts } = splitBulk(universe); const nodes = []; const crawl = crawlOutcomes(totals); if (crawl) nodes.push(crawlStage(crawl)); 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 relay = httpUrl(data.source?.relay); if (relay) { const coverage = make("p", "dialog-note"); coverage.textContent = `Repositories are found through the relay at ${new URL(relay).host}. A repository it does not list for a standard.site collection is not crawled.`; nodes.push(coverage); } 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, (key === BULK_REASON ? spamDescriptions[key] : filters[key]) ?? FILTER_FALLBACKS[key] ?? "Excluded from the ranking.", ]), ); nodes.push(countList(keys.map((key) => [key, excluded[key]]), descriptions)); nodes.push(wrongExclusionNote()); nodes.push(subhead("spam reasons")); 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("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; } function dialogLink(href, label, external = false) { const anchor = make("a", undefined, label); anchor.href = href; if (external) anchor.rel = "noopener noreferrer"; return anchor; } function dialogStat(label, value, note) { const stat = make("div", "dialog-stat"); stat.append(make("span", "dialog-stat-label", label)); stat.append(make("strong", "dialog-stat-value", value)); if (note) stat.append(make("span", "dialog-stat-note", note)); return stat; } /** The identity block at the top of the details dialog. */ function dialogProfile(pub, handle, author) { const profile = make("div", "dialog-profile"); const iconBox = make("div", "dialog-profile-icon"); iconBox.setAttribute("aria-hidden", "true"); const name = text(pub.name) || handle || "?"; iconBox.append(make("span", "dialog-profile-initial", Array.from(name.trim())[0]?.toUpperCase() ?? "?")); 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 copy = make("div", "dialog-profile-copy"); const byline = [text(author.displayName), handle ? `@${handle}` : undefined] .filter(Boolean) .join(" · "); if (byline) copy.append(make("p", "dialog-profile-author", byline)); const description = text(pub.description).replace(/\s+/gu, " ").trim(); if (description) { copy.append(make("p", "dialog-profile-description", description.slice(0, 280))); } const links = make("p", "dialog-profile-links"); const url = httpUrl(pub.url); if (url) links.append(dialogLink(url, "visit publication ↗", true)); if (PUBLICATION_URI.test(text(pub.uri))) { links.append(dialogLink(sharePath(pub.uri), "score page")); } const profileUrl = profileLink(handle, text(author.did) || text(pub.did)); if (profileUrl) links.append(dialogLink(profileUrl, "bluesky", true)); if (links.childElementCount) copy.append(links); profile.append(iconBox, copy); return profile; } /** The six published composite scores, in the same order as the table. */ function dialogComposites(pub) { const grid = make("div", "dialog-composites"); for (const category of state.tree) { const values = pub.composites?.[category.id] ?? {}; const raw = Number(values.raw); const label = categoryName(category); const card = make("div", "dialog-comp"); card.title = `${label}: ${Number.isFinite(raw) ? raw.toFixed(1) : "no score"}, ${percentileLabel(values.percentile)} percentile`; const head = make("div", "dialog-comp-head"); head.append( make("span", "dialog-comp-name", label), make("strong", "dialog-comp-value", Number.isFinite(raw) ? raw.toFixed(1) : "—"), ); const bar = make("span", "dialog-comp-bar"); bar.setAttribute("aria-hidden", "true"); const fill = make("i"); fill.style.width = `${Number.isFinite(raw) ? Math.max(0, Math.min(100, raw)) : 0}%`; bar.append(fill); card.append(head, bar); grid.append(card); } return grid; } /** Factor percentiles, folded one composite at a time. */ function dialogFactorGroups(pub) { const host = make("div", "dialog-factor-groups"); for (const category of state.tree) { const details = document.createElement("details"); details.className = "dialog-details"; const summary = document.createElement("summary"); summary.textContent = `${categoryName(category)} factors`; details.append( summary, debugList( (category.factors ?? []).map((factor) => [ text(factor.name), debugNumber(pub.factors?.[factor.id], 1), ]), ), ); host.append(details); } return host; } // 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); } function openLinkedPublication() { const pub = publicationFromHash(); if (!pub) return; const uri = text(pub.uri); const opener = [...document.querySelectorAll(".lb-row")] .find((row) => row.dataset.publication === uri) ?.querySelector(".lb-debug"); openDebug(pub, opener); } 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 handle = displayHandle(author.handle) || displayHandle(pub.handle); const diagnostics = pub.diagnostics ?? {}; const audience = diagnostics.audience ?? {}; const citations = diagnostics.citations ?? {}; const pulse = diagnostics.pulse ?? {}; const network = diagnostics.network ?? {}; const nodes = []; if (pub.stale) { nodes.push(make( "p", "dialog-note is-warning", "Not refreshed in the latest crawl; figures are from an earlier run.", )); } const total = state.rankedCount || state.publications?.length; const standing = make("div", "dialog-standing"); standing.append( dialogStat( "rank", pub.rank ? `#${exact.format(pub.rank)}` : "—", total ? `of ${exact.format(total)}` : "", ), dialogStat( "overall", Number.isFinite(Number(pub.score)) ? Number(pub.score).toFixed(1) : "—", ), dialogStat( "percentile", Number.isFinite(Number(pub.percentile)) ? Number(pub.percentile).toFixed(2) : "—", ), ); nodes.push(dialogProfile(pub, handle, author)); nodes.push(subhead("scores")); nodes.push(standing); nodes.push(dialogComposites(pub)); nodes.push(make( "p", "dialog-note", "Scores and factor values are percentiles of the indexed cohort. " + "Bluesky engagement is not collected in this release.", )); nodes.push(dialogFactorGroups(pub)); nodes.push(subhead("identity")); nodes.push(debugList([ ["url", text(pub.url) || "—"], ["author", text(author.displayName) || handle || "—"], ["handle", handle ? `@${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); if (!dialog.open) 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; // Moving a node drops its focus, so a reader who scrolls with a // control focused keeps it. const focused = document.activeElement; const moving = focused instanceof HTMLElement && (account.contains(focused) || notice.contains(focused)) ? focused : undefined; 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); if (moving && document.activeElement !== moving) moving.focus({ preventScroll: true }); } // 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. The root's scroll padding // reads the same height, so a focused row never scrolls under either. new ResizeObserver(([entry]) => { frameHeight = entry.borderBoxSize[0].blockSize; root.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 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; }); // The climbs panel and /find link to #pub=; a fragment change on the // same page does not reload, so open the row here too. window.addEventListener("hashchange", openLinkedPublication); 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-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; const climbs = document.getElementById("panoptiblog-climbs"); if (climbs) { climbs.replaceChildren(); climbs.hidden = true; } const weightsOpen = document.getElementById("panoptiblog-weights-open"); if (weightsOpen) weightsOpen.hidden = true; closeWeightsPanel(); } 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 = normalizeWeights(defaultWeights(state.tree), state.tree); state.weights = normalizeWeights(loadWeights(state.defaultWeights), state.tree); state.defaultPositions = defaultRankPositions(); state.previousGeneratedAt = data.previousGeneratedAt; state.rankedCount = Number(data.totals?.rankedPublications ?? state.cohort.length ?? 0); renderUpdated(data.generatedAt); renderEcosystem(data.totals?.ecosystem); renderIncluded(data); renderWeightPanel(); renderClimbs(state.publications); updateRankings(); document.dispatchEvent( new CustomEvent("panoptiblog:data", { detail: { publications: state.publications, rankedTotal: state.rankedCount, }, }), ); openLinkedPublication(); showDatasetSections(true); } function load() { main().catch((error) => { console.error("[panoptiblog] could not load the dataset", error); failed(); }); } setupIncludedDialog(); setupDebugDialog(); setupWeightsPanel(); setupFrame(); load();