// The in-popup subscriptions manager. // // popup.ts owns the tab bar and the three panels; this view fills the // Subscriptions panel and owns its own list scroll. Reads use the public // listRecords helper, writes use src/lib/subscription.ts (which invalidates // the worker's `own` cache), and publication records are hydrated a few at a // time behind skeleton rows. import type { Agent } from '@atproto/api' import { parseAtUri } from '../lib/atproto' import { ext } from '../lib/platform' import { DEFAULT_READER_ID, READERS, type Reader, pubUrl } from '../lib/readers' import { createSubscription, deleteSubscription, loadSubscriptions, publicationSummary, } from '../lib/subscription' import { type SubscriptionEntry, type SubscriptionRow, type SubscriptionSort, filterSubscriptions, formatSubscriptionDate, isSubscriptionSort, publicationFallback, safeHttpUrl, sortSubscriptions, subscriptionStats, } from '../lib/subscription-list' import type { PubInfo, SessionInfo } from '../lib/types' import { applyBadgeIcon } from './badge' /** How many publication records may be in flight at once. */ const HYDRATE_CONCURRENCY = 6 /** How long the undo bar stays up. */ const TOAST_MS = 8_000 type Mode = 'signed-out' | 'loading' | 'ready' | 'error' type Tone = 'info' | 'error' /** What the popup gives the view; all of it can change while the popup is open. */ export interface SubscriptionsHost { session(): SessionInfo | undefined /** Whether the popup already knows the stored session died. */ expired(): boolean readerId(): string /** Open the popup's existing sign-in panel. */ openSignin(): void /** Open a URL the way the popup's own Open button does. */ openUrl(url: string): void /** The stored session could not be restored; stop showing its account. */ onSessionExpired(): void } export interface SubscriptionsView { mount(host: SubscriptionsHost): void /** Switch the view on and start loading. */ open(): void /** Stop rendering and drop the transient bar. */ close(): void /** The popup's session changed while the view was open. */ sessionChanged(): void } const $ = (id: string) => document.getElementById(id) as T function element( tag: K, className?: string, text?: string, ): HTMLElementTagNameMap[K] { const node = document.createElement(tag) if (className) node.className = className if (text !== undefined) node.textContent = text return node } function create(): SubscriptionsView { let host: SubscriptionsHost | undefined let mounted = false let openState = false let mode: Mode = 'signed-out' let session: SessionInfo | undefined let agent: Agent | undefined let rows: SubscriptionRow[] = [] let visibleRows: SubscriptionRow[] = [] let query = '' let sortKey: SubscriptionSort = 'name' let selected = new Set() let hydrating = 0 let loading = false let writing = false let errorText = '' let generation = 0 let renderQueued = false let statusText = '' let statusTone: Tone = 'info' let confirmingBulk = false let toastTimer: ReturnType | undefined let undoAction: (() => Promise) | undefined let oauthModule: Promise | undefined function oauth(reason: string): Promise { if (!oauthModule) { console.debug('[substandard] oauth client loaded for', reason) oauthModule = import('../lib/oauth') } return oauthModule } // --- rendering ----------------------------------------------------------- function scheduleRender(): void { if (!openState || renderQueued) return renderQueued = true const run = () => { renderQueued = false if (openState) render() } if (typeof requestAnimationFrame === 'function') requestAnimationFrame(run) else setTimeout(run, 0) } function render(): void { if (!openState) return renderShell() if (mode === 'loading' || mode === 'ready') { renderStats() renderToolbar() renderList() renderBulk() } renderStatus() } function renderShell(): void { $('subs-signed-out').hidden = mode !== 'signed-out' $('subs-error').hidden = mode !== 'error' $('subs-ready').hidden = mode !== 'loading' && mode !== 'ready' if (mode === 'error') $('subs-error-text').textContent = errorText const ready = mode === 'ready' $('subs-stats').hidden = !ready $('subs-toolbar').hidden = !ready $('subs-bulk').hidden = !ready if (!ready) { confirmingBulk = false $('subs-confirm').hidden = true } } function renderStats(): void { const stats = subscriptionStats(rows) $('subs-total').textContent = String(stats.total) $('subs-hosts').textContent = String(stats.hosts) $('subs-newest').textContent = stats.newestAt ? formatSubscriptionDate(stats.newestAt) : '—' } function renderToolbar(): void { const search = $('subs-search') if (search.value !== query) search.value = query $('subs-sort').value = sortKey $('subs-refresh').disabled = loading || writing } function renderList(): void { const list = $('subs-list') const empty = $('subs-empty') const noResults = $('subs-no-results') if (mode === 'loading') { visibleRows = [] list.hidden = false list.setAttribute('aria-busy', 'true') list.replaceChildren( ...Array.from({ length: 4 }, () => skeletonRow()), ) empty.hidden = true noResults.hidden = true return } if (rows.length === 0) { visibleRows = [] list.replaceChildren() list.hidden = true empty.hidden = false noResults.hidden = true return } empty.hidden = true visibleRows = sortSubscriptions(filterSubscriptions(rows, query), sortKey) if (visibleRows.length === 0) { list.replaceChildren() list.hidden = true noResults.hidden = false return } noResults.hidden = true list.hidden = false const active = document.activeElement as HTMLElement | null const activeRow = active?.closest('[data-uri]')?.dataset.uri const activeAction = active?.dataset.action list.replaceChildren( ...visibleRows.map((row) => row.pub || row.failed ? rowElement(row) : skeletonRow(), ), ) list.setAttribute('aria-busy', String(hydrating > 0)) if (activeRow && activeAction) { const row = [...list.querySelectorAll('li[data-uri]')].find( (li) => li.dataset.uri === activeRow, ) row?.querySelector(`[data-action="${activeAction}"]`)?.focus({ preventScroll: true, }) } } function renderBulk(): void { if (mode !== 'ready' || rows.length === 0) { $('subs-bulk').hidden = true $('subs-confirm').hidden = true return } $('subs-bulk').hidden = false const allSelected = visibleRows.length > 0 && visibleRows.every((row) => selected.has(row.rkey)) const someSelected = visibleRows.some((row) => selected.has(row.rkey)) const all = $('subs-select-all') all.checked = allSelected all.indeterminate = someSelected && !allSelected $('subs-selected').textContent = `${selected.size} selected` const button = $('subs-bulk-unsubscribe') const hasSelection = selected.size > 0 button.hidden = !hasSelection button.disabled = writing || loading if (hasSelection) button.textContent = `Unsubscribe ${selected.size}` const showConfirm = confirmingBulk && selected.size > 0 && !writing && !loading $('subs-confirm').hidden = !showConfirm if (showConfirm) { $('subs-confirm-text').textContent = `Unsubscribe from ${selected.size} publication${selected.size === 1 ? '' : 's'}?` } } function renderStatus(): void { const el = $('subs-status') if (el.textContent !== statusText) el.textContent = statusText el.hidden = !statusText el.classList.toggle('error', statusTone === 'error') } function setStatus(text: string, tone: Tone = 'info'): void { statusText = text statusTone = tone renderStatus() } // --- rows ---------------------------------------------------------------- function displayName(row: SubscriptionRow): string { if (row.pub) return row.pub.name if (row.failed) return 'Unavailable publication' return publicationFallback(row.publication) } function skeletonRow(): HTMLLIElement { const li = element('li', 'subs-row is-loading') li.setAttribute('aria-hidden', 'true') li.append( element('span', 'skeleton subs-skeleton-check'), element('span', 'skeleton subs-skeleton-icon'), (() => { const main = element('div', 'subs-main') main.append( element('span', 'skeleton subs-skeleton-name'), element('span', 'skeleton subs-skeleton-line'), ) return main })(), element('span', 'skeleton subs-skeleton-action'), ) return li } function rowElement(row: SubscriptionRow): HTMLLIElement { const name = displayName(row) const failed = !!row.failed && !row.pub const li = element('li', 'subs-row') li.dataset.uri = row.uri const select = element('label', 'subs-check') const box = document.createElement('input') box.type = 'checkbox' box.dataset.action = 'select' box.checked = selected.has(row.rkey) box.disabled = writing box.setAttribute('aria-label', `Select ${name}`) box.addEventListener('change', () => { confirmingBulk = false if (box.checked) selected.add(row.rkey) else selected.delete(row.rkey) renderBulk() }) select.append(box, element('span', 'sr-only', `Select ${name}`)) const icon = element('span', 'subs-icon') const img = document.createElement('img') img.className = 'badge-icon' img.alt = '' img.hidden = true const mono = element('span', 'badge-icon badge-icon--mono') mono.setAttribute('aria-hidden', 'true') mono.hidden = true icon.append(img, mono) applyBadgeIcon(img, mono, name, row.pub?.iconUrl) const main = element('div', 'subs-main') const line = element('div', 'subs-line') const siteUrl = safeHttpUrl(row.pub?.url) if (siteUrl) { const link = document.createElement('a') link.className = 'subs-name' link.href = siteUrl link.target = '_blank' link.rel = 'noopener noreferrer' link.textContent = name line.append(link) } else { line.append(element('span', 'subs-name', name)) } main.append(line) const meta = element('div', 'subs-meta') if (row.pub?.host) meta.append(element('span', 'subs-host', row.pub.host)) if (row.createdAt) { const date = formatSubscriptionDate(row.createdAt) if (date) { const time = element('time', undefined, `Subscribed ${date}`) time.dateTime = row.createdAt meta.append(time) } } if (failed) { meta.append(element('span', 'subs-failed', 'Details unavailable')) const did = parseAtUri(row.publication)?.did if (did) meta.append(element('span', 'subs-did', did)) } if (meta.childElementCount > 0) main.append(meta) const actions = element('div', 'subs-actions') const reader = currentReader() const target = reader ? readerTarget(row, reader) : null if (reader && target) { const open = element('button', 'icon-btn subs-reader') open.type = 'button' open.dataset.action = 'reader' open.disabled = writing open.setAttribute('aria-label', `Open in ${reader.name}`) open.title = `Open in ${reader.name}` open.append(readerIcon(reader)) open.addEventListener('click', () => host?.openUrl(target)) actions.append(open) } const unsubscribe = element('button', 'btn sm subs-unsub', 'Unsubscribe') unsubscribe.type = 'button' unsubscribe.dataset.action = 'unsubscribe' unsubscribe.disabled = writing unsubscribe.setAttribute('aria-label', `Unsubscribe from ${name}`) unsubscribe.addEventListener('click', () => void unsubscribeRow(row)) actions.append(unsubscribe) li.append(select, icon, main, actions) return li } function readerIcon(reader: Reader): HTMLImageElement { const img = document.createElement('img') img.className = 'reader-icon' img.src = reader.icon img.alt = '' img.onerror = () => { console.debug('[substandard] vendored reader icon missing', reader.icon) img.remove() } return img } function currentReader(): Reader | undefined { const id = host?.readerId() ?? DEFAULT_READER_ID return ( READERS.find((reader) => reader.id === id) ?? READERS.find((reader) => reader.id === DEFAULT_READER_ID) ) } function publicationInfo(row: SubscriptionRow): PubInfo | null { if (!row.pub) return null const did = parseAtUri(row.publication)?.did if (!did) return null return { uri: row.publication, did, pds: '', record: { $type: 'site.standard.publication', url: row.pub.url ?? '', name: row.pub.name, description: row.pub.description, }, iconUrl: row.pub.iconUrl, verified: false, } } function readerTarget(row: SubscriptionRow, reader: Reader): string | null { const pub = publicationInfo(row) return pub ? pubUrl(reader.id, pub) : null } // --- loading ------------------------------------------------------------- async function load(refresh: boolean): Promise { const current = host?.session() if (!current) { session = undefined showSignedOut() return } session = current const token = ++generation loading = true errorText = '' if (rows.length === 0) { mode = 'loading' setStatus('Loading subscriptions…') } else { mode = 'ready' setStatus('Refreshing subscriptions…') } render() let entries: SubscriptionEntry[] try { entries = await loadSubscriptions(current.did) } catch (err) { console.debug('[substandard] subscription list failed', err) if (token !== generation) return loading = false if (rows.length > 0) { mode = 'ready' setStatus(`Could not refresh subscriptions: ${messageOf(err)}`, 'error') render() } else { setStatus('') mode = 'error' errorText = `Could not load your subscriptions. ${messageOf(err)}` render() } return } if (token !== generation) return const known = new Map(rows.map((row) => [row.uri, row])) rows = entries.map((entry) => { const previous = known.get(entry.uri) return previous ? { ...entry, pub: previous.pub, failed: previous.failed } : { ...entry } }) selected = new Set([...selected].filter((rkey) => rows.some((row) => row.rkey === rkey))) loading = false mode = 'ready' hydrating = refresh ? rows.length : rows.filter((row) => !row.pub).length render() void hydrate(token, refresh) } /** * Read publication records a few at a time, redrawing as each lands. A row * that cannot be read is marked failed and stays; the rest of the batch * continues. */ async function hydrate(token: number, refresh: boolean): Promise { const pending = refresh ? [...rows] : rows.filter((row) => !row.pub) const total = pending.length if (total === 0) { hydrating = 0 if (statusText.startsWith('Loading ')) { setStatus(`Loaded ${rows.length} subscription${rows.length === 1 ? '' : 's'}.`) } return } hydrating = total let next = 0 let done = 0 let failed = 0 const work = async () => { for (;;) { const row = pending[next++] if (!row) return try { row.pub = await publicationSummary(row.publication, refresh) row.failed = false } catch (err) { if (token !== generation) return console.debug('[substandard] publication details failed', row.publication, err) if (!row.pub) row.failed = true failed++ } if (token !== generation) return done++ hydrating = total - done scheduleRender() } } await Promise.all( Array.from({ length: Math.min(HYDRATE_CONCURRENCY, total) }, () => work()), ) if (token !== generation) return hydrating = 0 if (!writing && statusText.startsWith('Loading ')) { const missed = failed > 0 ? ` ${failed} publication${failed === 1 ? '' : 's'} unavailable.` : '' setStatus(`Loaded ${rows.length} subscription${rows.length === 1 ? '' : 's'}.${missed}`) } scheduleRender() } // --- writes -------------------------------------------------------------- async function writeAgent(): Promise { if (agent) return agent const { restoreAgent } = await oauth('a subscription write') const restored = await restoreAgent() if ('agent' in restored) { agent = restored.agent return agent } if (restored.status === 'expired') { host?.onSessionExpired() session = undefined showSignedOut('Your session ended — sign in again.') throw new Error('Session expired. Sign in again.') } throw new Error('Could not reach your data server. Try again.') } async function unsubscribeRow(row: SubscriptionRow): Promise { if (writing || loading || !session) return const did = session.did const name = displayName(row) const index = visibleRows.findIndex((candidate) => candidate.uri === row.uri) writing = true confirmingBulk = false render() setStatus(`Unsubscribing from ${name}…`) try { const current = await writeAgent() await deleteSubscription(current, did, row.rkey) if (!session || session.did !== did) return rows = rows.filter((candidate) => candidate.uri !== row.uri) selected.delete(row.rkey) setStatus(`Unsubscribed from ${name}.`) showUndo(`Unsubscribed from ${name}.`, () => undoUnsubscribe(row, did)) } catch (err) { console.debug('[substandard] unsubscribe failed', err) setStatus(`Could not unsubscribe from ${name}: ${messageOf(err)}`, 'error') } finally { writing = false render() focusAfterRemoval(index) } } async function undoUnsubscribe(row: SubscriptionRow, did: string): Promise { if (writing) return if (!session || session.did !== did) { hideToast() return } const name = displayName(row) writing = true render() try { const current = await writeAgent() const restored = await createSubscription(current, did, row.publication, row.createdAt) if (!session || session.did !== did) { writing = false hideToast() render() return } const restoredRow: SubscriptionRow = { ...row, ...restored, pub: row.pub, failed: row.failed, } rows = [restoredRow, ...rows] setStatus(`Restored ${name}.`) hideToast() writing = false render() focusRow(restoredRow.uri) return } catch (err) { console.debug('[substandard] subscription undo failed', err) setStatus(`Could not restore ${name}: ${messageOf(err)}`, 'error') armToastTimer() } writing = false render() } async function bulkUnsubscribe(): Promise { if (writing || loading || !session) return const targets = rows.filter((row) => selected.has(row.rkey)) if (targets.length === 0) return const did = session.did confirmingBulk = false writing = true render() let done = 0 let failed = 0 for (const row of targets) { if (!session || session.did !== did) break setStatus(`Unsubscribing ${done + failed + 1} of ${targets.length}…`) try { const current = await writeAgent() await deleteSubscription(current, did, row.rkey) rows = rows.filter((candidate) => candidate.uri !== row.uri) selected.delete(row.rkey) done++ } catch (err) { console.debug('[substandard] bulk unsubscribe failed', row.uri, err) failed++ } render() } writing = false if (!session || session.did !== did) return setStatus( failed > 0 ? `Unsubscribed ${done} of ${targets.length}. ${failed} failed; try again.` : `Unsubscribed ${done} subscription${done === 1 ? '' : 's'}.`, failed > 0 ? 'error' : 'info', ) render() // Keep only the rows that could not be removed selected, so a retry is // one click and the selection is not silently wider than what remains. selected = new Set([...selected].filter((rkey) => rows.some((row) => row.rkey === rkey))) render() if (selected.size > 0) $('subs-bulk-unsubscribe').focus() else $('subs-search').focus() } function focusAfterRemoval(index: number): void { if (!openState) return const target = visibleRows[Math.min(index, visibleRows.length - 1)] if (target) focusRow(target.uri) else $('subs-search').focus() } function focusRow(uri: string): void { const row = [...$('subs-list').querySelectorAll('li[data-uri]')].find( (li) => li.dataset.uri === uri, ) row?.querySelector('[data-action="unsubscribe"]')?.focus() } function messageOf(err: unknown): string { return err instanceof Error ? err.message : String(err) } // --- undo bar ------------------------------------------------------------ function showUndo(message: string, undo: () => Promise): void { if (!openState) return undoAction = undo $('subs-toast-text').textContent = message $('subs-toast-undo').hidden = false $('subs-toast-undo').disabled = false $('subs-toast').hidden = false armToastTimer() } function hideToast(): void { if (toastTimer) { clearTimeout(toastTimer) toastTimer = undefined } undoAction = undefined $('subs-toast').hidden = true } function armToastTimer(): void { if (toastTimer) clearTimeout(toastTimer) toastTimer = setTimeout(hideToast, TOAST_MS) } async function runUndo(): Promise { const action = undoAction if (!action) return $('subs-toast-undo').disabled = true try { await action() } finally { if (!$('subs-toast').hidden) { $('subs-toast-undo').disabled = false } } } // --- states -------------------------------------------------------------- function showSignedOut(note?: string): void { mode = 'signed-out' loading = false writing = false confirmingBulk = false rows = [] selected.clear() query = '' setStatus('') const message = note ?? (host?.expired() ? 'Your session ended — sign in again.' : 'Sign in to manage your subscriptions.') $('subs-signin-note').textContent = message hideToast() render() } // --- events -------------------------------------------------------------- function onSearch(): void { query = $('subs-search').value confirmingBulk = false renderList() renderBulk() } function onSort(): void { const value = $('subs-sort').value if (isSubscriptionSort(value)) sortKey = value confirmingBulk = false renderList() renderBulk() } function onSelectAll(): void { const all = $('subs-select-all') confirmingBulk = false if (all.checked) for (const row of visibleRows) selected.add(row.rkey) else for (const row of visibleRows) selected.delete(row.rkey) render() } function beginBulkConfirm(): void { if (writing || loading || selected.size === 0) return confirmingBulk = true renderBulk() $('subs-confirm-cancel').focus() } function cancelBulkConfirm(): void { confirmingBulk = false renderBulk() $('subs-bulk-unsubscribe').focus() } function sessionChanged(): void { if (!openState) return const next = host?.session() if (!next) { generation++ session = undefined agent = undefined showSignedOut() return } if (!session || session.did !== next.did) { session = next agent = undefined rows = [] selected.clear() query = '' void load(false) } else { session = next } } function mount(next: SubscriptionsHost): void { host = next if (mounted) return mounted = true $('subs-refresh').addEventListener('click', () => void load(true)) $('subs-search').addEventListener('input', onSearch) $('subs-sort').addEventListener('change', onSort) $('subs-select-all').addEventListener('change', onSelectAll) $('subs-bulk-unsubscribe').addEventListener('click', beginBulkConfirm) $('subs-confirm-cancel').addEventListener('click', cancelBulkConfirm) $('subs-confirm-ok').addEventListener('click', () => void bulkUnsubscribe()) $('subs-signin').addEventListener('click', () => host?.openSignin()) $('subs-retry').addEventListener('click', () => void load(true)) $('subs-toast-undo').addEventListener('click', () => void runUndo()) $('subs-toast-close').addEventListener('click', hideToast) ext.storage.onChanged.addListener((changes, area) => { if (area !== 'local' || !('session' in changes)) return if (openState) sessionChanged() }) } function open(): void { openState = true generation++ hideToast() confirmingBulk = false const current = host?.session() if (current && session?.did === current.did && mode === 'ready') { // Coming back to the tab: keep the list, search and selection where // they were. Refresh is deliberate and lives in the toolbar. render() return } setStatus('') if (!current) { session = undefined showSignedOut() } else { session = current mode = 'loading' loading = true rows = [] selected.clear() render() void load(false) } } function close(): void { openState = false generation++ loading = false confirmingBulk = false hideToast() } return { mount, open, close, sessionChanged, } } export const subscriptionsView = create()