// /panoptiblog's compare dialog. The full ranked dataset is several megabytes, // so it is fetched only when the dialog opens. Records are third-party data, // so every value reaches the DOM through textContent. import { comparePublications, explainComparison, } from "./panoptiblog-compare-model.js"; import { search } from "./panoptiblog-lookup.js"; const ALL_URL = "/panoptiblog/all.json"; const PARAM = "compare"; const EVENT = "panoptiblog:compare"; const exact = new Intl.NumberFormat("en"); const dialog = document.getElementById("panoptiblog-compare"); const openButton = document.getElementById("panoptiblog-compare-open"); const closeButton = document.getElementById("panoptiblog-compare-close"); const status = document.getElementById("panoptiblog-compare-status"); const content = document.getElementById("panoptiblog-compare-content"); let dataset; let pendingRequest; let pendingUri; let opener; let ui; function text(value) { return value === undefined || value === null ? "" : String(value); } function make(tag, className, value) { const node = document.createElement(tag); if (className) node.className = className; if (value !== undefined) node.textContent = value; return node; } function link(href, label) { const anchor = make("a", undefined, label); anchor.href = href; return anchor; } function stat(label, value) { const item = make("div"); item.append(make("dt", undefined, label), make("dd", undefined, value)); return item; } function nameOf(entry) { return entry.name || entry.handle || entry.uri || "untitled publication"; } function percentileText(value) { return Number.isFinite(value) ? value.toFixed(1) : "—"; } function signed(value) { if (!Number.isFinite(value)) return "—"; const amount = Math.abs(value).toFixed(1); if (value > 0) return `+${amount}`; if (value < 0) return `-${amount}`; return "0.0"; } function runDate(value) { const time = Date.parse(text(value)); return Number.isFinite(time) ? new Date(time).toISOString().slice(0, 10) : "unknown"; } function optionLabel(row) { const rank = Number(row.rank); const name = text(row.name) || text(row.handle) || "untitled publication"; const handle = row.handle ? ` (@${text(row.handle)})` : ""; return `#${exact.format(rank)} — ${name}${handle}`; } function movement(entry) { const from = Number(entry.previousRank); const to = Number(entry.rank); const change = from - to; if (!Number.isFinite(change) || change === 0) return `#${exact.format(from)} · no change`; return `#${exact.format(from)} · ${change > 0 ? "up" : "down"} ${exact.format(Math.abs(change))}`; } /** One fetch per page; a failure can be retried. */ function loadAll() { if (dataset) return Promise.resolve(dataset); pendingRequest ??= fetch(ALL_URL, { headers: { accept: "application/json" } }) .then(async (response) => { if (!response.ok) throw new Error(`${response.status} ${response.statusText}`); const payload = await response.json(); const rawTree = payload?.method?.tree; const tree = Array.isArray(rawTree) ? rawTree : rawTree?.categories; if (!Array.isArray(tree) || tree.length === 0) throw new Error("no score tree"); const rows = []; const seen = new Set(); for (const row of Array.isArray(payload?.publications) ? payload.publications : []) { const uri = text(row?.uri); if (!uri || typeof row.rank !== "number" || !Number.isFinite(row.rank) || seen.has(uri)) { continue; } seen.add(uri); rows.push(row); } rows.sort( (left, right) => Number(left.rank) - Number(right.rank) || text(left.uri).localeCompare(text(right.uri)), ); const byUri = new Map(rows.map((row) => [row.uri, row])); console.debug(`[panoptiblog] full ranking loaded: ${rows.length} publications`); dataset = { generatedAt: payload.generatedAt, tree, rows, byUri, rankedCount: Number(payload?.totals?.rankedPublications) > 0 ? Number(payload.totals.rankedPublications) : rows.length, }; return dataset; }) .catch((error) => { pendingRequest = undefined; throw error; }); return pendingRequest; } function failure(error) { const panel = make("div", "pano-failure"); panel.append(make( "p", "pano-failure-message", error?.message === "no score tree" ? "the full ranking has no score tree" : "the full ranking is unavailable right now", )); const actions = make("div", "pano-failure-actions"); const retry = make("button", "pano-retry", "try again"); retry.type = "button"; retry.addEventListener("click", () => start()); actions.append(retry, link(ALL_URL, "view the dataset")); panel.append(actions); return panel; } function picker(labelText, id) { const wrap = make("div", "pano-compare-picker"); const label = make("label", undefined, labelText); label.htmlFor = `panoptiblog-compare-${id}`; const current = make("p", "pano-compare-current"); const input = make("input", "pano-compare-search"); input.type = "search"; input.id = `panoptiblog-compare-${id}`; input.placeholder = "search ranked blogs"; input.autocomplete = "off"; input.autocapitalize = "none"; input.spellcheck = false; input.setAttribute("aria-controls", `panoptiblog-compare-${id}-results`); const results = make("ul", "pano-compare-results"); results.id = `panoptiblog-compare-${id}-results`; results.setAttribute("aria-label", `Ranked blogs matching blog ${id.toUpperCase()}`); results.hidden = true; wrap.append(label, current, input, results); return { wrap, input, results, current, id }; } function firstOther(uri) { return dataset.rows.find((row) => row.uri !== uri)?.uri ?? uri; } function chooseInitial() { const params = new URL(location.href).searchParams.get(PARAM)?.split(",") ?? []; const requestedA = text(pendingUri) || text(params[0]).trim(); const requestedB = text(params[1]).trim(); const record = Boolean(pendingUri); pendingUri = undefined; const a = dataset.byUri.has(requestedA) ? requestedA : dataset.rows[0].uri; const b = dataset.byUri.has(requestedB) && requestedB !== a ? requestedB : firstOther(a); return { a, b, record: record && a === requestedA }; } function remember(a, b) { const url = new URL(location.href); if (a && b) url.searchParams.set(PARAM, `${a},${b}`); else url.searchParams.delete(PARAM); history.replaceState(history.state, "", url.href); } function hideResults(picker) { picker.results.replaceChildren(); picker.results.hidden = true; } function renderCurrent() { for (const [picker, uri] of [ [ui.aPicker, ui.aUri], [ui.bPicker, ui.bUri], ]) { const row = dataset.byUri.get(uri); picker.current.textContent = row ? `now ${optionLabel(row)}` : "choose a ranked blog"; } } function selectPicker(side, uri) { if (!dataset.byUri.has(uri)) return; if (side === "a") { ui.aUri = uri; if (ui.bUri === uri) ui.bUri = firstOther(uri); } else { ui.bUri = uri; if (ui.aUri === uri) ui.aUri = firstOther(uri); } for (const picker of [ui.aPicker, ui.bPicker]) { picker.input.value = ""; hideResults(picker); } renderCurrent(); changed(); } function showResults(side) { const picker = side === "a" ? ui.aPicker : ui.bPicker; const query = text(picker.input.value).trim(); if (!query) { hideResults(picker); return; } const { results, total } = search(dataset.rows, query, 8); picker.results.replaceChildren(); if (results.length === 0) { picker.results.append(make("li", "pano-compare-noresult", "no ranked blogs match")); } else { for (const row of results) { const item = make("li"); const button = make("button", "pano-compare-result", optionLabel(row)); button.type = "button"; // Keep focus in the search box until the click selects the result. button.addEventListener("mousedown", (event) => event.preventDefault()); button.addEventListener("click", () => selectPicker(side, row.uri)); item.append(button); picker.results.append(item); } if (total > results.length) { picker.results.append( make("li", "pano-compare-more", `${exact.format(total)} matches; keep typing to narrow`), ); } } picker.results.hidden = false; } function wirePicker(picker, side) { picker.input.addEventListener("input", () => showResults(side)); picker.input.addEventListener("focus", () => { if (text(picker.input.value).trim()) showResults(side); }); picker.input.addEventListener("keydown", (event) => { if (event.key === "Escape" && !picker.results.hidden) { event.preventDefault(); hideResults(picker); return; } if (event.key === "ArrowDown") { const first = picker.results.querySelector("button"); if (first) { event.preventDefault(); first.focus(); } } if (event.key === "Enter") { const first = picker.results.querySelector("button"); if (first) { event.preventDefault(); first.click(); } } }); picker.input.addEventListener("blur", (event) => { // Keep the list while the keyboard is inside it; hide after a click away. if (picker.results.contains(event.relatedTarget)) return; setTimeout(() => hideResults(picker), 150); }); } function sideCard(label, entry, total) { const card = make("div", "pano-compare-side"); card.append(make("p", "pano-compare-side-label", label)); card.append(make("h3", "pano-compare-name", nameOf(entry))); if (entry.handle) card.append(make("p", "pano-compare-handle", `@${entry.handle}`)); const stats = make("dl", "stats find-stats"); if (Number.isFinite(entry.rank)) { stats.append(stat( "rank", Number.isFinite(total) && total > 0 ? `#${exact.format(entry.rank)} of ${exact.format(total)}` : `#${exact.format(entry.rank)}`, )); } if (Number.isFinite(entry.score)) stats.append(stat("score", entry.score.toFixed(2))); if (Number.isFinite(entry.percentile)) { stats.append(stat("percentile", entry.percentile.toFixed(2))); } if (Number.isFinite(entry.previousRank)) { stats.append(stat("previous run", movement(entry))); } card.append(stats); return card; } function bar(value) { const track = make("span", "pano-compare-bar"); track.setAttribute("aria-hidden", "true"); const fill = make("span"); fill.style.width = `${Number.isFinite(value) ? Math.max(0, Math.min(100, value)) : 0}%`; track.append(fill); return track; } function barRow(label, value) { const row = make("div", "pano-compare-bar-row"); row.append( make("span", "pano-compare-bar-label", label), bar(value), make("span", "pano-compare-bar-value", percentileText(value)), ); return row; } function gapNodes(comparison) { const { summary } = comparison; const lead = make("p", "pano-compare-lead"); if (summary.tied) { const winner = summary.leader === "a" ? summary.a : summary.leader === "b" ? summary.b : null; lead.textContent = winner ? `Scores are tied at ${summary.a.score.toFixed(1)}; ${nameOf(winner)} ranks first.` : `Scores are tied at ${summary.a.score.toFixed(1)}.`; } else if (summary.leader) { const leader = summary.leader === "a" ? summary.a : summary.b; const ranks = summary.rankGap; lead.textContent = `${nameOf(leader)} leads by ${(summary.scoreGap ?? 0).toFixed(1)} points` + (Number.isFinite(ranks) ? ` and ${exact.format(ranks)} rank${ranks === 1 ? "" : "s"}.` : "."); } else { lead.textContent = "These blogs do not have comparable scores."; } const stats = make("dl", "stats find-stats"); if (Number.isFinite(summary.rankGap)) { stats.append(stat("rank gap", exact.format(summary.rankGap))); } if (Number.isFinite(summary.scoreGap)) { stats.append(stat("score gap", summary.scoreGap.toFixed(1))); } return [lead, stats]; } function compositeNodes(comparison) { if (comparison.composites.length === 0) { return [make("p", "pano-compare-empty", "This run has no composites.")]; } return comparison.composites.map((entry) => { const row = make("div", "pano-compare-composite"); const head = make("div", "pano-compare-composite-head"); head.append( make("span", "pano-compare-composite-name", entry.name), make("span", "pano-compare-delta", signed(entry.delta)), ); const bars = make("div", "pano-compare-bars"); bars.append(barRow("A", entry.a), barRow("B", entry.b)); row.append(head, bars); return row; }); } function factorRow(row) { const line = make("div", "pano-compare-factor"); line.append( make("span", "pano-compare-factor-name", row.factor), make("span", "pano-compare-factor-value", `A ${percentileText(row.aPercentile)}`), make("span", "pano-compare-factor-value", `B ${percentileText(row.bPercentile)}`), make("span", "pano-compare-factor-value", `Δ ${signed(row.delta)}`), make("span", "pano-compare-factor-value", `weighted ${signed(row.pointsDelta)}`), ); return line; } function factorNodes(comparison) { const groups = new Map(); for (const row of comparison.factors) { if (!groups.has(row.categoryId)) groups.set(row.categoryId, []); groups.get(row.categoryId).push(row); } const openIds = new Set(); const topCategory = comparison.topFactors?.[0]?.categoryId; if (topCategory) openIds.add(topCategory); let largestId = null; let largestSize = -1; for (const entry of comparison.composites) { const size = Number.isFinite(entry.delta) ? Math.abs(entry.delta) : -1; if (size > largestSize) { largestId = entry.id; largestSize = size; } } if (largestId) openIds.add(largestId); const nodes = []; for (const composite of comparison.composites) { const rows = groups.get(composite.id); if (!rows?.length) continue; const details = make("details", "pano-compare-factor-group"); details.open = openIds.has(composite.id); const heading = make("summary"); heading.append( make("span", "pano-compare-factor-group-name", composite.name), make("span", "pano-compare-delta", signed(composite.delta)), ); details.append(heading); const list = make("div", "pano-compare-factor-rows"); for (const row of rows) list.append(factorRow(row)); details.append(list); nodes.push(details); } return nodes.length > 0 ? nodes : [make("p", "pano-compare-empty", "This run has no factor data.")]; } function buildShell() { const pickers = make("div", "pano-compare-pickers"); const aPicker = picker("blog A", "a"); const bPicker = picker("blog B", "b"); const swap = make("button", "pano-compare-swap", "swap"); swap.type = "button"; swap.addEventListener("click", () => { const a = ui.aUri; ui.aUri = ui.bUri; ui.bUri = a; for (const picker of [ui.aPicker, ui.bPicker]) { picker.input.value = ""; hideResults(picker); } renderCurrent(); changed(); }); pickers.append(aPicker.wrap, bPicker.wrap, swap); const sides = make("div", "pano-compare-sides"); const gap = make("div", "pano-compare-gap"); const explanation = make("p", "pano-compare-explanation"); const composites = make("div", "pano-compare-section"); composites.append(make("h3", undefined, "composites")); composites.append(make( "p", "pano-compare-legend", "bars are composite scores; delta is A minus B", )); const compositeList = make("div", "pano-compare-composites"); composites.append(compositeList); const factors = make("div", "pano-compare-section"); factors.append(make("h3", undefined, "factors")); factors.append(make( "p", "pano-compare-legend", "weighted points use the published weights; delta is A minus B", )); const factorList = make("div", "pano-compare-factors"); factors.append(factorList); const footer = make("p", "pano-compare-footer"); const note = make("p", "pano-compare-note", "Factors are percentiles within the ranked cohort."); const pickerNote = make( "p", "pano-compare-legend", "Only ranked publications can be compared. Search works by handle, name, DID, website, or at-uri.", ); const shell = make("div", "pano-compare-body"); shell.append(pickers, pickerNote, sides, gap, explanation, composites, factors, footer, note); content.replaceChildren(shell); ui = { aPicker, bPicker, aUri: null, bUri: null, sides, gap, explanation, compositeList, factorList, footer, }; wirePicker(aPicker, "a"); wirePicker(bPicker, "b"); const initial = chooseInitial(); ui.aUri = initial.a; ui.bUri = initial.b; renderCurrent(); changed(initial.record); aPicker.input.focus(); } function update() { const a = dataset.byUri.get(ui.aUri); const b = dataset.byUri.get(ui.bUri); if (!a || !b) { ui.sides.replaceChildren(); ui.gap.replaceChildren(make("p", "pano-compare-empty", "Choose two ranked blogs.")); ui.explanation.textContent = ""; ui.compositeList.replaceChildren(); ui.factorList.replaceChildren(); ui.footer.textContent = ""; return; } const comparison = comparePublications(a, b, dataset.tree); ui.sides.replaceChildren( sideCard("A", comparison.summary.a, dataset.rankedCount), sideCard("B", comparison.summary.b, dataset.rankedCount), ); ui.gap.replaceChildren(...gapNodes(comparison)); ui.explanation.textContent = explainComparison(comparison, dataset.tree); ui.compositeList.replaceChildren(...compositeNodes(comparison)); ui.factorList.replaceChildren(...factorNodes(comparison)); ui.footer.textContent = `published weights · run ${runDate(dataset.generatedAt)}`; } function changed(record = true) { if (!ui) return; if (record) remember(ui.aUri, ui.bUri); update(); } function applyPending() { if (!ui || !pendingUri) return; const uri = pendingUri; pendingUri = undefined; if (!dataset.byUri.has(uri)) return; selectPicker("a", uri); } let starting; function start() { if (ui?.aPicker) { applyPending(); return undefined; } if (starting) return starting; starting = (async () => { if (status) { status.hidden = false; status.textContent = "loading the full ranking…"; } content.replaceChildren(); try { await loadAll(); } catch (error) { console.error("[panoptiblog] could not load the full ranking", error); if (!dialog?.open) return; if (status) status.hidden = true; content.replaceChildren(failure(error)); return; } if (!dialog?.open) return; if (status) status.hidden = true; if (dataset.rows.length < 2) { content.replaceChildren(make( "p", "pano-compare-empty", "Compare needs at least two ranked blogs.", )); return; } buildShell(); })().finally(() => { starting = undefined; }); return starting; } function openCompare(uri) { if (!dialog) return; if (uri) pendingUri = uri; if (!dialog.open) { opener = document.activeElement; dialog.showModal(); openButton?.setAttribute("aria-expanded", "true"); } start(); } function closeCompare() { if (dialog?.open) dialog.close(); } if (dialog && openButton) { openButton.addEventListener("click", () => openCompare()); closeButton?.addEventListener("click", closeCompare); dialog.addEventListener("close", () => { openButton.setAttribute("aria-expanded", "false"); if (opener?.isConnected) opener.focus(); opener = undefined; }); dialog.addEventListener("click", (event) => { if (event.target !== dialog) return; const rect = dialog.getBoundingClientRect(); if ( event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom ) { closeCompare(); } }); document.addEventListener(EVENT, (event) => { const uri = text(event.detail?.uri); if (uri) openCompare(uri); }); const params = new URL(location.href).searchParams; if (params.get(PARAM) && !params.get("q")) openCompare(); }