Something went wrong. Try again.
Browser extension: detect and subscribe to standard.site publications on ATProto substandard.blog
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285import { accountLink, accountSeparator, accountWho, signInAccount, type SignInAccountOptions,} from '../../src/lib/signin'import substandardMark from '../../brand/wordmark.svg?raw'import threadbareMark from './assets/threadbare.svg?raw'
import init, { cancel, scan, thread_view } from './wasm/longread_wasm.js'import { completeCallback, isCallback, restoreSession, signOut, startSignIn, takeReturnHash, type Session,} from './auth'import { captureEvent, exportProperties, scanDoneProperties, scanFailedProperties, startAnalytics, threadOpenedProperties, type ScanStage,} from './analytics'import { copyArticle, markdownBody, renderedBody, splitFrontMatter } from './article'import { isOwnThread } from './gate'import { SESSION_ENDED, SIGN_IN_FAILED, signInFailureMessage } from './messages'import { createRuns } from './runs'import { clearScan, readScan, scanAgeLabel, writeScan, type CachedScan } from './scan-cache'import { scanEmptyNote, scanTruncationNote } from './scan-note'import { restoreScanView, SCAN_TITLE, threadTitle, type ScanViewState } from './scan-view'
interface AuthorRow { did: string handle: string display_name: string | null avatar: string | null}
interface ScoreFactor { id: string name: string weight: number scale: string detail: string raw: number | null bounded: number | null percentile: number | null}
interface ScoreCategory { id: string name: string weight: number raw: number | null percentile: number | null factors: ScoreFactor[]}
interface CanonicalScore { version: number cohort: string categories: ScoreCategory[] overall_raw: number | null overall_percentile: number | null notes: string[]}
interface ForkOption { uri: string posts: number date: string snippet: string chosen: boolean}
interface Fork { parent_uri: string parent_snippet: string options: ForkOption[]}
type LabelState = 'visible' | 'warn' | 'hidden'
interface ThreadRow { author: AuthorRow root_uri: string root_date: string post_count: number graphemes: number words: number likes: number reposts: number quotes: number replies: number dropped_branches: number score: number canonical_score: CanonicalScore labels: string[] label_state: LabelState forks: Fork[] topics: string[] root_text: string root_thumb: string | null url: string}
interface ThreadView { markdown: string topics: string[] post_count: number labels: string[] label_state: LabelState forks: Fork[]}
interface ScanResult { rows: ThreadRow[] truncated: boolean posts_read: number oldest_post_date: string | null longest_chain: number cancelled: boolean}
const RUN_OPTIONS = { since: 'all', minPosts: 5, minWords: 0, includeReplies: true,}
const MIN_PERCENTILE = 75const MIN_PERCENTILE_COHORT = 5const PAGE_SIZE = 50const LAST_HANDLE_KEY = 'threadbare:last-handle'
type Route = | { kind: 'scan' } | { kind: 'thread'; uri: string; branch: string | null }
const appRoot = document.querySelector<HTMLElement>('#app')if (!appRoot) throw new Error('missing #app')const app: HTMLElement = appRoot
const threadbareTarget = document.querySelector<HTMLElement>('#threadbare-mark')if (threadbareTarget) threadbareTarget.innerHTML = threadbareMarkconst substandardTarget = document.querySelector<HTMLElement>('#substandard-mark')if (substandardTarget) substandardTarget.innerHTML = substandardMark
const revealedRows = new Set<string>()const revealedThreads = new Set<string>()const rowViews = new Map<string, ThreadView>()let currentRows: ThreadRow[] = []let currentEmptyNote = ''let currentNote = ''let currentContainer: HTMLElement | null = nulllet resultLimit = PAGE_SIZElet showHidden = localStorage.getItem('threadbare:show-hidden') === '1'let showLower = falselet currentSession: Session | undefinedlet currentDid = ''let accountOpen = falselet formHandle = localStorage.getItem(LAST_HANDLE_KEY) ?? ''let accountError = ''let accountHandle = ''let rememberedScanView: Partial<ScanViewState> | undefined
// Test builds only. A normal build leaves this unset and requires OAuth.const TEST_DID = import.meta.env.VITE_THREADBARE_TEST_DID as string | undefined
let wasmReady: Promise<unknown> | undefinedlet wasmLoaded = false
const runs = createRuns(() => { if (wasmLoaded) cancel()})
function loadWasm(): Promise<unknown> { if (wasmReady) return wasmReady const ready = init().then(() => { wasmLoaded = true }) wasmReady = ready return ready}
/* Sign-in */
function errorText(error: unknown): string { return error instanceof Error ? error.message : String(error)}
function shortDid(did: string): string { return did.length > 26 ? `${did.slice(0, 23)}…` : did}
function rememberHandle(handle: string): void { if (!handle) return formHandle = handle try { localStorage.setItem(LAST_HANDLE_KEY, handle) } catch { // The form still remembers it for this page load. }}
async function fetchHandle(did: string): Promise<string | undefined> { try { const response = await fetch( `https://public.api.bsky.app/xrpc/app.bsky.actor.getProfile?actor=${encodeURIComponent(did)}`, ) if (!response.ok) return undefined const profile = (await response.json()) as { handle?: unknown } return typeof profile.handle === 'string' ? profile.handle : undefined } catch { return undefined }}
const CALLOUT = 'find your long threads!'
function accountOptions(open: boolean): SignInAccountOptions { return { open, callout: CALLOUT, initialHandle: formHandle, error: accountError, onOpen: openSignIn, onChange: (handle) => { formHandle = handle }, onSubmit: (handle) => void submitSignIn(handle), onCancel: () => { accountOpen = false accountError = '' renderAccount() }, idPrefix: 'threadbare', }}
function renderAccount(): void { const host = document.querySelector<HTMLElement>('#threadbare-account') if (!host) return host.classList.toggle('is-signed-in', Boolean(currentSession)) if (!currentSession) { host.replaceChildren(signInAccount(accountOptions(accountOpen))) return } host.replaceChildren( accountWho(accountHandle ? `@${accountHandle}` : shortDid(currentDid)), accountSeparator(), accountLink('sign out', () => void leave()), )}
function focusHandle(): void { document.querySelector<HTMLInputElement>('#threadbare-handle')?.focus()}
function openSignIn(): void { accountOpen = true accountError = '' renderAccount() focusHandle()}
async function submitSignIn(value: string): Promise<void> { const handle = value.trim().replace(/^@/, '') formHandle = handle if (!handle) { accountError = 'enter your handle' renderAccount() focusHandle() return } accountError = '' renderAccount() rememberHandle(handle) try { await startSignIn(handle) } catch (error) { console.debug('[threadbare] sign-in failed', error) accountError = signInFailureMessage(error) renderAccount() focusHandle() }}
function renderLogin(message?: string): void { document.title = SCAN_TITLE document.body.dataset.auth = 'out' if (message) { accountOpen = true accountError = message } app.innerHTML = ` <section class="panel login"> <h1 tabindex="-1">Find your threads worth a blog post</h1> <p class="hint">threadbare reads your Bluesky account to find the seed of your next blog posts. It scores based on content with enough room and craft to stand alone, not just the most-liked ones. The export format is a Markdown document.</p> <figure class="path"> <div class="path-visual" aria-hidden="true"> <div class="path-thread"> <div class="path-thread-head"> <span class="path-avatar">@</span> <span class="path-name">your thread</span> <span class="path-index">1/7</span> </div> <div class="path-lines"> <span class="path-line"></span> <span class="path-line path-line-short"></span> <span class="path-line path-line-short"></span> </div> <div class="path-meta">7 posts · six composite scorers</div> </div> <div class="path-arrow"> <span class="path-arrow-label">export Markdown</span> <svg viewBox="0 0 64 24"><path d="M2 12h52M44 4l10 8-10 8" /></svg> </div> <div class="path-post"> <div class="path-pub"><span>your publication</span><span>standard.site</span></div> <span class="path-title">A thread worth a post</span> <span class="path-line"></span> <span class="path-line"></span> <span class="path-line path-line-short"></span> </div> </div> <figcaption>The long threads worth writing up are surfaced by the same six-composite tree as panoptiblog, then exported as a Markdown document for your standard.site post.</figcaption> </figure> </section>` renderAccount() focusViewHeading()}
function showSession(session: Session): void { currentSession = session currentDid = session.sub accountOpen = false accountError = '' accountHandle = '' document.body.dataset.auth = 'in' renderAccount() void fetchHandle(session.sub).then((handle) => { if (!handle || currentDid !== session.sub) return accountHandle = handle rememberHandle(handle) renderAccount() })}
async function leave(): Promise<void> { const session = currentSession const did = currentDid currentSession = undefined currentDid = '' rememberedScanView = undefined if (did) await clearScan(did) try { if (session) await signOut(session) } catch (error) { console.debug('[threadbare] sign-out failed', error) } location.reload()}
async function boot(): Promise<void> { document.body.dataset.auth = 'out' if (TEST_DID) { if (isCallback()) history.replaceState(null, '', '/' + takeReturnHash()) showSession({ sub: TEST_DID, signOut: async () => {} }) void renderRoute() return } if (isCallback()) { try { const session = await completeCallback() if (session) { showSession(session) history.replaceState(null, '', '/' + takeReturnHash()) void renderRoute() return } } catch (error) { console.debug('[threadbare] OAuth callback failed', error) history.replaceState(null, '', '/' + takeReturnHash()) renderLogin(SIGN_IN_FAILED) return } history.replaceState(null, '', '/' + takeReturnHash()) } try { const session = await restoreSession() if (session) { showSession(session) void renderRoute() return } } catch (error) { console.debug('[threadbare] session restore failed', error) renderLogin(SESSION_ENDED) return } renderLogin()}
function currentRoute(): Route { const raw = location.hash.replace(/^#\/?/, '') const queryIndex = raw.indexOf('?') const path = queryIndex === -1 ? raw : raw.slice(0, queryIndex) const params = new URLSearchParams(queryIndex === -1 ? '' : raw.slice(queryIndex + 1))
if (path === 'thread') { const uri = params.get('uri') if (uri) return { kind: 'thread', uri, branch: params.get('branch') } } return { kind: 'scan' }}
async function renderRoute(): Promise<void> { const token = runs.begin() if (!currentSession) { renderLogin() return } const route = currentRoute() if (route.kind === 'thread') rememberScanView() try { if (route.kind === 'scan') { document.title = SCAN_TITLE renderScan(token) } else if (route.kind === 'thread') { document.title = threadTitle() await renderThread(token, route.uri, route.branch) } } catch (error) { if (runs.isActive(token)) showError(error) }}
/** Keep enough of the scan view to return to the same place from a thread. */function rememberScanView(): void { const results = document.querySelector<HTMLElement>('#results') if (!results) return rememberedScanView = { showLower, resultLimit, scrollY: window.scrollY, criteriaOpen: document.querySelector<HTMLDetailsElement>('.criteria')?.open ?? false, openScores: openScoreUris(results), }}
/** Move focus to the heading of the view just rendered, without scrolling it. */function focusViewHeading(): void { document.querySelector<HTMLElement>('#app .panel h1')?.focus({ preventScroll: true })}
/* Results */
function setResults( container: HTMLElement, rows: ThreadRow[], emptyNote = '', note = '', reset = true,): void { currentRows = rows currentEmptyNote = emptyNote currentNote = note currentContainer = container if (reset) { showLower = false resultLimit = PAGE_SIZE } drawResults()}
type ResultsFocus = { control: 'show-more' | 'show-lower' | 'show-hidden' previousShown: ThreadRow[]}
function drawResults(focus?: ResultsFocus): void { const container = currentContainer if (!container) return const hidden = currentRows.filter((row) => row.label_state === 'hidden') const visibleRows = currentRows.filter( (row) => row.label_state !== 'hidden' || showHidden, ) const sorted = [...visibleRows].sort((left, right) => right.score - left.score) const cutoffApplies = currentRows.length >= MIN_PERCENTILE_COHORT const cutoff = cutoffApplies ? MIN_PERCENTILE : 0 const below = cutoff > 0 ? sorted.filter((row) => row.score < cutoff) : [] const rows = cutoff > 0 && !showLower ? sorted.filter((row) => row.score >= cutoff) : sorted const shown = rows.slice(0, resultLimit) let html = currentNote ? `<p class="scan-note">${esc(currentNote)}</p>` : '' if (rows.length) { html += threadList(shown) } else { html += currentRows.length === 0 ? `<p class="empty">${esc(currentEmptyNote || 'No threads meet the criteria.')}</p>` : '<p class="empty">No threads at the top-quarter cutoff. Show lower-scoring threads.</p>' } if (rows.length > resultLimit) { html += `<button type="button" class="show-more">Show more (${rows.length - resultLimit})</button>` } if (below.length > 0) { html += `<button type="button" class="show-lower">${ showLower ? 'Hide' : 'Show' } ${below.length} lower-scoring thread${below.length === 1 ? '' : 's'}</button>` } if (hidden.length > 0) { html += `<button type="button" class="show-hidden">${ showHidden ? 'Hide' : 'Show' } ${hidden.length} hidden by content labels</button>` } container.innerHTML = html bindThreadRows(container) container.querySelector('.show-more')?.addEventListener('click', () => { resultLimit += PAGE_SIZE drawResults({ control: 'show-more', previousShown: shown }) }) container.querySelector('.show-hidden')?.addEventListener('click', () => { showHidden = !showHidden localStorage.setItem('threadbare:show-hidden', showHidden ? '1' : '0') drawResults({ control: 'show-hidden', previousShown: shown }) }) container.querySelector('.show-lower')?.addEventListener('click', () => { showLower = !showLower resultLimit = PAGE_SIZE drawResults({ control: 'show-lower', previousShown: shown }) }) if (focus) restoreResultsFocus(container, focus, shown)}
/** Keep keyboard focus in the list after drawResults replaces it. */function restoreResultsFocus( container: HTMLElement, focus: ResultsFocus, shown: ThreadRow[],): void { const control = container.querySelector<HTMLElement>(`.${focus.control}`) if (control) { control.focus() return } const previous = new Set(focus.previousShown.map((row) => row.root_uri)) const revealed = shown.find((row) => !previous.has(row.root_uri)) if (!revealed) return const card = [...container.querySelectorAll<HTMLElement>('.thread-card')].find( (element) => element.dataset.uri === revealed.root_uri, ) card?.querySelector<HTMLElement>('.thread-open')?.focus()}
/* Scan */
function openScoreUris(container: HTMLElement): string[] { return [...container.querySelectorAll<HTMLElement>('.score-details[open]')] .map((detail) => detail.closest<HTMLElement>('.thread-card')?.dataset.uri) .filter((uri): uri is string => typeof uri === 'string')}
function restoreOpenScores(container: HTMLElement, uris: string[]): void { if (!uris.length) return const open = new Set(uris) container.querySelectorAll<HTMLElement>('.thread-card[data-uri]').forEach((card) => { const details = card.querySelector<HTMLDetailsElement>('.score-details') if (details) details.open = open.has(card.dataset.uri ?? '') })}
function renderScan(token: number): void { const restore = rememberedScanView && restoreScanView(rememberedScanView, PAGE_SIZE) rememberedScanView = undefined
app.innerHTML = ` <section class="panel"> <h1 tabindex="-1">Surface the threads worth writing</h1> <p class="hint">Reads your own posts, joins self-replies and reply-started chains, and scores the long ones with the same six-composite tree as panoptiblog. Open a thread to copy its Markdown or download the full file.</p> <details class="criteria"> <summary>What makes a thread worth a blog post?</summary> <div class="criteria-body"> <p><strong>Long enough to stand alone.</strong> Five or more posts. The scan reads all available history and includes threads that start as replies. There is no word floor; the score weighs prose and depth.</p> <p><strong>One line of thought.</strong> A long self-thread already has a voice, an argument and an ending. Link dumps and short reaction chains fall on depth, structure and continuity.</p> <p><strong>Not just the best performing.</strong> Audience — likes, reposts and quotes — is one of six composites. A quiet thread with strong writing, volume and continuity can outrank a popular but thin one. Engagement stays visible as a diagnostic.</p> </div> </details> <div class="scan-status"> <p id="status" class="status" role="status"></p> <button type="button" id="scan-cancel" class="cancel" hidden>Cancel</button> </div> <p id="scan-meta" class="scan-meta" hidden> <span id="scan-age"></span> <button type="button" id="rescan">Rescan</button> </p> </section> <div id="scan-error"></div> <section id="results" class="results"></section>`
const results = must(document.querySelector<HTMLElement>('#results')) const status = must(document.querySelector<HTMLElement>('#status')) const errorHost = must(document.querySelector<HTMLElement>('#scan-error')) const cancelButton = must(document.querySelector<HTMLButtonElement>('#scan-cancel')) const meta = must(document.querySelector<HTMLElement>('#scan-meta')) const age = must(document.querySelector<HTMLElement>('#scan-age')) const rescan = must(document.querySelector<HTMLButtonElement>('#rescan'))
const setScanning = (scanning: boolean): void => { cancelButton.hidden = !scanning cancelButton.disabled = false }
const retry = (): void => void run()
cancelButton.addEventListener('click', () => { cancel() cancelButton.disabled = true status.textContent = 'Cancelling…' })
const onProgress = (count: number): void => { if (!runs.isActive(token)) return status.textContent = `Reading public records… ${count.toLocaleString()} posts` }
if (restore?.criteriaOpen) { document.querySelector<HTMLDetailsElement>('.criteria')!.open = true } if (restore) { showLower = restore.showLower resultLimit = restore.resultLimit } focusViewHeading()
const showAge = (savedAt: number): void => { age.textContent = `Scanned ${scanAgeLabel(savedAt)}` meta.hidden = false }
let busy = false const run = async (cached?: CachedScan<ScanResult>): Promise<void> => { if (busy) return busy = true rescan.disabled = true if (!cached) status.textContent = 'Reading public records…' const started = performance.now() let stage: ScanStage = 'load' errorHost.replaceChildren() let cancelled = false try { await loadWasm() if (!runs.isActive(token)) return stage = 'scan' setScanning(true) const result = (await scan( currentDid, RUN_OPTIONS, currentDid, onProgress, )) as ScanResult if (!runs.isActive(token)) return if (result.cancelled) { cancelled = true status.textContent = 'Scan cancelled.' if (!cached) setResults(results, [], 'Scan cancelled.') return } const open = cached ? openScoreUris(results) : [] setResults( results, result.rows, scanEmptyNote(result), scanTruncationNote(result), !cached, ) if (cached) restoreOpenScores(results, open) void writeScan(currentDid, result) if (!result.cancelled) { showAge(Date.now()) captureEvent( 'scan_done', scanDoneProperties({ durationMs: performance.now() - started, rows: result.rows.length, truncated: result.truncated, fromCache: false, }), ) } if (result.truncated) { toast(`Stopped after ${result.posts_read} posts.`) } } catch (error) { if (runs.isActive(token)) { captureEvent('scan_failed', scanFailedProperties(cached ? 'refresh' : stage, error)) } if (cached) { toast('Could not refresh; showing saved results.') showError(error, errorHost, { message: 'Could not refresh the scan.', retry, }) } else if (runs.isActive(token)) { showError(error, errorHost, { message: 'The scan could not finish.', retry, }) } } finally { busy = false if (runs.isActive(token)) { setScanning(false) rescan.disabled = false if (!cancelled) status.textContent = '' } } }
rescan.addEventListener('click', () => { if (busy) return status.textContent = 'Reading public records…' void run() })
status.textContent = 'Checking saved results…' void (async () => { const cached = await readScan<ScanResult>(currentDid) if (!runs.isActive(token)) return if (cached && Array.isArray(cached.result.rows)) { setResults( results, cached.result.rows, scanEmptyNote(cached.result), scanTruncationNote(cached.result), false, ) showAge(cached.savedAt) if (restore) { restoreOpenScores(results, restore.openScores) requestAnimationFrame(() => { if (runs.isActive(token)) window.scrollTo(0, restore.scrollY) }) } if (cached.fresh) { status.textContent = '' captureEvent( 'scan_done', scanDoneProperties({ durationMs: 0, rows: cached.result.rows.length, truncated: cached.result.truncated, fromCache: true, }), ) return } status.textContent = 'Refreshing…' } void run(cached) })()}
/* Thread */
async function renderThread(token: number, uri: string, branch: string | null): Promise<void> { app.innerHTML = '<p class="empty">Reading thread…</p>' await loadWasm() if (!runs.isActive(token)) return const view = (await thread_view(uri, branch, currentDid)) as ThreadView if (!runs.isActive(token)) return rowViews.set(uri, view) if (!view.markdown.trim()) { app.innerHTML = '<p class="empty">Nothing to show for that post.</p><p><a class="back-link" href="#scan">← threads</a></p>' document.querySelector<HTMLElement>('.back-link')?.focus() return } renderArticle(view, uri)}
function renderArticle(view: ThreadView, sourceUri: string, focus = true): void { const { meta, body } = splitFrontMatter(view.markdown) const title = meta.title || 'Untitled' const author = meta.author || '' const date = meta.publishDate ? meta.publishDate.slice(0, 10) : '' const source = safeHref(meta.source) const rendered = renderedBody(body) const byline = [ date ? esc(date) : '', author ? `${author.startsWith('@') ? '' : '@'}${esc(author)}` : '', source ? `<a href="${esc(source)}" target="_blank" rel="noreferrer">Bluesky</a>` : '', ] .filter(Boolean) .join(' · ') const revealed = revealedThreads.has(sourceUri) const contentVisible = view.label_state === 'visible' || revealed const warning = view.label_state !== 'visible' && !revealed const branches = view.forks.length ? branchPanel(view.forks, sourceUri) : '' const canExport = isOwnThread(sourceUri, currentDid) const index = view.post_count ? `· <span class="thread-view-index">1<span class="thread-total">/${view.post_count}</span></span>` : ''
document.title = threadTitle(title) app.innerHTML = ` <article class="panel thread ph-no-capture"> <a class="back-link" href="#scan">← threads</a> <header class="thread-header"> <h1 tabindex="-1">${esc(title)}</h1> <p class="meta">${byline}${index ? ` ${index}` : ''}</p> ${ view.topics.length ? `<p class="thread-topics"><span class="topics-label">about</span>${topicChips(view.topics)}</p>` : '' } ${branches} <div class="actions"> ${ canExport ? `<button type="button" data-action="copy">Copy Markdown</button> <button type="button" data-action="copy-link">Copy Bluesky link</button> <button type="button" data-action="download">Download .md</button>` : '<span class="gate-note">Only the thread author can export it.</span>' } </div> <p id="action-status" class="status" role="status"></p> </header> ${ warning ? `<div class="content-warning thread-warning"><span class="topics-label">warned</span><span>${esc(labelText(view.labels))}</span><button type="button" data-reveal-thread="${esc(sourceUri)}">Show</button></div>` : `<div class="rendered">${rendered}</div>` } </article>`
const status = must(document.querySelector<HTMLElement>('#action-status')) app.querySelector<HTMLButtonElement>('button[data-action="copy"]')?.addEventListener( 'click', async () => { try { await copyArticle(markdownBody(view.markdown), rendered) if (status) status.textContent = 'Copied.' captureEvent('export', exportProperties('copy_markdown', 'thread', true)) } catch { if (status) status.textContent = 'Copy failed; download the Markdown instead.' captureEvent('export', exportProperties('copy_markdown', 'thread', false)) } }, ) app.querySelector<HTMLButtonElement>('button[data-action="copy-link"]')?.addEventListener( 'click', async () => { const link = source || blueskyLink(sourceUri) if (!link) { if (status) status.textContent = 'No Bluesky link found for this thread.' captureEvent('export', exportProperties('copy_link', 'thread', false)) return } try { await navigator.clipboard.writeText(link) if (status) status.textContent = 'Copied Bluesky link.' captureEvent('export', exportProperties('copy_link', 'thread', true)) } catch { if (status) status.textContent = 'Could not copy the Bluesky link.' captureEvent('export', exportProperties('copy_link', 'thread', false)) } }, ) app.querySelector<HTMLButtonElement>('button[data-action="download"]')?.addEventListener( 'click', () => { try { downloadMarkdown(view.markdown, title) captureEvent('export', exportProperties('download', 'thread', true)) } catch { if (status) status.textContent = 'Download failed.' captureEvent('export', exportProperties('download', 'thread', false)) } }, ) app.querySelector<HTMLButtonElement>('button[data-reveal-thread]')?.addEventListener( 'click', () => { revealedThreads.add(sourceUri) renderArticle(view, sourceUri, false) }, ) if (contentVisible) { // The links in the rendered article open in a new tab. app.querySelectorAll<HTMLAnchorElement>('.rendered a').forEach((link) => { link.target = '_blank' link.rel = 'noreferrer' }) } if (focus) focusViewHeading()}
function branchPanel(forks: Fork[], sourceUri: string): string { return `<div class="branch-panel"><span class="topics-label">branches</span>${forks .map( (fork) => ` <div class="fork"> <span class="fork-parent">${esc(fork.parent_snippet)}</span> <ul>${fork.options .map( (option) => ` <li class="${option.chosen ? 'chosen' : ''}"> <a href="#thread?uri=${encodeURIComponent(sourceUri)}&branch=${encodeURIComponent(option.uri)}"> ${option.posts} posts · ${esc(option.date)} · ${esc(option.snippet)} </a> </li>`, ) .join('')}</ul> </div>`, ) .join('')}</div>`}
/* Row cards */
function countLabel(value: number, singular: string, plural = `${singular}s`): string { return `${value} ${value === 1 ? singular : plural}`}
function topicChips(topics: string[]): string { return topics.map((topic) => `<span class="chip">${esc(topic)}</span>`).join('')}
function labelText(labels: string[]): string { const names: Record<string, string> = { '!warn': 'content warning', '!hide': 'hidden', '!no-unauthenticated': 'hidden', porn: 'adult content', sexual: 'adult content', nudity: 'nudity', 'graphic-media': 'graphic media', gore: 'gore', spam: 'spam', scam: 'scam', impersonation: 'impersonation', misleading: 'misleading', } const unique = [...new Set(labels.map((label) => names[label] ?? label))] return unique.length ? unique.join(', ') : 'content warning'}
function category(row: ThreadRow, name: string): ScoreCategory | undefined { return row.canonical_score.categories.find((item) => item.name === name)}
function categoryPercentile(row: ThreadRow, name: string): number { return category(row, name)?.percentile ?? 0}
function fixed(value: number | null | undefined, places: number): string { return value === null || value === undefined ? '-' : value.toFixed(places)}
function scorePanel(row: ThreadRow): string { const score = row.canonical_score const categories = score.categories .map((item) => { const factors = item.factors .map( (factor) => ` <div class="score-factor"> <span class="score-factor-name">${esc(factor.name)}</span> <span class="score-factor-meta">w ${factor.weight.toFixed(2)} · ${esc(factor.scale)}</span> <span class="score-factor-values">raw ${fixed(factor.raw, 3)} · p${fixed(factor.percentile, 0)}</span> <span class="score-factor-detail">${esc(factor.detail)}</span> </div>`, ) .join('') return ` <section class="score-category"> <div class="score-category-head"> <span class="score-category-name">${esc(item.name)}</span> <span class="score-category-meta">w ${item.weight.toFixed(2)} · raw ${fixed(item.raw, 2)} · p${fixed(item.percentile, 0)}</span> </div> ${factors} </section>` }) .join('') const notes = score.notes.map((note) => `<li>${esc(note)}</li>`).join('') return ` <div class="score-panel"> <p class="score-formula">panoptiblog tree v${score.version} · ${esc(score.cohort)}</p> <p class="score-context">A percentile among the scanned threads, not a global popularity rank. Audience is one of six composites; engagement is a diagnostic.</p> <dl> <div><dt>overall</dt><dd>p${fixed(score.overall_percentile, 0)} · raw ${fixed(score.overall_raw, 3)}</dd></div> <div><dt>length</dt><dd>${row.words} words · ${row.graphemes} graphemes · ${row.post_count} posts</dd></div> <div><dt>engagement</dt><dd>${countLabel(row.likes, 'like')} · ${countLabel(row.reposts, 'repost')} · ${countLabel(row.quotes, 'quote')} · ${countLabel(row.replies, 'reply', 'replies')}</dd></div> </dl> <div class="score-categories">${categories}</div> ${notes ? `<ul class="score-notes">${notes}</ul>` : ''} </div>`}
function threadList(rows: ThreadRow[]): string { const cards = rows .map((row, rank) => { const topics = row.topics ?? [] const shown = topics.slice(0, 3) const more = topics.length - shown.length const style = Math.round(categoryPercentile(row, 'Style')) const scoreTitle = [ `overall p${Math.round(row.score)}`, ...row.canonical_score.categories.map( (item) => `${item.name} p${fixed(item.percentile, 0)}`, ), ].join(' · ') const displayName = row.author.display_name?.trim() const name = displayName || `@${row.author.handle}` const handle = displayName ? `<span class="root-handle">@${esc(row.author.handle)}</span>` : '' const avatar = row.author.avatar ? `<img class="root-avatar" src="${esc(row.author.avatar)}" alt="" loading="lazy" />` : `<span class="root-avatar root-monogram">${esc((displayName || row.author.handle).slice(0, 1).toUpperCase())}</span>` const profileUrl = `https://bsky.app/profile/${row.author.did}` const revealed = revealedRows.has(row.root_uri) const contentVisible = row.label_state === 'visible' || revealed const warning = row.label_state !== 'visible' && !revealed ? `<div class="content-warning"><span class="topics-label">warned</span><span>${esc(labelText(row.labels))}</span><button type="button" data-reveal="${esc(row.root_uri)}">Show</button></div>` : `<p class="root-snippet">${esc(row.root_text)}</p>` const thumb = contentVisible && row.root_thumb ? `<img class="thread-thumb" src="${esc(row.root_thumb)}" alt="" loading="lazy" />` : '' const sideBranches = row.forks.reduce( (total, fork) => total + fork.options.filter((option) => !option.chosen).length, 0, ) const branches = sideBranches ? `<a class="thread-branches" href="#thread?uri=${encodeURIComponent(row.root_uri)}">⑂ ${sideBranches}</a>` : '' const canExport = isOwnThread(row.root_uri, currentDid) const actions = ` <details class="row-menu"> <summary title="Thread actions" aria-label="Thread actions">⋯</summary> <div class="row-menu-panel"> ${ canExport ? '<button type="button" data-row-action="copy">Copy Markdown</button><button type="button" data-row-action="copy-link">Copy Bluesky link</button>' : `<span class="row-menu-note">Only @${esc(row.author.handle)} can export this thread.</span>` } <a href="${esc(row.url)}" target="_blank" rel="noreferrer">Open on Bluesky</a> </div> </details>` return ` <article class="thread-card ph-no-capture${row.label_state === 'hidden' ? ' thread-card--hidden' : ''}" data-uri="${esc(row.root_uri)}" data-rank="${rank + 1}"> <div class="thread-spine" aria-label="post 1 of ${row.post_count}"> <span class="thread-index">1<span class="thread-total">/${row.post_count}</span></span> <span class="thread-line" aria-hidden="true"></span> </div> ${avatar} <div class="thread-body"> <div class="thread-head"> <a class="root-name" href="${esc(profileUrl)}" target="_blank" rel="noreferrer">${esc(name)}</a> ${handle} <span class="root-date">${esc(row.root_date)}</span> ${row.label_state === 'hidden' ? '<span class="thread-hidden">hidden</span>' : ''} ${actions} </div> ${warning} <div class="thread-foot"> ${ contentVisible ? `<span class="root-engagement"> <span title="${countLabel(row.likes, 'like')}" aria-label="${countLabel(row.likes, 'like')}">♥ ${row.likes}</span> <span title="${countLabel(row.reposts, 'repost')}" aria-label="${countLabel(row.reposts, 'repost')}">⇄ ${row.reposts}</span> <span title="${countLabel(row.replies, 'reply', 'replies')}" aria-label="${countLabel(row.replies, 'reply', 'replies')}">↩ ${row.replies}</span> <span title="${countLabel(row.quotes, 'quote')}" aria-label="${countLabel(row.quotes, 'quote')}">❝ ${row.quotes}</span> </span>` : '' } ${ contentVisible && shown.length ? `<span class="thread-topics"><span class="topics-label">about</span>${topicChips(shown)}${ more > 0 ? `<span class="chip">+${more}</span>` : '' }</span>` : '' } ${branches} <a class="thread-open" href="#thread?uri=${encodeURIComponent(row.root_uri)}" aria-label="Open thread by @${esc(row.author.handle)}">open →</a> </div> <details class="score-details"> <summary title="${esc(scoreTitle)}">p${Math.round(row.score)} · style ${style}</summary> ${scorePanel(row)} </details> </div> ${thumb} </article>` }) .join('') return `<div class="thread-list">${cards}</div>`}
function bindThreadRows(container: HTMLElement): void { container.querySelectorAll<HTMLElement>('.thread-card[data-uri]').forEach((card) => { const uri = card.dataset.uri const rank = Number(card.dataset.rank) const reportOpen = () => captureEvent('thread_opened', threadOpenedProperties(rank)) const open = () => { if (!uri) return reportOpen() location.hash = `#thread?uri=${encodeURIComponent(uri)}` } card.querySelectorAll<HTMLAnchorElement>('a.thread-open, a.thread-branches').forEach( (link) => link.addEventListener('click', reportOpen), ) card.addEventListener('click', (event) => { if ((event.target as HTMLElement).closest('a, button, summary, details, input, textarea')) { return } open() }) card.querySelectorAll<HTMLButtonElement>('[data-row-action]').forEach((button) => { button.addEventListener('click', async (event) => { event.stopPropagation() if (!uri) return const menu = button.closest<HTMLDetailsElement>('.row-menu') if (!isOwnThread(uri, currentDid)) { if (menu) menu.open = false toast('Only the author can export this thread.') return } const kind = button.dataset.rowAction === 'copy' ? 'copy_markdown' : 'copy_link' const report = (ok: boolean) => captureEvent('export', exportProperties(kind, 'row', ok)) try { if (button.dataset.rowAction === 'copy') { const view = rowViews.get(uri) ?? (await summaryFor(uri)) await copyMarkdown(view) toast('Copied Markdown.') report(true) } else if (button.dataset.rowAction === 'copy-link') { const link = blueskyLink(uri) if (!link) { toast('No Bluesky link found for this thread.') report(false) } else { await navigator.clipboard.writeText(link) toast('Copied Bluesky link.') report(true) } } } catch (error) { report(false) toast(error instanceof Error ? error.message : String(error)) } finally { if (menu) menu.open = false } }) }) card.querySelectorAll<HTMLButtonElement>('[data-reveal]').forEach((button) => { button.addEventListener('click', (event) => { event.stopPropagation() const reveal = button.dataset.reveal if (reveal) { revealedRows.add(reveal) drawResults() } }) }) })}
async function summaryFor(uri: string): Promise<ThreadView> { const cached = rowViews.get(uri) if (cached) return cached await loadWasm() const view = (await thread_view(uri, null, currentDid)) as ThreadView rowViews.set(uri, view) return view}
function copyMarkdown(view: ThreadView): Promise<void> { const { body } = splitFrontMatter(view.markdown) return copyArticle(markdownBody(view.markdown), renderedBody(body))}
/* Helpers */
/** The public Bluesky URL for a thread root at-uri. */function blueskyLink(uri: string): string { const match = uri.match(/^at:\/\/([^/]+)\/app\.bsky\.feed\.post\/([^/?#]+)/) return match ? `https://bsky.app/profile/${match[1]}/post/${match[2]}` : ''}
function downloadMarkdown(markdown: string, title: string): void { const blob = new Blob([markdown], { type: 'text/markdown;charset=utf-8' }) const url = URL.createObjectURL(blob) const link = document.createElement('a') link.href = url link.download = `${slug(title)}.md` document.body.append(link) link.click() link.remove() URL.revokeObjectURL(url)}
function slug(title: string): string { const value = title .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, '') .slice(0, 60) return value || 'thread'}
interface ErrorOptions { message?: string retry?: () => void}
function showError( error: unknown, container: HTMLElement = app, options: ErrorOptions = {},): void { const raw = errorText(error) const retry = options.retry container.innerHTML = ` <div class="error" role="alert"> <p>${esc(options.message ?? 'Could not load this page.')}</p> ${retry ? '<button type="button" class="retry">Try again</button>' : ''} <details><summary>Details</summary><pre>${esc(raw)}</pre></details> </div>` if (retry) container.querySelector<HTMLButtonElement>('.retry')?.addEventListener('click', retry)}
function toast(message: string): void { const element = document.querySelector<HTMLElement>('#toast') if (!element) return element.textContent = message element.classList.add('show') window.setTimeout(() => element.classList.remove('show'), 2200)}
function safeHref(value: string | null | undefined): string | null { if (!value) return null try { const url = new URL(value, location.href) if (url.protocol === 'http:' || url.protocol === 'https:') return url.toString() } catch { // fall through } return null}
function must<T>(value: T | null): T { if (value === null) throw new Error('missing element') return value}
function esc(value: unknown): string { return String(value ?? '').replace( /[&<>"']/g, (character) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', })[character] as string, )}
window.addEventListener('hashchange', () => void renderRoute())void boot()void startAnalytics()