import 'actor-typeahead' import type { Agent } from '@atproto/api' import { parseAtUri } from '../lib/atproto' import { AUTH_ERROR_KEY } from '../lib/authflow' import { invalidate, invalidateAccount } from '../lib/cache' import { isDevChannel } from '../lib/channel' import { BOARD_URL, type BoardSpace, DISCUSSION_COLLECTION, type SpaceTag, buildDiscussion, discussionUrl, fetchSpace, } from '../lib/feedback' import { ext } from '../lib/platform' import { isScopeError } from '../lib/scope' import { LAST_HANDLE_KEY, SESSION_EXPIRED_KEY, getStoredSession } from '../lib/session-store' import { DEFAULT_READER_ID, READERS, type Reader, docUrl, migrateReaderId, pubSiteUrl, pubUrl, } from '../lib/readers' import { shareOnBlueskyUrl } from '../lib/share' import { resolveSiteAccount, type SiteAccount } from '../lib/site-handle' import { type StatusMessage, statusMessagesFor } from '../lib/status' import { rgbCss } from '../lib/theme' import { pinState, welcomeUrl } from '../lib/welcome' import { CARDS, type CardHost } from './cards' import { siteCard } from './cards/site' import { LoadTracker } from './cards/loading' import { type RegisteredDisclosure, wireDisclosure } from './disclosure' import { $, TONE_ICONS } from './dom' import { applyBadgeIcon, badge } from './badge' import { closeMenus, wireMenu } from './menu' import { send } from './send' import { subscriptionsView } from './subscriptions-view' import { THEME_LABELS, type ThemeChoice, applyTheme, isThemeChoice, readThemeChoice, setTheme, watchSystemTheme, } from './theme' import { wireTypeaheadSubmit } from '../lib/typeahead' import type { PageState, PubInfo, SessionInfo } from '../lib/types' const SUB_COLLECTION = 'site.standard.graph.subscription' /** * The OAuth client is most of the 843 kB OAuth chunk, and nothing the popup * draws needs it. Importing it here keeps it out of the first paint; warming * it once the popup is idle (prefetchOAuth) means a reader who opens the * sign-in form or whose session is being probed does not pay for the download * then, either (TODO.md). */ 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 } /** * Fetch the OAuth chunk after the popup is usable, rather than before it is. * `requestIdleCallback` is the honest version; the timeout is for a browser * without it, and is deliberately late enough not to compete with first paint. * * Sign-in itself runs in the worker's OAuth host, but the popup needs this * chunk for the session probe that follows it and for every signed-in write; * fetching it into the HTTP cache now is what keeps those from waiting. */ function prefetchOAuth(): void { const load = () => void oauth('idle prefetch') if (typeof requestIdleCallback === 'function') { requestIdleCallback(load, { timeout: 2_000 }) } else { setTimeout(load, 350) } } /** * Which card loads are still running, and which have run long enough to be * worth a placeholder. Redraws by itself when one crosses that line, since * nothing else is happening at that moment (src/popup/cards/loading.ts). */ const loads = new LoadTracker(() => render()) /** * What the cards can ask for. Methods rather than values: a card holds this * for the life of the popup and the answers change under it. */ const host: CardHost = { state: () => state, siteAccount: () => siteAccount, session: () => session, rerender: () => render(), loading: (id) => loads.busy(id), } /** Start every card's load, and watch it, in the one place they are started. */ function loadCards(refresh: boolean) { // Every card fetches on its own, in parallel, and redraws when it lands. for (const card of CARDS) loads.track(card.id, card.load?.(host, refresh)) // Redrawn here rather than left to the first load that finishes, so the // card says it is busy from the moment it is (see render). render() } let state: PageState | undefined let session: SessionInfo | undefined let tabId: number | undefined let httpPage = false let requestFailed = false let sessionExpired = false /** The current page's host as an atproto account, when it is one. */ let siteAccount: SiteAccount | undefined let defaultReader = DEFAULT_READER_ID let signinNudge = false /** Whether the toolbar icon is known to be unpinned; undefined until asked. */ let unpinned: boolean | undefined /** Subscribe is armed for its second click (blocked publisher; see renderSubscribe). */ let subscribeArmed = false /** The feedback board, read once per popup open (see loadBoard). */ let board: BoardSpace | undefined let themeChoice: ThemeChoice = 'system' let signinDisclosure!: RegisteredDisclosure /** * What a write owes the cache: this one changed the subscription collection, * so the list read from it is no longer what the PDS holds. Nothing else the * account has is affected — re-reading 1500 follows because somebody * subscribed to a blog would be a strange thing to do (src/lib/cache.ts). */ async function invalidateSubsCache() { if (session) await invalidate({ scope: 'own', subject: session.did, name: 'subs' }) } /** * Drop everything cached from this account's own repo. For signing out, where * the next account's answers must not be the previous one's. */ async function invalidateAccountCaches() { if (session) await invalidateAccount(session.did) } async function init() { const [tab] = await ext.tabs.query({ active: true, currentWindow: true }) tabId = tab?.id httpPage = !!tab?.url && /^https?:\/\//.test(tab.url) // Started, not awaited: the popup draws from what it already knows, and the // status region gains the nudge if and when this answer arrives. void checkPinned() const stored = await ext.storage.local.get('defaultReader') // Migrated on read, not rewritten: a choice stored under the old id keeps // working, and it is rewritten the next time the user picks a reader. const chosen = typeof stored.defaultReader === 'string' ? migrateReaderId(stored.defaultReader) : undefined if (chosen && READERS.some((r) => r.id === chosen)) { defaultReader = chosen } else { console.debug(`substandard: no stored reader choice, defaulting to ${DEFAULT_READER_ID}`) } // The board's own page, linkable before (and whether or not) its record // loads; the link text becomes the space's real name once it does. The host // it is hosted on stays outside the link, in the markup, so the sentence // names userinput.app either way — the board is called substandard.blog, // which on its own reads as if the post lands on this extension's own site. $('feedback-board').href = BOARD_URL for (const card of CARDS) card.mount?.(host) session = await getStoredSession() renderAccount() // If somebody opened Subscriptions before storage answered, let the view // adopt the session that has just arrived. subscriptionsView.sessionChanged() void refreshAccount() void probeSessionExpiry() await showAuthError() await showSessionExpired() await loadState(false) // After the popup has drawn, not before: the chunk is for later. prefetchOAuth() } /** * The stored did/handle mirror can outlive the OAuth session it mirrors. * Restore the real session off the open path so an expired sign-in surfaces * as a status pill instead of a dead Subscribe button. A restore that cannot * reach the PDS proves nothing, so it leaves the signed-in UI alone. */ async function probeSessionExpiry() { if (!session || navigator.onLine === false) return const { restoreAgent } = await oauth('session probe') const restored = await restoreAgent() if ('agent' in restored || !session) return if (restored.status === 'unreachable') { console.debug('[substandard] could not verify the session; leaving it signed in') return } console.debug('[substandard] stored session no longer restorable; treating as expired') sessionExpired = true session = undefined subscriptionsView.sessionChanged() await prefillLastHandle() openSigninPanel() $('signin-note').textContent = 'Your session ended — sign in again.' renderAccount() render() } /** * Restore for a write the user just asked for. A dead session flips the UI to * the signed-out warning; an unreachable PDS is reported as a retry instead, * because the session itself has not been shown to be gone. */ async function agentForWrite(action: string): Promise { const { restoreAgent } = await oauth(action) const restored = await restoreAgent() if ('agent' in restored) return restored.agent if (restored.status === 'expired') { sessionExpired = true session = undefined subscriptionsView.sessionChanged() renderAccount() render() throw new Error('Session expired, please sign in again') } throw new Error(`Could not reach your data server to ${action}. Try again.`) } /** Handle and avatar can change remotely; refresh them off the open path. */ async function refreshAccount() { if (!session) return const { refreshStoredSession } = await oauth('account refresh') const updated = await refreshStoredSession() if (updated) { session = updated renderAccount() } } /** Show (once) a sign-in failure that happened after the last popup closed. */ async function showAuthError() { const stored = await ext.storage.session.get(AUTH_ERROR_KEY) const authError = stored[AUTH_ERROR_KEY] as string | undefined if (!authError) return openSigninPanel() $('signin-note').textContent = `Sign-in failed: ${authError}` await ext.storage.session.remove(AUTH_ERROR_KEY) } /** Show that the previous session ended on its own, not by sign-out. */ async function showSessionExpired() { if (session) return const stored = await ext.storage.local.get(SESSION_EXPIRED_KEY) if (!stored[SESSION_EXPIRED_KEY]) return // The subscriptions view reads this (through the host) to word its own // re-authentication state. sessionExpired = true await prefillLastHandle() openSigninPanel() $('signin-note').textContent = 'Your session ended — sign in again.' } /** The mirror is gone after expiry; the last known handle is still helpful. */ async function prefillLastHandle() { const input = $('handle-input') if (input.value.trim()) return const stored = await ext.storage.local.get(LAST_HANDLE_KEY) const handle = stored[LAST_HANDLE_KEY] as string | undefined if (handle) input.value = handle } async function loadState(refresh: boolean) { if (tabId === undefined) { $('status').textContent = 'No active tab.' return } if (refresh) $('status').textContent = 'Re-checking this page…' requestFailed = false // The previous page's account must not stand in for this one while the new // detection state is on its way. siteAccount = undefined // A new answer about the page disarms a pending confirm: the thing the // second click was going to agree to may no longer be what is on screen. subscribeArmed = false try { state = await send({ type: 'get-state', tabId, refresh }) } catch (err) { console.debug('[substandard] get-state failed', err) state = undefined requestFailed = true } render() void probeSiteAccount(state) loadCards(refresh) } /** * Off the render path: ask whether the page's own host is an atproto account. * This runs even when detection found a publication, because the page's * account and the publication's author are different accounts on a reader * site — the popup labels them "This site" and "Author". A miss or a failed * lookup simply leaves the site card off. */ async function probeSiteAccount(next: PageState | undefined) { if (!next || next.error || navigator.onLine === false) return const resolved = await resolveSiteAccount(next.url) // A navigation or refresh landed while the lookup was out; this answer is // about a page the popup no longer shows. if (state !== next) return siteAccount = resolved ?? undefined render() if (!siteAccount) return console.debug('[substandard] site is an Atmosphere account', siteAccount.handle) loadCards(false) } function renderAccount() { $('account-btn').hidden = !session if (!session) { closeMenus() $('signin-open').hidden = false return } // Keep the panel as it is: a profile refresh landing mid-switch must not // close the form under the user. setSigninPanel(!$('signin-panel').hidden) const label = `@${session.handle ?? session.did}` $('account-handle').textContent = label applyBadgeIcon( $('account-avatar'), $('account-avatar-fallback'), label, session.avatarUrl, ) } /** * The header Sign in button is the panel's only button: it expands into the * handle form, and once open it submits it. Everything that hides the panel * must go through here so the button's state stays truthful. While signed in * the button appears only with the panel (the switch-account flow), so the * form always has its submit button. */ function setSigninPanel(open: boolean) { if (open) signinDisclosure.open() else signinDisclosure.close() // Signed in, the account chip is the control; this button is only the // signed-out entry point. The panel itself has its own Cancel. $('signin-open').hidden = !!session } function openSigninPanel() { setSigninPanel(true) } /** The publication's declared colors, as custom properties scoped to #pub. */ const PUB_THEME_VARS = ['--pub-bg', '--pub-fg', '--pub-accent'] as const function applyPubTheme(pub: PubInfo | undefined) { const el = $('pub') const theme = pub?.theme if (!theme) { for (const name of PUB_THEME_VARS) el.style.removeProperty(name) el.removeAttribute('data-themed') return } el.style.setProperty('--pub-bg', rgbCss(theme.background)) el.style.setProperty('--pub-fg', rgbCss(theme.foreground)) el.style.setProperty('--pub-accent', rgbCss(theme.accent)) el.setAttribute('data-themed', '') } function render() { const pub = state?.pub renderStatus() const pubEl = $('pub') applyPubTheme(pub) if (!pub) { pubEl.hidden = true // The site profile is not part of the publication: it is the account the // page itself is, and it has to draw on a page with no publication too. siteCard.render(host) return } pubEl.hidden = false renderPubIcon(pub) renderPubName(pub) $('pub-desc').textContent = pub.record.description ?? '' $('pub-desc').hidden = !pub.record.description const docLine = $('doc-line') if (state?.doc) { const title = state.doc.record.title docLine.replaceChildren( badge({ kind: 'post', size: 'sm', ghost: true, label: `Article: ${title}`, title }), ) docLine.hidden = false } else { docLine.hidden = true } for (const card of CARDS) card.render(host) // One "still working" for the whole card, rather than one per placeholder: // the placeholders are hidden from assistive technology, which gets the // card's own state instead of a row of empty elements. if (loads.anyPending()) pubEl.setAttribute('aria-busy', 'true') else pubEl.removeAttribute('aria-busy') renderSubscribe() renderOpen() renderShare() } /** * Read the toolbar pin state without holding up the first paint. Browsers * that cannot answer (Firefox, older Chrome) or whose read fails leave the * value undefined, and that shows no nudge rather than a wrong one — telling * somebody who already pinned the icon to pin it is the failure to avoid * (src/lib/welcome.ts). */ async function checkPinned() { const pin = await pinState() // pinState logs a read that failed; an absent API has no call to fail, so // this logs that case once per popup instead. if (pin === 'unknown' && typeof ext.action?.getUserSettings !== 'function') { console.debug('[substandard] no toolbar pin API; leaving the nudge out') } unpinned = pin === 'unpinned' ? true : undefined // loadState has its own "No active tab." line, which renderStatus does not // know about and must not overwrite. if (tabId !== undefined) renderStatus() } /** * Every applicable status as its own pill, most severe first (a page can be * offline, unverified, and signed out all at once). Hidden when nominal. */ function renderStatus() { const messages = statusMessagesFor({ state, httpPage, signedIn: !!session, requestFailed, sessionExpired, signinNudge, unpinned, }) const el = $('status') el.hidden = messages.length === 0 el.replaceChildren(...messages.map(pillFor)) // "Checking this page…" is the worker not having answered yet, which is the // same kind of not-finished the publication card reports while its lookups // are out — said here in the same way, on the region that is showing it. if (messages.some((msg) => msg.pending)) el.setAttribute('aria-busy', 'true') else el.removeAttribute('aria-busy') } function pillFor(msg: StatusMessage): HTMLElement { const pill = document.createElement('div') pill.className = `pill ${msg.tone}` if (msg.tone !== 'info') { const icon = document.createElement('span') icon.className = 'pill-icon' icon.innerHTML = TONE_ICONS[msg.tone] pill.append(icon) } const body = document.createElement('span') const at = msg.link ? msg.text.indexOf(msg.link.text) : -1 if (!msg.link || at === -1) { body.textContent = msg.text } else { const link = document.createElement('a') link.href = msg.link.href link.target = '_blank' link.rel = 'noopener noreferrer' link.textContent = msg.link.text body.append(msg.text.slice(0, at), link, msg.text.slice(at + msg.link.text.length)) } pill.append(body) return pill } function renderPubIcon(pub: PubInfo) { applyBadgeIcon( $('pub-icon'), $('pub-icon-fallback'), pub.record.name, pub.iconUrl, ) } /** * Publication name, linked to the pub's own site. Usually redundant (the * popup mostly opens on that site), but from a reader or any other page it * is the one way back to the pub itself. */ function renderPubName(pub: PubInfo) { const el = $('pub-name') const url = pubSiteUrl(pub) if (!url) { console.debug('[substandard] pub record url not linkable', pub.record.url) el.textContent = pub.record.name return } const link = document.createElement('a') link.href = url link.target = '_blank' link.rel = 'noopener noreferrer' link.textContent = pub.record.name el.replaceChildren(link) } function renderSubscribe() { const btn = $('subscribe') const rkey = state?.subscriptionRkey if (!session) { // aria-disabled, not disabled: the button stays clickable so the click // can answer with the sign-in pill instead of doing nothing. btn.textContent = 'Subscribe' btn.disabled = false btn.setAttribute('aria-disabled', 'true') btn.title = 'Sign in to subscribe' btn.classList.add('primary') btn.classList.remove('subscribed') return } btn.removeAttribute('aria-disabled') btn.title = '' btn.classList.remove('confirm') if (rkey) { btn.textContent = '✓ Subscribed' btn.title = 'Unsubscribe' btn.classList.remove('primary') btn.classList.add('subscribed') } else if (subscribeArmed) { // Second click of a subscribe to a blocked account. Red and reworded, so // the click that goes through is never the one muscle memory expects. btn.textContent = 'Subscribe anyway?' btn.title = 'Subscribe to a publication you have blocked' btn.classList.remove('primary', 'subscribed') btn.classList.add('confirm') } else { btn.textContent = 'Subscribe' btn.classList.add('primary') btn.classList.remove('subscribed') } } function readerTarget(readerId: string): string | null { const pub = state?.pub if (!pub) return null if (!state?.doc) return pubUrl(readerId, pub) const target = docUrl(readerId, pub, state.doc, state.url) if (!target) { console.debug( `[substandard] ${readerId} has no article view (or it would just link back to this page); linking the publication instead`, ) } return target ?? pubUrl(readerId, pub) } function readerIcon(reader: Reader): HTMLImageElement { const img = document.createElement('img') img.className = 'reader-icon' img.src = reader.icon img.alt = '' // Vendored files, so a load failure is a packaging bug: log it, drop the img. img.onerror = () => { console.debug('[substandard] vendored reader icon missing', reader.icon) img.remove() } return img } /** The record a reader would be opening: the article if there is one. */ function targetCollection(): string | undefined { const uri = state?.doc?.uri ?? state?.pub?.uri return uri ? (parseAtUri(uri)?.collection ?? undefined) : undefined } function renderOpen() { const reader = READERS.find((r) => r.id === defaultReader) ?? READERS[0]! const collection = targetCollection() const btn = $('open-default') // The menu names the reader; the split button stays short enough for the // actions row at 400px. btn.replaceChildren(readerIcon(reader), 'Open') btn.setAttribute('aria-label', `Open in ${reader.name}`) btn.title = reader.describe(collection) btn.disabled = !readerTarget(reader.id) const menu = $('reader-menu') menu.innerHTML = '' for (const r of READERS) { const target = readerTarget(r.id) // The row holds two menu items rather than one button with a nested star: // opening a reader and choosing a default are separate actions, and both // have to be reachable from the keyboard. const row = document.createElement('div') row.className = 'menu-row' row.setAttribute('role', 'none') const open = document.createElement('button') open.type = 'button' open.className = 'item reader-open' open.setAttribute('role', 'menuitem') open.disabled = !target // The catalog's own words for what this reader does with this record. open.title = r.describe(collection) const label = document.createElement('span') label.textContent = r.name open.append(readerIcon(r), label) open.addEventListener('click', () => target && openUrl(target)) const star = document.createElement('button') star.type = 'button' star.className = 'item star-btn' star.setAttribute('role', 'menuitemradio') star.setAttribute('aria-checked', String(r.id === defaultReader)) star.setAttribute('aria-label', `Set ${r.name} as default reader`) star.title = 'Set as default reader' star.dataset.menuKeepOpen = 'true' star.dataset.readerStar = r.id star.textContent = r.id === defaultReader ? '★' : '☆' star.addEventListener('click', async (event) => { event.stopPropagation() defaultReader = r.id await ext.storage.local.set({ defaultReader: r.id }) renderOpen() // The menu was rebuilt; keep focus on the same reader's star. menu.querySelector(`[data-reader-star="${r.id}"]`)?.focus() }) row.append(open, star) menu.append(row) } } /** * Hands the article to Bluesky's composer; nothing is posted from here, and * the button works signed out because the intent link needs no session * (src/lib/share.ts). */ function renderShare() { const pub = state?.pub const url = pub ? shareOnBlueskyUrl(pub, state?.doc, state?.url) : null const btn = $('share') btn.disabled = !url btn.dataset.url = url ?? '' } function openUrl(url: string) { ext.tabs.create({ url }) window.close() } // --- feedback --- /** * The report form in the Feedback tab. Independent of everything above it: * feedback works on a page with no publication, and on no page at all. */ function onFeedbackOpen() { // Said before anything is typed rather than after: the write needs a session. $('feedback-note').textContent = session ? '' : 'Sign in to send feedback.' void loadBoard() } /** * The board record: fetched on first open, not on every popup open — the popup * is opened constantly and most opens never touch feedback. One read per popup * lifetime is also fresh enough for the strongRef, which is seconds old by the * time anything is sent. */ async function loadBoard() { if (board) return try { board = await fetchSpace() } catch (err) { console.debug('[substandard] feedback board could not be read', err) $('feedback-note').textContent = 'The feedback board could not be read. Try again later.' return } console.debug('[substandard] feedback board loaded', board.uri, board.cid) $('feedback-board').textContent = board.name renderFeedbackTags(board.tags) } /** Categories as the board itself lists them, so this repo holds no copy. */ function renderFeedbackTags(tags: SpaceTag[]) { const row = $('feedback-tags') row.replaceChildren( ...tags.map((tag) => { const box = document.createElement('input') box.type = 'checkbox' box.value = tag.value const label = document.createElement('label') label.className = 'feedback-tag' // The label wraps the box, so the word is part of the hit target. label.append(box, tag.label) return label }), ) row.hidden = tags.length === 0 } function tickedTags(): string[] { return [...$('feedback-tags').querySelectorAll('input:checked')].map( (box) => box.value, ) } /** Empties the form and points at the posted report on the board. */ function feedbackPosted(did: string, uri: string) { $('feedback-title').value = '' $('feedback-body').value = '' for (const box of $('feedback-tags').querySelectorAll('input')) { box.checked = false } const note = $('feedback-note') note.textContent = 'Sent. ' const rkey = parseAtUri(uri)?.rkey if (!rkey) { console.debug('[substandard] posted feedback has an unexpected uri', uri) return } const link = document.createElement('a') link.href = discussionUrl(did, rkey) link.target = '_blank' link.rel = 'noopener noreferrer' link.textContent = 'View it on the board.' note.append(link) } // --- events --- $('open-default').addEventListener('click', () => { const target = readerTarget(defaultReader) if (target) openUrl(target) }) $('subscribe').addEventListener('click', async () => { if (!session) { console.debug('[substandard] subscribe clicked while signed out; showing the sign-in pill') signinNudge = true renderStatus() return } const pub = state?.pub if (!pub || tabId === undefined) return const rkey = state?.subscriptionRkey // Subscribing to an account you have blocked takes two clicks: the first // only arms the button. Unsubscribing is never gated — undoing it is the // safe direction. if (!rkey && state?.blocked && !subscribeArmed) { console.debug('[substandard] subscribe to a blocked publisher; arming the confirm', pub.did) subscribeArmed = true renderSubscribe() return } const btn = $('subscribe') btn.disabled = true $('action-note').textContent = rkey ? 'Unsubscribing…' : 'Subscribing…' try { const agent = await agentForWrite('subscribe or unsubscribe') if (rkey) { await agent.com.atproto.repo.deleteRecord({ repo: session.did, collection: SUB_COLLECTION, rkey, }) } else { await agent.com.atproto.repo.createRecord({ repo: session.did, collection: SUB_COLLECTION, record: { $type: SUB_COLLECTION, publication: pub.uri, createdAt: new Date().toISOString(), }, }) } await invalidateSubsCache() state = await send({ type: 'get-state', tabId, refresh: true }) $('action-note').textContent = '' } catch (err) { $('action-note').textContent = `Failed: ${err instanceof Error ? err.message : err}` } // Disarmed whether the write landed or failed: a confirm answers one click, // and a retry after a failure deserves to be asked again. subscribeArmed = false renderSubscribe() $('subscribe').disabled = false }) $('signin-cancel').addEventListener('click', () => setSigninPanel(false)) $('signin-form').addEventListener('submit', async (e) => { e.preventDefault() const handle = $('handle-input').value.trim().replace(/^@/, '') if (!handle) return const note = $('signin-note') note.textContent = 'Waiting for consent…' try { // The worker runs the flow (consent window + offscreen OAuth host); this // popup dies as soon as the consent window takes focus, and the result // lands in storage for the next popup open. await send({ type: 'signin', handle }) window.close() } catch (err) { note.textContent = `Sign-in failed: ${err instanceof Error ? err.message : err}` } }) // The host element makes clicking a suggested account sign in as it. const handleInput = $('handle-input') wireTypeaheadSubmit(handleInput, $('signin-form'), handleInput.closest('actor-typeahead') ?? undefined) // Just a shortcut into the sign-in form: the current login stays usable, and // the worker revokes it only once the replacement sign-in completes // (src/signin.ts). Closing the popup or the consent window changes nothing. $('switch-account').addEventListener('click', (e) => { e.stopPropagation() closeMenus() openSigninPanel() }) $('signout').addEventListener('click', async () => { const { signOut } = await oauth('sign out') await invalidateAccountCaches() await signOut() session = undefined subscriptionsView.sessionChanged() // Everything a card remembered was the old account's answer. for (const card of CARDS) card.reset?.() renderAccount() render() loadCards(false) // The account chip is gone now; the Sign in button is the next useful stop. $('signin-open').focus() }) $('share').addEventListener('click', () => { const url = $('share').dataset.url if (url) openUrl(url) }) $('refresh').addEventListener('click', () => loadState(true)) // No stopPropagation, unlike the sign-in panel: the document-level handler // closes the menus and leaves this section alone, which is what a click here // should do anyway. $('feedback-cancel').addEventListener('click', () => selectTab('page', true)) // --- debug menu (dev channel only) --- // // Where dev-only tools go, all of them reaching something a released build // deliberately makes unreachable: // // - the welcome page, which Chrome otherwise shows exactly once per install // (src/background.ts) and which is therefore impossible to look at again // without reinstalling the extension; // - a re-scan, which the header's Refresh button also does but which lives // inside the publication section, so it is hidden on exactly the pages a // re-scan is most wanted for: the ones detection found nothing on; // - dropping every cached read, which nothing else does at all. Refresh // bypasses the caches on the path it walks; this empties them, so the // next read of anything — on any tab, from a cold worker — runs the miss // path a user with a warm cache would never see. /** What the last debug action did. Cleared whenever the menu opens. */ function debugNote(text: string) { $('debug-note').textContent = text $('debug-note').hidden = !text } if (isDevChannel()) $('debug-area').hidden = false $('debug-welcome').addEventListener('click', () => openUrl(welcomeUrl())) // Both of the below stop the click reaching the document-level close-all // handler: the menu is where the answer is written, so it has to still be // open when the answer arrives. $('debug-rescan').addEventListener('click', async (e) => { e.stopPropagation() debugNote('Re-scanning…') await loadState(true) debugNote(requestFailed ? 'Re-scan failed; see the console.' : 'Re-scanned.') }) // Only drops. Re-scanning from here would refill on the way out, and watching // a cold read happen is the reason to empty the caches in the first place — // so which read runs next is left to whoever asked. $('debug-drop-cache').addEventListener('click', async (e) => { e.stopPropagation() debugNote('Dropping…') try { const { dropped } = await send<{ dropped: number }>({ type: 'drop-caches' }) debugNote(`Dropped ${dropped} ${dropped === 1 ? 'entry' : 'entries'}.`) } catch (err) { console.debug('[substandard] drop-caches failed', err) debugNote(err instanceof Error ? err.message : String(err)) } }) $('feedback-form').addEventListener('submit', async (e) => { e.preventDefault() const note = $('feedback-note') if (!session) { note.textContent = 'Sign in to send feedback.' return } if (!board) { note.textContent = 'The feedback board could not be read. Try again later.' return } // Validated before the session is restored: a too-long title should not cost // a token refresh, and its message is the same either way. let record: Record try { record = buildDiscussion(board, { title: $('feedback-title').value, body: $('feedback-body').value, tags: tickedTags(), }) } catch (err) { note.textContent = err instanceof Error ? err.message : String(err) return } const did = session.did const send = $('feedback-send') send.disabled = true note.textContent = 'Sending…' try { const agent = await agentForWrite('send feedback') const { data } = await agent.com.atproto.repo.createRecord({ repo: did, collection: DISCUSSION_COLLECTION, record, }) console.debug('[substandard] feedback posted', data.uri) feedbackPosted(did, data.uri) } catch (err) { console.debug('[substandard] feedback post failed', err) // A session granted before this extension asked for the feedback scope is // refused by the PDS, not by anything here — see isScopeError. note.textContent = isScopeError(err) ? 'This sign-in cannot post feedback. Sign in again to allow it.' : `Failed: ${err instanceof Error ? err.message : err}` } send.disabled = false }) function setupTheme(): void { themeChoice = readThemeChoice() applyTheme(themeChoice) updateThemeControls() // While the choice is System, follow the OS when it changes. watchSystemTheme(() => { if (readThemeChoice() === 'system') { applyTheme('system') updateThemeControls() } }) } function updateThemeControls(): void { $('theme-btn').setAttribute('aria-label', `Theme: ${THEME_LABELS[themeChoice]}`) for (const item of $('theme-menu').querySelectorAll('[data-theme-choice]')) { item.setAttribute('aria-checked', String(item.dataset.themeChoice === themeChoice)) } } function chooseTheme(choice: ThemeChoice): void { themeChoice = choice setTheme(choice) updateThemeControls() } type TabId = 'page' | 'subscriptions' | 'feedback' const TAB_ORDER: TabId[] = ['page', 'subscriptions', 'feedback'] const TAB_PANELS: Record = { page: 'panel-page', subscriptions: 'subscriptions-view', feedback: 'feedback', } let activeTab: TabId = 'page' function tabButton(tab: TabId): HTMLButtonElement { return $(`tab-${tab}`) } /** Show one panel and tell the other tabs they are not selected. */ function selectTab(tab: TabId, focus = false): void { if (tab === activeTab) { if (focus) tabButton(tab).focus() return } if (activeTab === 'subscriptions') subscriptionsView.close() activeTab = tab for (const candidate of TAB_ORDER) { const selected = candidate === tab const button = tabButton(candidate) button.setAttribute('aria-selected', String(selected)) button.tabIndex = selected ? 0 : -1 $(TAB_PANELS[candidate]).hidden = !selected } if (tab === 'subscriptions') subscriptionsView.open() if (tab === 'feedback') onFeedbackOpen() if (tab === 'page') render() if (focus) tabButton(tab).focus() } function setupTabs(): void { for (const tab of TAB_ORDER) { tabButton(tab).addEventListener('click', () => selectTab(tab)) } $('tabs').addEventListener('keydown', (event) => { const index = TAB_ORDER.indexOf(activeTab) let next: number | undefined if (event.key === 'ArrowRight') next = (index + 1) % TAB_ORDER.length else if (event.key === 'ArrowLeft') next = (index - 1 + TAB_ORDER.length) % TAB_ORDER.length else if (event.key === 'Home') next = 0 else if (event.key === 'End') next = TAB_ORDER.length - 1 if (next === undefined) return event.preventDefault() selectTab(TAB_ORDER[next]!, true) }) } /** * Wire the one set of controls that need keyboard and focus behavior: the * menus, the tab bar, the sign-in disclosure, and Escape/outside-click. Called * once, before any state is loaded, so every handler sees a fully wired popup. */ function setupControls(): void { setupTheme() const menu = (trigger: HTMLElement, panel: HTMLElement, onOpen?: () => void) => wireMenu({ trigger, menu: panel, onOpen: () => { setSigninPanel(false) onOpen?.() }, }) menu($('account-btn'), $('account-menu')) menu($('open-more'), $('reader-menu')) menu($('theme-btn'), $('theme-menu')) menu($('debug-open'), $('debug-menu'), () => debugNote('')) setupTabs() signinDisclosure = wireDisclosure({ trigger: $('signin-open'), panel: $('signin-panel'), onOpen: () => { closeMenus() $('handle-input').focus() }, }) subscriptionsView.mount({ session: () => session, expired: () => sessionExpired, readerId: () => defaultReader, openSignin: () => openSigninPanel(), openUrl: (url) => openUrl(url), onSessionExpired: () => { sessionExpired = true session = undefined void prefillLastHandle() renderAccount() render() }, }) for (const item of $('theme-menu').querySelectorAll('[data-theme-choice]')) { item.addEventListener('click', () => { const choice = item.dataset.themeChoice if (isThemeChoice(choice)) chooseTheme(choice) }) } document.addEventListener('click', () => { closeMenus() setSigninPanel(false) }) document.addEventListener('keydown', (event) => { if (event.key !== 'Escape') return closeMenus(true) signinDisclosure.close(true) $('signin-open').hidden = !!session }) } // The running build, read from the manifest rather than baked in at build // time, so it is the version Chrome actually installed and can be read back // in a bug report. Dev-channel builds carry the commit in version_name // ("1.4.0+abc1234"); store builds have no version_name and show the version. const manifest = ext.runtime.getManifest() $('version').textContent = `v${manifest.version_name ?? manifest.version}` setupControls() init()