import { 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 = 75 const MIN_PERCENTILE_COHORT = 5 const PAGE_SIZE = 50 const LAST_HANDLE_KEY = 'threadbare:last-handle' type Route = | { kind: 'scan' } | { kind: 'thread'; uri: string; branch: string | null } const appRoot = document.querySelector('#app') if (!appRoot) throw new Error('missing #app') const app: HTMLElement = appRoot const threadbareTarget = document.querySelector('#threadbare-mark') if (threadbareTarget) threadbareTarget.innerHTML = threadbareMark const substandardTarget = document.querySelector('#substandard-mark') if (substandardTarget) substandardTarget.innerHTML = substandardMark const revealedRows = new Set() const revealedThreads = new Set() const rowViews = new Map() let currentRows: ThreadRow[] = [] let currentEmptyNote = '' let currentNote = '' let currentContainer: HTMLElement | null = null let resultLimit = PAGE_SIZE let showHidden = localStorage.getItem('threadbare:show-hidden') === '1' let showLower = false let currentSession: Session | undefined let currentDid = '' let accountOpen = false let formHandle = localStorage.getItem(LAST_HANDLE_KEY) ?? '' let accountError = '' let accountHandle = '' let rememberedScanView: Partial | 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 | undefined let wasmLoaded = false const runs = createRuns(() => { if (wasmLoaded) cancel() }) function loadWasm(): Promise { 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 { 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('#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('#threadbare-handle')?.focus() } function openSignIn(): void { accountOpen = true accountError = '' renderAccount() focusHandle() } async function submitSignIn(value: string): Promise { 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 = ` ` 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 { 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 { 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 { 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('#results') if (!results) return rememberedScanView = { showLower, resultLimit, scrollY: window.scrollY, criteriaOpen: document.querySelector('.criteria')?.open ?? false, openScores: openScoreUris(results), } } /** Move focus to the heading of the view just rendered, without scrolling it. */ function focusViewHeading(): void { document.querySelector('#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 ? `

${esc(currentNote)}

` : '' if (rows.length) { html += threadList(shown) } else { html += currentRows.length === 0 ? `

${esc(currentEmptyNote || 'No threads meet the criteria.')}

` : '

No threads at the top-quarter cutoff. Show lower-scoring threads.

' } if (rows.length > resultLimit) { html += `` } if (below.length > 0) { html += `` } if (hidden.length > 0) { html += `` } 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(`.${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('.thread-card')].find( (element) => element.dataset.uri === revealed.root_uri, ) card?.querySelector('.thread-open')?.focus() } /* Scan */ function openScoreUris(container: HTMLElement): string[] { return [...container.querySelectorAll('.score-details[open]')] .map((detail) => detail.closest('.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('.thread-card[data-uri]').forEach((card) => { const details = card.querySelector('.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 = `

Surface the threads worth writing

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.

What makes a thread worth a blog post?

Long enough to stand alone. 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.

One line of thought. 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.

Not just the best performing. 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.

` const results = must(document.querySelector('#results')) const status = must(document.querySelector('#status')) const errorHost = must(document.querySelector('#scan-error')) const cancelButton = must(document.querySelector('#scan-cancel')) const meta = must(document.querySelector('#scan-meta')) const age = must(document.querySelector('#scan-age')) const rescan = must(document.querySelector('#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('.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): Promise => { 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(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 { app.innerHTML = '

Reading thread…

' 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 = '

Nothing to show for that post.

← threads

' document.querySelector('.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 ? `Bluesky` : '', ] .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 ? `· 1/${view.post_count}` : '' document.title = threadTitle(title) app.innerHTML = `
← threads

${esc(title)}

${byline}${index ? ` ${index}` : ''}

${ view.topics.length ? `

about${topicChips(view.topics)}

` : '' } ${branches}
${ canExport ? ` ` : 'Only the thread author can export it.' }

${ warning ? `
warned${esc(labelText(view.labels))}
` : `
${rendered}
` }
` const status = must(document.querySelector('#action-status')) app.querySelector('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('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('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('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('.rendered a').forEach((link) => { link.target = '_blank' link.rel = 'noreferrer' }) } if (focus) focusViewHeading() } function branchPanel(forks: Fork[], sourceUri: string): string { return `
branches${forks .map( (fork) => `
${esc(fork.parent_snippet)}
`, ) .join('')}
` } /* 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) => `${esc(topic)}`).join('') } function labelText(labels: string[]): string { const names: Record = { '!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) => `
${esc(factor.name)} w ${factor.weight.toFixed(2)} · ${esc(factor.scale)} raw ${fixed(factor.raw, 3)} · p${fixed(factor.percentile, 0)} ${esc(factor.detail)}
`, ) .join('') return `
${esc(item.name)} w ${item.weight.toFixed(2)} · raw ${fixed(item.raw, 2)} · p${fixed(item.percentile, 0)}
${factors}
` }) .join('') const notes = score.notes.map((note) => `
  • ${esc(note)}
  • `).join('') return `

    panoptiblog tree v${score.version} · ${esc(score.cohort)}

    A percentile among the scanned threads, not a global popularity rank. Audience is one of six composites; engagement is a diagnostic.

    overall
    p${fixed(score.overall_percentile, 0)} · raw ${fixed(score.overall_raw, 3)}
    length
    ${row.words} words · ${row.graphemes} graphemes · ${row.post_count} posts
    engagement
    ${countLabel(row.likes, 'like')} · ${countLabel(row.reposts, 'repost')} · ${countLabel(row.quotes, 'quote')} · ${countLabel(row.replies, 'reply', 'replies')}
    ${categories}
    ${notes ? `
      ${notes}
    ` : ''}
    ` } 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 ? `@${esc(row.author.handle)}` : '' const avatar = row.author.avatar ? `` : `${esc((displayName || row.author.handle).slice(0, 1).toUpperCase())}` 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 ? `
    warned${esc(labelText(row.labels))}
    ` : `

    ${esc(row.root_text)}

    ` const thumb = contentVisible && row.root_thumb ? `` : '' const sideBranches = row.forks.reduce( (total, fork) => total + fork.options.filter((option) => !option.chosen).length, 0, ) const branches = sideBranches ? `⑂ ${sideBranches}` : '' const canExport = isOwnThread(row.root_uri, currentDid) const actions = `
    ⋯
    ${ canExport ? '' : `Only @${esc(row.author.handle)} can export this thread.` } Open on Bluesky
    ` return `
    1/${row.post_count}
    ${avatar}
    ${esc(name)} ${handle} ${esc(row.root_date)} ${row.label_state === 'hidden' ? 'hidden' : ''} ${actions}
    ${warning}
    ${ contentVisible ? ` ♥ ${row.likes} ⇄ ${row.reposts} ↩ ${row.replies} ❝ ${row.quotes} ` : '' } ${ contentVisible && shown.length ? `about${topicChips(shown)}${ more > 0 ? `+${more}` : '' }` : '' } ${branches} open →
    p${Math.round(row.score)} · style ${style} ${scorePanel(row)}
    ${thumb}
    ` }) .join('') return `
    ${cards}
    ` } function bindThreadRows(container: HTMLElement): void { container.querySelectorAll('.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('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('[data-row-action]').forEach((button) => { button.addEventListener('click', async (event) => { event.stopPropagation() if (!uri) return const menu = button.closest('.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('[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 { 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 { 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 = ` ` if (retry) container.querySelector('.retry')?.addEventListener('click', retry) } function toast(message: string): void { const element = document.querySelector('#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(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()