// Asteri self-hosted front end. // Reads come from the local indexer (index.astronomi.ca); all writes go straight // to the signed-in member's own PDS over their OAuth session. The indexer // follows the firehose, so new records appear within a second or two. const API = 'https://boards.astronomi.ca/api'; const PROFILE_API = 'https://public.api.bsky.app/xrpc/app.bsky.actor.getProfile'; const CLIENT_ID = 'https://boards.astronomi.ca/client-metadata.json'; const HANDLE_RESOLVER = 'https://resolve.astronomi.ca'; const BOARDS = [ { slug: 'sophia', name: 'Sophia', theme: 'Wise', color: '#7ba3e8', description: 'General discussions, blogging, talk, ideas & advice. Insightful conversations, ideas, theories, science, philosophy, learning, and life advice. Best tags: Conversations, Thoughts & Ideas, Writings, Help & Support.' }, { slug: 'astra', name: 'Astra', theme: 'Space', color: '#b2dbe3', description: 'Astronomy, cosmology & science fiction. Space missions, astrophysics, cosmic consciousness, new scientific discoveries, and sci-fi. Best tags: Articles & Resources, Photos & Images, Thoughts & Ideas, Creations.' }, { slug: 'pleroma', name: 'Pleroma', theme: 'Culture', color: '#f3efc6', description: 'Art, myths, depth psychology & theories. Creative projects, music, visual art, Jungian psychology, astrology, mythology, and open speculations. Best tags: Creations, Writings, Thoughts & Ideas, Experiences.' }, { slug: 'terra', name: 'Terra', theme: 'Globe', color: '#ddbb98', description: 'Earth, nature, ecology & world resources. Environmental discussions, nature photography, climate, human society, and curated links and articles from around the web. Best tags: Photos & Images, Articles & Resources, Links and Files, Conversations.' }, { slug: 'simulacra', name: 'Simulacra', theme: 'Code', color: '#ee8fa3', description: 'Data, scripts, spells, symbols & syntax. Apps, software, synths, data visualization, ongoing design projects, language, and symbolic systems. Best tags: Links and Files, Creations, Photos & Images, Thoughts & Ideas.' }, { slug: 'sacra', name: 'Sacra', theme: 'Life', color: '#7cb587', description: 'Spirituality, support & meaningful reflections. Spiritual experiences, life integration, peer support, memorials, and deeper personal reflections. Best tags: Help & Support, Experiences, Conversations, Writings.' }, { slug: 'umbra', name: 'Umbra', theme: 'Sense', color: '#c0c0c0', description: 'Dreams, the unconscious, archives & off-topic. Dream journaling, free-space talks, and hidden or restricted threads. Best tags: Experiences, Links and Files, Conversations.' }, ]; const FLAIR_COLORS = [ ['Mercury', '#c0c0c0'], ['Venus', '#d4cec0'], ['Earth', '#7cb587'], ['Moon', '#fdf6ff'], ['Mars', '#ee8fa3'], ['Jupiter', '#ddbb98'], ['Saturn', '#f3efc6'], ['Ouranos', '#b2dbe3'], ['Neptune', '#7ba3e8'], ]; const POST_TAGS = [ 'Conversations', 'Experiences', 'Thoughts & Ideas', 'Creations', 'Writings', 'Music', 'Photos & Images', 'Articles & Resources', 'Help & Support', 'Links & Files', ]; const TAB_COLORS = ['#c0c0c0', '#d4cec0', '#ee8fa3', '#ddbb98', '#f3efc6', '#b2dbe3', '#7ba3e8']; // Left: Asteri, Members, Boards, Topics. Center: Spaces. Right: Lists, // Following, Feeds, custom feed tabs, and the + button. const HOME_LEFT = [['asteri', 'Asteri'], ['boards', 'Boards'], ['topics', 'Topics']]; const HOME_CENTER = [['spaces', 'Spaces']]; const HOME_RIGHT = [['lists', 'Lists'], ['following', 'Following'], ['feeds', 'Feeds']]; const ALL_HOME = [...HOME_LEFT, ...HOME_CENTER, ...HOME_RIGHT]; // Row of toggleable tag pills; returns the element and a getter for the picks. // `pre` preselects tags (used when editing an existing post). function tagPicker(max = 3, pre = []) { const wrap = el('div', 'meta'); wrap.style.gap = '0.4rem'; const picked = new Set(); const ON = 'color:var(--heading);border-color:var(--dim);background:rgba(159,191,224,0.12)'; for (const t of POST_TAGS) { const b = el('button', 'tag', t); b.type = 'button'; b.setAttribute('aria-pressed', 'false'); b.onclick = () => { if (picked.has(t)) { picked.delete(t); b.setAttribute('aria-pressed', 'false'); b.style.cssText = ''; } else if (picked.size < max) { picked.add(t); b.setAttribute('aria-pressed', 'true'); b.style.cssText = ON; } }; if (pre.includes(t) && picked.size < max) { picked.add(t); b.setAttribute('aria-pressed', 'true'); b.style.cssText = ON; } wrap.appendChild(b); } return { wrap, getTags: () => [...picked] }; } // Moderation: hide-from-index, owner-token protected. Admins see Hide tools; // the token is entered once and kept in this browser's localStorage — it is // never in the source. Hiding removes content from THIS site's index; the // record remains in the author's repo (the protocol working as designed). const ADMINS = new Set(['did:plc:rnn63n5auoexnihjf7zllr6l', 'did:plc:sredqd6wh7spqe25dkm5cxrv']); const isAdmin = () => !!session && ADMINS.has(myDid); const LABELER_DID = 'did:plc:rn6spz2zedgovfgjxczjor4i'; // ozone.astronomi.ca // Bluesky's own global content-label categories, same wording and // defaults as the official app's Content filters settings. These read // and write the member's real app.bsky.actor.defs preferences (not an // Asteri-only setting), so the choice made here is the same one their // Bluesky app honors, and vice versa. const CONTENT_LABEL_DEFS = [ { id: 'porn', name: 'Adult Content', desc: 'Explicit sexual images.', adult: true }, { id: 'sexual', name: 'Sexually Suggestive', desc: 'Does not include nudity.', adult: true }, { id: 'graphic-media', name: 'Graphic Media', desc: 'Explicit or potentially disturbing media.', adult: true }, { id: 'nudity', name: 'Non-sexual Nudity', desc: 'E.g. artistic nudes.', adult: false }, ]; let contentPrefsCache = null; // Reads the member's real Bluesky preferences, pulls out adultContentPref // and any global (no labelerDid) contentLabelPref rows, and fills in // Bluesky's own defaults for anything not yet set. async function loadContentPrefs() { if (contentPrefsCache) return contentPrefsCache; const out = { adultEnabled: false, labels: { porn: 'hide', sexual: 'warn', 'graphic-media': 'warn', nudity: 'warn' } }; try { const res = await session.fetchHandler(myPds + '/xrpc/app.bsky.actor.getPreferences'); const data = await res.json().catch(() => ({})); const prefs = data.preferences ?? []; const adult = prefs.find((pr) => pr.$type === 'app.bsky.actor.defs#adultContentPref'); if (adult) out.adultEnabled = !!adult.enabled; for (const pr of prefs) { if (pr.$type === 'app.bsky.actor.defs#contentLabelPref' && !pr.labelerDid && pr.label in out.labels) { out.labels[pr.label] = pr.visibility; } } } catch { /* fall back to defaults */ } contentPrefsCache = out; return out; } // Writes adultContentPref + the four global contentLabelPref rows back, // preserving every other preference entry untouched (putPreferences // replaces the whole array, so a naive write would wipe saved feeds etc). async function saveContentPrefs(next) { const res = await session.fetchHandler(myPds + '/xrpc/app.bsky.actor.getPreferences'); const data = await res.json().catch(() => ({})); const prefs = (data.preferences ?? []).filter((pr) => pr.$type !== 'app.bsky.actor.defs#adultContentPref' && !(pr.$type === 'app.bsky.actor.defs#contentLabelPref' && !pr.labelerDid && pr.label in next.labels)); prefs.push({ $type: 'app.bsky.actor.defs#adultContentPref', enabled: next.adultEnabled }); for (const [label, visibility] of Object.entries(next.labels)) { prefs.push({ $type: 'app.bsky.actor.defs#contentLabelPref', label, visibility }); } const putRes = await session.fetchHandler(myPds + '/xrpc/app.bsky.actor.putPreferences', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ preferences: prefs }), }); if (!putRes.ok) { const d = await putRes.json().catch(() => ({})); throw new Error(d.message || d.error || ('HTTP ' + putRes.status)); } contentPrefsCache = next; } // Worst visibility among a post's matching global content labels // ('hide' beats 'warn' beats 'show'/'ignore'), or null if none apply. function contentFilterFor(fp, prefs) { const vals = (fp?.labels ?? []).map((l) => l.val); let worst = null; for (const def of CONTENT_LABEL_DEFS) { if (!vals.includes(def.id)) continue; if (def.adult && !prefs.adultEnabled) return 'hide'; const v = prefs.labels[def.id]; if (v === 'hide') return 'hide'; if (v === 'warn' && worst !== 'hide') worst = 'warn'; } return worst; } // Ozone moderator panel: gated on membership in the labeler's own team, // checked once at boot. A non-member's listMembers call 403s -- treated // as not-a-moderator, no separate token needed. let isOzoneMod = false; let myOzoneRole = null; async function checkOzoneMod() { try { const res = await session.fetchHandler( myPds + '/xrpc/tools.ozone.team.listMembers', { headers: { 'atproto-proxy': LABELER_DID + '#atproto_labeler' } }); if (!res.ok) throw new Error('not a member'); const data = await res.json(); const me = (data.members ?? []).find((m) => m.did === myDid); isOzoneMod = !!me; myOzoneRole = me?.role ?? null; } catch { isOzoneMod = false; myOzoneRole = null; } } async function emitOzoneEvent(event, uri, cid) { const res = await session.fetchHandler( myPds + '/xrpc/tools.ozone.moderation.emitEvent', { method: 'POST', headers: { 'content-type': 'application/json', 'atproto-proxy': LABELER_DID + '#atproto_labeler', }, body: JSON.stringify({ createdBy: myDid, subject: cid ? { $type: 'com.atproto.repo.strongRef', uri, cid } : { $type: 'com.atproto.admin.defs#repoRef', did: uri }, event, modTool: { name: 'asteri' }, }), }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.message || data.error || ('HTTP ' + res.status)); return data; } async function modCall(action, body = {}) { const token = localStorage.getItem('asteri:modToken') ?? window.prompt('Moderation token (from the indexer\'s MOD_TOKEN):') ?? ''; if (!token) throw new Error('No token'); localStorage.setItem('asteri:modToken', token); const res = await fetch(API + '/mod/' + action, { method: 'POST', headers: { 'content-type': 'application/json', 'x-mod-token': token }, body: JSON.stringify(body), }); const data = await res.json().catch(() => ({})); if (res.status === 403) { localStorage.removeItem('asteri:modToken'); throw new Error('Token rejected — re-enter it next time'); } if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`); return data; } function modTools(uri, kind, label, board) { if (!isAdmin()) return null; const b = el('button', 'linklike', 'Hide'); b.style.color = 'var(--danger)'; b.title = `Hide this ${label} from this site (the record stays in the author's repo)`; b.onclick = async (e) => { e.preventDefault(); e.stopPropagation(); const reason = window.prompt(`Hide this ${label} from Asteri? Reason (optional):`) ?? null; if (reason === null) return; b.disabled = true; try { await modCall('hide', { uri, kind, reason }); toast(`${label} hidden from this site`); // A hidden topic's page 404s once the index drops it — go back to its board. if (label === 'topic') location.hash = '#/boards/' + (board ?? 'sophia'); else window.setTimeout(route, 800); } catch (err) { toast('Hide failed: ' + err.message); b.disabled = false; } }; return b; } function ozoneModTools(uri, cid, label) { if (!isOzoneMod) return null; const wrap = el('span', 'meta'); const act = async (fn, busyMsg, doneMsg) => { try { toast(busyMsg); await fn(); toast(doneMsg); window.setTimeout(route, 800); } catch (err) { toast('Action failed: ' + err.message); } }; const ack = el('button', 'linklike', 'Acknowledge'); ack.onclick = () => act(() => emitOzoneEvent({ $type: 'tools.ozone.moderation.defs#modEventAcknowledge' }, uri, cid), 'Acknowledging...', 'Acknowledged'); const esc = el('button', 'linklike', 'Escalate'); esc.onclick = () => act(() => emitOzoneEvent({ $type: 'tools.ozone.moderation.defs#modEventEscalate' }, uri, cid), 'Escalating...', 'Escalated'); const lbl = el('button', 'linklike', 'Label'); lbl.onclick = () => { const val = window.prompt('Label value(s), comma/space separated:'); if (!val) return; act(() => emitOzoneEvent({ $type: 'tools.ozone.moderation.defs#modEventLabel', createLabelVals: val.split(/[\s,]+/).filter(Boolean), negateLabelVals: [], }, uri, cid), 'Labeling...', 'Label applied'); }; const td = el('button', 'linklike', 'Takedown'); td.style.color = 'var(--danger)'; td.onclick = () => { const comment = window.prompt('Takedown this ' + label + '? Reason (optional):') ?? ''; act(() => emitOzoneEvent({ $type: 'tools.ozone.moderation.defs#modEventTakedown', comment }, uri, cid), 'Taking down...', label + ' taken down'); }; const rtd = el('button', 'linklike', 'Reverse takedown'); rtd.onclick = () => act(() => emitOzoneEvent({ $type: 'tools.ozone.moderation.defs#modEventReverseTakedown' }, uri, cid), 'Reversing...', 'Takedown reversed'); wrap.append(ack, esc, lbl, td, rtd); return wrap; } // Fetches open + escalated subject statuses from the Ozone queue, proxied // through the signed-in moderator's own PDS -- same pattern as checkOzoneMod. async function fetchOzoneQueue(reviewState) { const qs = new URLSearchParams({ limit: '50', reviewState }); const res = await session.fetchHandler( myPds + '/xrpc/tools.ozone.moderation.queryStatuses?' + qs.toString(), { headers: { 'atproto-proxy': LABELER_DID + '#atproto_labeler' } }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.message || data.error || ('HTTP ' + res.status)); return data.subjectStatuses ?? []; } // One row in the Ozone queue: subject link, review state, report/comment // context, and the same action row used on individual posts/comments. function ozoneQueueItem(st) { const card = el('div', 'card'); const sub = st.subject ?? {}; const uri = sub.uri ?? sub.did; const cid = sub.cid; const isAsteriRecord = typeof sub.uri === 'string' && sub.uri.includes('/ca.astronomi.boards.'); const kind = sub.uri?.includes('.comment/') ? 'comment' : sub.uri ? 'topic' : 'account'; const head = el('div', 'meta'); head.style.marginTop = '0'; const stateLabel = (st.reviewState ?? '').split('#').pop()?.replace('review', '') || 'unknown'; head.appendChild(el('span', 'tag', stateLabel)); if (st.takendown) { const td = el('span', 'tag', 'Taken down'); td.style.color = 'var(--danger)'; head.appendChild(td); } if (st.lastReportedAt) head.appendChild(el('span', 'muted small', 'reported ' + timeAgo(st.lastReportedAt))); card.appendChild(head); if (isAsteriRecord && kind === 'topic') { const rkey = sub.uri.split('/').pop(); const link = el('a', null, 'Topic: ' + rkey); link.href = '#/post/' + rkey; card.appendChild(link); } else { card.appendChild(el('p', 'small', uri ?? 'Unknown subject')); } if (st.comment) card.appendChild(el('p', 'muted small', 'Note: ' + st.comment)); if (Array.isArray(st.tags) && st.tags.length) card.appendChild(el('p', 'muted small', 'Tags: ' + st.tags.join(', '))); const ot = ozoneModTools(uri, cid, kind); if (ot) card.appendChild(ot); return card; } // Moderation labels from the Ozone labeler, attached by the indexer. // '!warn' gets a click-through blur matching the global-label convention; // anything else (spam, off-topic, etc.) renders as a small amber chip. function labelChips(labels) { if (!labels || !labels.length) return null; const wrap = el('span', 'label-chips'); for (const l of labels) { const chip = el('span', 'label-chip' + (l.val === '!warn' ? ' label-chip-warn' : ''), l.val === '!warn' ? 'Warning' : l.val); chip.title = 'Labeled by the moderation service' + (l.cts ? ' on ' + new Date(l.cts).toLocaleDateString() : ''); wrap.appendChild(chip); } return wrap; } function hasWarnLabel(labels) { return !!labels?.some((l) => l.val === '!warn'); } // ---------- state ---------- let oauth = null; let session = null; let myDid = null; let myPds = null; const myVotes = new Map(); // subjectUri -> my vote record uri const myBallots = new Map(); // postUri -> { uri, option } const myFollows = new Map(); // postUri -> my topicFollow record uri const profiles = new Map(); // did -> { handle?, displayName?, avatar?, banner?, verified?, trustedVerifier? } const forumProfiles = new Map(); // did -> forum profile | null (ca.astronomi.boards.profile) const pdsByDid = new Map(); // did -> pds endpoint (for blob URLs) let currentPostBoard = null; // board slug of whichever topic is open, for banner 'up a level' let composeOpener = null; // set by the boards tab while it's on screen let homeSelect = null; // set by viewHome; lets compose switch to Boards const app = document.getElementById('app'); const authBox = document.getElementById('auth'); // ---------- tiny dom helpers ---------- function el(tag, cls, text) { const n = document.createElement(tag); if (cls) n.className = cls; if (text !== undefined) n.textContent = text; return n; } // A small "Copy link" button that writes the clean, crawler-friendly path // (/p/:rkey or /b/:slug) to the clipboard — not the hash URL, which servers // never see and can't generate og cards for. function copyLinkButton(path, label) { const b = el('button', 'link-copy-btn', label ?? 'Copy link'); b.type = 'button'; b.onclick = async () => { try { await navigator.clipboard.writeText(location.origin + path); toast('Link copied'); } catch { toast('Could not copy link'); } }; return b; } // A small cyan share-arrow icon button — copies a clean path link, same // clipboard logic as copyLinkButton, just an icon instead of a text pill. function shareIconButton(path, label) { const b = el('button', 'share-icon-btn'); b.type = 'button'; b.title = label ?? 'Copy link'; b.setAttribute('aria-label', label ?? 'Copy link'); b.innerHTML = ''; b.onclick = async () => { try { await navigator.clipboard.writeText(location.origin + path); toast('Link copied'); } catch { toast('Could not copy link'); } }; return b; } function toast(msg) { const t = document.getElementById('toast'); t.textContent = msg; t.classList.add('show'); window.setTimeout(() => t.classList.remove('show'), 3200); } function timeAgo(iso) { const s = Math.max(1, (Date.now() - +new Date(iso)) / 1000); if (s < 60) return `${Math.floor(s)}s ago`; if (s < 3600) return `${Math.floor(s / 60)}m ago`; if (s < 86400) return `${Math.floor(s / 3600)}h ago`; return `${Math.floor(s / 86400)}d ago`; } async function getJSON(path) { const res = await fetch(API + path); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.error || `HTTP ${res.status}`); return data; } function rkeyOf(uri) { return uri.split('/').pop(); } // All posts across every board — one request to the indexer's global route. async function loadAllPosts() { const data = await getJSON('/posts'); return data.posts ?? []; } // ---------- rich text ---------- // Bodies may carry a small sanitized subset of HTML (from richer clients). // Plain-text bodies render untouched; anything with tags is sanitized first. const HTML_RE = /<\/?[a-z][\s\S]*?>/i; function sanitizeHtml(html) { const ALLOWED = new Set(['B', 'STRONG', 'I', 'EM', 'S', 'STRIKE', 'U', 'UL', 'OL', 'LI', 'BR', 'P', 'DIV', 'BLOCKQUOTE', 'A', 'SPAN', 'FONT', 'IMG']); const doc = new DOMParser().parseFromString(html, 'text/html'); const walk = (node) => { for (const child of Array.from(node.childNodes)) { if (child.nodeType !== 1) continue; const el = child; if (el.tagName === 'SCRIPT' || el.tagName === 'STYLE') { el.remove(); continue; } if (!ALLOWED.has(el.tagName)) { walk(el); el.replaceWith(...el.childNodes); continue; } if (el.tagName === 'A') { const href = el.getAttribute('href') ?? ''; for (const a of Array.from(el.attributes)) el.removeAttribute(a.name); if (/^https?:\/\//i.test(href)) { el.setAttribute('href', href); el.setAttribute('target', '_blank'); el.setAttribute('rel', 'noopener noreferrer'); } else { el.replaceWith(...el.childNodes); continue; } } else if (el.tagName === 'IMG') { const src = el.getAttribute('src') ?? ''; const alt = el.getAttribute('alt') ?? ''; for (const a of Array.from(el.attributes)) el.removeAttribute(a.name); if (/^https?:\/\//i.test(src)) { el.setAttribute('src', src); el.setAttribute('alt', alt); el.setAttribute('style', 'max-width:100%;height:auto;border-radius:8px;margin:0.4rem 0;display:block'); el.setAttribute('loading', 'lazy'); } else { el.remove(); continue; } } else if (el.tagName === 'SPAN' || el.tagName === 'FONT') { const color = el.style?.color || el.getAttribute('color') || ''; for (const a of Array.from(el.attributes)) el.removeAttribute(a.name); const m = color.match(/#(?:[0-9a-fA-F]{3,4}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})/); if (m) el.setAttribute('style', `color:${m[0]}`); } else { for (const a of Array.from(el.attributes)) el.removeAttribute(a.name); } walk(el); } }; walk(doc.body); return doc.body.innerHTML; } // Render a body: sanitized HTML when it contains tags, plain text otherwise. // Rich embeds for known media links: YouTube, Vimeo, SoundCloud, Bandcamp. // Anything else returns null and the caller renders its normal link. function linkEmbed(url, bandcampId) { try { const u = new URL(url); const h = u.hostname.replace(/^www\./, ''); const frame = (src, ratio) => { const w = el('div', 'embed-frame'); if (ratio) w.style.aspectRatio = ratio; const f = el('iframe'); f.src = src; f.loading = 'lazy'; f.allowFullscreen = true; f.setAttribute('allow', 'accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture'); f.title = 'Embedded media'; w.appendChild(f); return w; }; if (h === 'youtu.be') return frame('https://www.youtube-nocookie.com/embed' + u.pathname, '16/9'); if (h === 'youtube.com' || h === 'm.youtube.com') { const v = u.searchParams.get('v'); if (v) return frame('https://www.youtube-nocookie.com/embed/' + v, '16/9'); const m = u.pathname.match(/^\/(shorts|live|embed)\/([\w-]+)/); if (m) return frame('https://www.youtube-nocookie.com/embed/' + m[2], '16/9'); return null; } if (h === 'vimeo.com') { const m = u.pathname.match(/^\/(\d+)/); if (m) return frame('https://player.vimeo.com/video/' + m[1], '16/9'); return null; } if (h === 'soundcloud.com') { return frame('https://w.soundcloud.com/player/?url=' + encodeURIComponent(url) + '&visual=false', null); } if (h === 'on.soundcloud.com') return null; // short links don't resolve server-side; keep the link card if (h.endsWith('.bandcamp.com')) { // Bandcamp's player needs a real numeric track/album ID that only // lives in the page's own metadata — the indexer fetches it in the // background and stores it. Until that arrives, fall through to the // plain link card rather than show a guaranteed-black iframe. if (!bandcampId) return null; const m = u.pathname.match(/^\/(track|album)\//); if (m) { const w = frame('https://bandcamp.com/EmbeddedPlayer/' + m[1] + '=' + bandcampId + '/size=large/bgcol=030f2a/linkcol=b2dbe3/tracklist=false/transparent=true/', null); if (w) { w.style.cssText += 'width:350px;height:470px;margin:0.6rem auto 0;'; } return w; } return null; } } catch { /* not a URL */ } return null; } // A real preview card for a post's link, built from the indexer's scraped // og:title/description/image. Used only when linkEmbed() has no rich embed // for the URL and the scrape actually returned something. function linkCard(p) { if (!p.linkTitle && !p.linkImage) return null; const card = el('a', 'link-card'); card.href = p.url; card.target = '_blank'; card.rel = 'noopener noreferrer'; if (p.linkImage) { const img = el('img', 'link-card-image'); img.src = p.linkImage; img.loading = 'lazy'; img.alt = ''; card.appendChild(img); } const body = el('div', 'link-card-body'); const dom = domainOf(p.url); if (dom) body.appendChild(el('span', 'link-card-domain', dom)); if (p.linkTitle) body.appendChild(el('span', 'link-card-title', p.linkTitle)); if (p.linkDesc) body.appendChild(el('span', 'link-card-desc', p.linkDesc)); card.appendChild(body); return card; } function richText(text) { const div = el('div', 'comment-body'); if (text && HTML_RE.test(text)) div.innerHTML = sanitizeHtml(text); else div.textContent = text ?? ''; return div; } function signatureLine(signature, color) { if (!signature) return null; const p = el('p', 'signature', '— ' + signature); if (color) p.style.color = color; return p; } // ---------- rich editor ---------- // A small contentEditable editor writing sanitized HTML. Toolbar buttons run // document.execCommand (deprecated but universal); output passes the same // sanitizer as read-side rendering before it ever reaches a record. function richEditor(placeholder) { const wrap = el('div', 'editor'); const bar = el('div', 'editor-bar'); bar.setAttribute('role', 'toolbar'); bar.setAttribute('aria-label', 'Text formatting'); const area = el('div', 'editor-area'); area.contentEditable = 'true'; area.dataset.placeholder = placeholder ?? ''; area.setAttribute('role', 'textbox'); area.setAttribute('aria-multiline', 'true'); const exec = (cmd, arg) => { area.focus(); document.execCommand(cmd, false, arg); }; const LINK_ICON = ''; const PHOTO_ICON = ''; const buttons = [ ['B', 'Bold', () => exec('bold')], ['I', 'Italic', () => exec('italic')], ['S', 'Strikethrough', () => exec('strikeThrough')], ['•', 'Bullet list', () => exec('insertUnorderedList')], ['1.', 'Numbered list', () => exec('insertOrderedList')], [LINK_ICON, 'Add link', () => { const u = window.prompt('Link URL (https://…)'); if (u && /^https?:\/\//i.test(u)) exec('createLink', u); }], [PHOTO_ICON, 'Add photo by URL', () => { const u = window.prompt('Photo URL (https://…)'); if (u && /^https?:\/\//i.test(u)) exec('insertImage', u); }], ['⌫', 'Clear formatting', () => exec('removeFormat')], ]; for (const [glyph, label, fn] of buttons) { const b = el('button', 'linklike'); if (glyph.startsWith('<')) b.innerHTML = glyph; else b.textContent = glyph; b.type = 'button'; b.title = label; b.setAttribute('aria-label', label); b.onmousedown = (e) => e.preventDefault(); // keep the text selection b.onclick = fn; bar.appendChild(b); } const colors = el('span', 'editor-colors'); for (const [, c] of FLAIR_COLORS) { const dot = el('button', 'color-dot'); dot.type = 'button'; dot.style.background = c; dot.title = 'Text color'; dot.setAttribute('aria-label', 'Text color ' + c); dot.onmousedown = (e) => e.preventDefault(); dot.onclick = () => exec('foreColor', c); colors.appendChild(dot); } bar.prepend(colors); // bubbles on the left, ahead of the formatting buttons wrap.append(bar, area); return { wrap, // Sanitized HTML for the record; '' when visually empty. getHTML: () => { const html = area.innerHTML.trim(); if (!html || !area.textContent?.trim() && !area.querySelector('img')) return ''; return sanitizeHtml(html); }, // Prefill for editing an existing record; sanitized like any other input. setHTML: (html) => { area.innerHTML = sanitizeHtml(html ?? ''); }, focus: () => area.focus(), }; } // ---------- identity ---------- async function pdsOf(did) { if (pdsByDid.has(did)) return pdsByDid.get(did); const url = did.startsWith('did:web:') ? 'https://' + did.slice(8).replace(/:/g, '/') + '/.well-known/did.json' : 'https://plc.directory/' + did; const doc = await (await fetch(url)).json(); const svc = (doc.service ?? []).find((s) => s.id === '#atproto_pds' || s.type === 'AtprotoPersonalDataServer'); if (!svc) throw new Error('No PDS found for ' + did); pdsByDid.set(did, svc.serviceEndpoint); return svc.serviceEndpoint; } // Blobs live on the author's PDS; resolve lazily and set the img src when known. // If the author's PDS can't serve the blob, fall back to Bluesky's CDN. // Clicking opens the lightbox with the full image and its alt text. function blobImg(did, cid, alt, cls) { const img = el('img', cls ?? 'media-img'); img.alt = alt ?? ''; img.loading = 'lazy'; img.style.cursor = 'zoom-in'; pdsOf(did).then((pds) => { img.onerror = () => { img.onerror = () => img.remove(); img.src = `https://cdn.bsky.app/img/feed_fullsize/plain/${encodeURIComponent(did)}/${encodeURIComponent(cid)}@jpeg`; }; img.src = `${pds}/xrpc/com.atproto.sync.getBlob?did=${encodeURIComponent(did)}&cid=${encodeURIComponent(cid)}`; img.onclick = () => openLightbox( `https://cdn.bsky.app/img/feed_fullsize/plain/${encodeURIComponent(did)}/${encodeURIComponent(cid)}@jpeg`, alt, (alt || 'image').replace(/\.\w+$/, '') + '.jpg', `${pds}/xrpc/com.atproto.sync.getBlob?did=${encodeURIComponent(did)}&cid=${encodeURIComponent(cid)}`); }).catch(() => { img.remove(); }); return img; } // Full-screen image viewer: full image, alt text, open-in-tab + download. // Viewing uses Bluesky's CDN (proper image/jpeg headers — displays inline). // Downloads fetch the bytes from the author's PDS, which allows cross-origin // reads; the CDN blocks them. Falls back between the two if one fails. function openLightbox(src, alt, filename, fetchSrc) { const box = el('div', 'lightbox'); box.setAttribute('role', 'dialog'); box.setAttribute('aria-label', alt || 'Image viewer'); const img = el('img'); img.src = src; img.alt = alt ?? ''; box.appendChild(img); if (alt) box.appendChild(el('p', 'lb-alt', alt)); const row = el('div', 'lb-row'); const open = el('a', null, 'Open in tab ↗'); open.href = src; open.target = '_blank'; open.rel = 'noopener noreferrer'; const save = el('button', null, 'Download'); save.type = 'button'; save.onclick = async () => { save.disabled = true; let blob = null; for (const u of [fetchSrc, src]) { if (!u || blob) continue; try { const res = await fetch(u); if (res.ok) blob = await res.blob(); } catch { /* try the next source */ } } if (blob) { const a = el('a'); a.href = URL.createObjectURL(blob); a.download = filename || 'image.jpg'; a.click(); URL.revokeObjectURL(a.href); } else { toast('Download failed — use Open in tab and save from there'); } save.disabled = false; }; const close = el('button', null, 'Close'); close.type = 'button'; close.onclick = () => box.remove(); row.append(open, save, close); box.appendChild(row); box.onclick = (e) => { if (e.target === box) box.remove(); }; const onKey = (e) => { if (e.key === 'Escape') { box.remove(); document.removeEventListener('keydown', onKey); } }; document.addEventListener('keydown', onKey); document.body.appendChild(box); } async function profileOf(did) { if (profiles.has(did)) return profiles.get(did); let p = null; try { const res = await fetch(PROFILE_API + '?actor=' + encodeURIComponent(did)); if (res.ok) { const d = await res.json(); p = { handle: d.handle, displayName: d.displayName, avatar: d.avatar, banner: d.banner, description: d.description, verified: d.verification?.verifiedStatus === 'valid', trustedVerifier: d.verification?.trustedVerifierStatus === 'valid', }; } } catch { /* fall through to DID label */ } profiles.set(did, p); return p; } function flairPill(text, color) { const c = color || '#c0c0c0'; const s = el('span', 'tag', text); s.style.cssText = `color:${c};border-color:${c}66;background:${c}14`; return s; } // Route Bluesky avatars through the img proxy's thumbnail preset — full-size // avatar PNGs are the heaviest recurring images on the site. function avatarThumb(url) { if (typeof url !== 'string') return url; return url.replace('https://cdn.bsky.social/img/avatar/plain/', 'https://cdn.bsky.app/img/avatar_thumbnail/plain/'); } function authorEl(did, flairText, flairColor) { const a = el('a', 'author', did.slice(0, 18) + '…'); a.href = '#/user/' + did; profileOf(did).then((p) => { if (!p) return; a.textContent = ''; if (p.avatar) { const img = el('img', 'avatar'); img.src = avatarThumb(p.avatar); img.alt = ''; a.appendChild(img); } a.appendChild(document.createTextNode(p.displayName || '@' + p.handle)); if (p.handle) a.title = '@' + p.handle; const fp = forumProfiles.get(did); const ft = flairText ?? fp?.flairText; const fc = flairColor ?? fp?.flairColor; if (ft) { a.appendChild(document.createTextNode(' ')); a.appendChild(flairPill(ft, fc)); } }); return a; } // ---------- auth ---------- async function bootAuth() { const { BrowserOAuthClient } = await import( 'https://cdn.jsdelivr.net/npm/@atproto/oauth-client-browser/+esm'); oauth = await BrowserOAuthClient.load({ clientId: CLIENT_ID, handleResolver: HANDLE_RESOLVER }); const init = await oauth.init(); session = init?.session ?? null; if (session) { myDid = session.sub; myPds = await pdsOf(myDid); loadMyVotes(); loadMyBallots(); loadMyFollows(); await checkOzoneMod(); await loadContentPrefs(); } renderAuth(); renderHeaderExtras(); applySettings(); } function renderAuth() { authBox.textContent = ''; if (session) { const who = el('a', 'who', myDid.slice(0, 16) + '…'); who.href = '#/user/' + myDid; profileOf(myDid).then((p) => { if (p?.handle) who.textContent = '@' + p.handle; }); const out = el('button', 'signout', 'Sign out'); out.onclick = async () => { await session.signOut(); location.reload(); }; authBox.append(who, out); } else { // Sign-in dropdown: pick your PDS, enter your handle, continue. Same OAuth // flow either way — the chooser just sets expectations, like the hosted Site. const wrap = el('div', 'signin'); const open = el('button', 'signin-btn', 'Sign in / Sign up'); open.setAttribute('aria-expanded', 'false'); const menu = el('div', 'pds-menu'); menu.setAttribute('role', 'dialog'); menu.setAttribute('aria-label', 'Choose your PDS'); menu.hidden = true; menu.appendChild(el('p', 'pds-head', 'Choose your PDS')); const input = el('input'); input.placeholder = 'you.astronomi.ca'; input.setAttribute('aria-label', 'Your handle'); const PDS_OPTIONS = [ ['Astronomica', 'The Astronomica PDS — home of Asteri.', 'you.astronomi.ca'], ['Bluesky', 'The Bluesky PDS (bsky.social accounts).', 'you.bsky.social'], ['Other PDS', 'Any other server — enter your full handle and we\'ll find it.', 'your.full.handle'], ]; for (const [name, hint, placeholder] of PDS_OPTIONS) { const opt = el('button', 'pds-opt'); opt.type = 'button'; opt.appendChild(el('span', 'pds-name', name)); opt.appendChild(el('span', 'pds-hint', hint)); opt.onclick = () => { input.value = ''; input.placeholder = placeholder; input.focus(); }; menu.appendChild(opt); } const go = el('button', 'primary', 'Continue'); const submit = () => { if (input.value.trim()) oauth.signIn(input.value.trim()); }; go.onclick = submit; input.onkeydown = (e) => { if (e.key === 'Enter') submit(); }; const foot = el('div', 'pds-foot'); foot.append(input, go); menu.appendChild(foot); menu.appendChild(el('p', 'muted small', 'New here? Signing in with any of these creates your account.')); const onDown = (e) => { if (!wrap.contains(e.target)) close(); }; const onKey = (e) => { if (e.key === 'Escape') close(); }; const close = () => { menu.hidden = true; open.setAttribute('aria-expanded', 'false'); document.removeEventListener('mousedown', onDown); document.removeEventListener('keydown', onKey); }; open.onclick = () => { if (!menu.hidden) { close(); return; } menu.hidden = false; open.setAttribute('aria-expanded', 'true'); document.addEventListener('mousedown', onDown); document.addEventListener('keydown', onKey); }; wrap.append(open, menu); authBox.appendChild(wrap); } } // Header actions, matching the hosted Site: compose pencil, notification bell // with a dropdown panel, then Members / Mod links beside the auth box. // Settings panel (cog, right of the bell): small site preferences, kept on // this device. Reduced motion also honors the OS setting by default. const SETTINGS_KEY = 'asteri:settings'; function readSettings() { try { return { reducedMotion: false, defaultTab: 'boards', ...JSON.parse(localStorage.getItem(SETTINGS_KEY) ?? '{}') }; } catch { return { reducedMotion: false, defaultTab: 'boards' }; } } function writeSetting(k, v) { const s = readSettings(); s[k] = v; try { localStorage.setItem(SETTINGS_KEY, JSON.stringify(s)); } catch { /* private mode */ } applySettings(); } function applySettings() { document.body.classList.toggle('reduced-motion', !!readSettings().reducedMotion); } function settingsPanel(anchor) { const existing = document.getElementById('settingsMenu'); if (existing) { existing.remove(); return; } const s = readSettings(); const menu = el('div', 'pds-menu'); menu.id = 'settingsMenu'; menu.appendChild(el('p', 'pds-head', 'Settings')); const toggleRow = (label, key) => { const row = el('label', 'crosspost'); row.style.cssText = 'display:flex;align-items:center;gap:0.5rem;padding:0.5rem 0.7rem;width:100%'; const box = el('input'); box.type = 'checkbox'; box.checked = !!s[key]; box.onchange = () => writeSetting(key, box.checked); row.append(box, document.createTextNode(label)); return row; }; menu.appendChild(toggleRow('Reduced motion (stars, twilight backdrop)', 'reducedMotion')); if (session) { const cfSection = el('div'); cfSection.style.cssText = 'padding:0.5rem 0.7rem;width:100%'; cfSection.appendChild(el('p', 'pds-head', 'Content filters')); cfSection.appendChild(el('p', 'muted small', 'Loading…')); menu.appendChild(cfSection); loadContentPrefs().then((prefs) => { cfSection.textContent = ''; cfSection.appendChild(el('p', 'pds-head', 'Content filters')); const adultRow = el('label', 'crosspost'); adultRow.style.cssText = 'display:flex;align-items:center;gap:0.5rem;padding:0.3rem 0;width:100%'; const adultBox = el('input'); adultBox.type = 'checkbox'; adultBox.checked = prefs.adultEnabled; adultBox.onchange = () => { prefs.adultEnabled = adultBox.checked; saveContentPrefs(prefs).then(() => toast('Content filters updated')).catch((e) => toast('Save failed: ' + e.message)); }; adultRow.append(adultBox, document.createTextNode('Enable adult content')); cfSection.appendChild(adultRow); for (const def of CONTENT_LABEL_DEFS) { const row = el('div'); row.style.cssText = 'padding:0.4rem 0'; row.appendChild(el('span', 'small', def.name)); row.appendChild(el('span', 'muted small', ' — ' + def.desc)); const sel = el('select'); sel.style.cssText = 'display:block;margin-top:0.2rem'; for (const [val, text] of [['show', 'Show'], ['warn', 'Warn'], ['hide', 'Hide']]) { const o = el('option', null, text); o.value = val; if (prefs.labels[def.id] === val) o.selected = true; sel.appendChild(o); } sel.onchange = () => { prefs.labels[def.id] = sel.value; saveContentPrefs(prefs).then(() => toast('Content filters updated')).catch((e) => toast('Save failed: ' + e.message)); }; row.appendChild(sel); cfSection.appendChild(row); } }).catch(() => { cfSection.textContent = ''; cfSection.appendChild(el('p', 'muted small', 'Could not load content filters.')); }); } const tabRow = el('div'); tabRow.style.cssText = 'display:flex;align-items:center;gap:0.5rem;padding:0.5rem 0.7rem'; tabRow.appendChild(el('span', 'muted small', 'Home opens on')); const sel = el('select'); sel.style.marginLeft = 'auto'; for (const [id, label] of [['boards', 'Boards'], ['asteri', 'Asteri'], ['topics', 'Topics'], ['following', 'Following'], ['feeds', 'Feeds']]) { const o = el('option', null, label); o.value = id; if (s.defaultTab === id) o.selected = true; sel.appendChild(o); } sel.onchange = () => { writeSetting('defaultTab', sel.value); try { localStorage.setItem('asteri:lastTab', sel.value); } catch { /* private mode */ } }; tabRow.appendChild(sel); menu.appendChild(tabRow); anchor.parentNode.style.position = 'relative'; anchor.parentNode.appendChild(menu); const onDown = (e) => { if (!menu.contains(e.target) && e.target !== anchor && !anchor.contains(e.target)) { menu.remove(); document.removeEventListener('mousedown', onDown); } }; document.addEventListener('mousedown', onDown); } function renderHeaderExtras() { const composeBtn = document.getElementById('composeBtn'); const bellSlot = document.getElementById('bellSlot'); const settingsBtn = document.getElementById('settingsBtn'); if (settingsBtn) { settingsBtn.hidden = false; settingsBtn.onclick = () => settingsPanel(settingsBtn); } const modLink = document.getElementById('modLink'); if (!composeBtn || !bellSlot) return; if (session) { composeBtn.hidden = false; composeBtn.onclick = () => composeChooser(composeBtn); bellSlot.appendChild(notificationBell()); if ((isAdmin() || isOzoneMod) && modLink) modLink.hidden = false; // Wide screens only (CSS keeps it hidden on mobile): account link ahead // of Members / Mod. const membersLink = document.getElementById('membersLink'); if (membersLink && !document.getElementById('profileLink')) { const pl = el('a', 'head-link profile-link', 'Account'); pl.id = 'profileLink'; pl.href = '#/user/' + myDid; profileOf(myDid).then((p) => { if (p?.handle) pl.textContent = '@' + p.handle; }); membersLink.parentNode.insertBefore(pl, membersLink); } } } // Banner and brand clicks land on the Boards home tab from anywhere. function goBoardsHome() { if ((location.hash || '#/') !== '#/') { location.hash = '#/'; return; } homeSelect?.('boards'); } function openCompose() { if ((location.hash || '#/') !== '#/') location.hash = '#/'; window.setTimeout(() => { homeSelect?.('boards'); window.dispatchEvent(new Event('asteri:compose')); }, 350); } function notificationBell() { const wrap = el('div', 'bell-wrap'); const btn = el('button', 'icon-btn'); btn.type = 'button'; btn.title = 'Notifications'; btn.setAttribute('aria-label', 'Notifications'); btn.setAttribute('aria-expanded', 'false'); btn.innerHTML = ''; const panel = el('div', 'notif-panel'); panel.hidden = true; panel.setAttribute('role', 'dialog'); panel.setAttribute('aria-label', 'Notifications'); let items = null; const renderPanel = () => { panel.textContent = ''; panel.appendChild(el('p', 'notif-head', 'Notifications')); if (!items) { panel.appendChild(el('p', 'muted small center', 'Loading…')); return; } if (!items.length) { panel.appendChild(el('p', 'muted small center', 'Replies to your posts and comments will appear here.')); return; } const ul = el('ul', 'notif-list'); for (const n of items) { const li = el('li'); const a = el('a', 'notif-item'); a.href = '#/post/' + n.postRkey; const line = el('p', 'notif-line'); line.appendChild(authorEl(n.authorDid)); line.appendChild(document.createTextNode(n.kind === 'reply-comment' ? ' replied to your comment' : ' replied to your post')); a.appendChild(line); if (n.postTitle) a.appendChild(el('p', 'notif-title', '“' + n.postTitle + '”')); a.appendChild(el('p', 'notif-text', n.text.replace(/<[^>]*>/g, '').slice(0, 120))); a.appendChild(el('p', 'notif-time', timeAgo(n.createdAt))); a.addEventListener('click', close); li.appendChild(a); ul.appendChild(li); } panel.appendChild(ul); }; const markSeen = () => { try { localStorage.setItem('asteri:notifSeen', new Date().toISOString()); } catch { /* private mode */ } wrap.querySelector('.badge')?.remove(); btn.classList.remove('bell-unread'); }; const onDown = (e) => { if (!wrap.contains(e.target)) close(); }; const onKey = (e) => { if (e.key === 'Escape') close(); }; function close() { panel.hidden = true; btn.setAttribute('aria-expanded', 'false'); document.removeEventListener('mousedown', onDown); document.removeEventListener('keydown', onKey); } btn.onclick = async () => { if (!panel.hidden) { close(); return; } panel.hidden = false; btn.setAttribute('aria-expanded', 'true'); document.addEventListener('mousedown', onDown); document.addEventListener('keydown', onKey); renderPanel(); if (!items) { try { items = (await getJSON('/notifications/' + myDid)).items ?? []; } catch { items = []; } renderPanel(); } markSeen(); }; getJSON('/notifications/' + myDid).then((data) => { const seen = localStorage.getItem('asteri:notifSeen') ?? ''; const unread = (data.items ?? []).filter((n) => n.createdAt > seen).length; if (unread > 0) { btn.appendChild(el('span', 'badge', unread > 9 ? '9+' : String(unread))); btn.classList.add('bell-unread'); } }).catch(() => {}); wrap.append(btn, panel); return wrap; } // ---------- repo writes (member's own PDS) ---------- async function repoWrite(method, body) { const res = await session.fetchHandler(myPds + '/xrpc/com.atproto.repo.' + method, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.message || data.error || `HTTP ${res.status}`); return data; } async function uploadBlob(file) { const res = await session.fetchHandler(myPds + '/xrpc/com.atproto.repo.uploadBlob', { method: 'POST', headers: { 'content-type': file.type }, body: file, }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.message || data.error || `Upload HTTP ${res.status}`); return data.blob; } // Re-encode to JPEG so saved/opened copies are always .jpg (quality 0.92). // GIFs keep their original bytes so animation survives. // Re-encode to JPEG under a byte ceiling: step quality down, then shrink // dimensions if quality alone can't get there. cap defaults to just under // the app.bsky image blob limit; boards media passes a larger one. // GIFs pass through untouched, but are rejected if over the cap. async function toJpeg(file, cap = 1_900_000) { if (file.type === 'image/gif') { if (file.size > cap) throw new Error(file.name + ' is over the upload limit (' + Math.round(cap / 1e6) + ' MB) — GIFs can\'t be recompressed.'); return file; } const img = await new Promise((res, rej) => { const i = new Image(); i.onload = () => res(i); i.onerror = rej; i.src = URL.createObjectURL(file); }); let scale = 1; let quality = 0.92; for (let attempt = 0; attempt < 8; attempt++) { const canvas = document.createElement('canvas'); canvas.width = Math.round(img.naturalWidth * scale); canvas.height = Math.round(img.naturalHeight * scale); canvas.getContext('2d').drawImage(img, 0, 0, canvas.width, canvas.height); const blob = await new Promise((res) => canvas.toBlob(res, 'image/jpeg', quality)); if (blob && blob.size <= cap) { URL.revokeObjectURL(img.src); return new File([blob], file.name.replace(/\.[^.]+$/, '') + '.jpg', { type: 'image/jpeg' }); } if (quality > 0.6) quality -= 0.1; else scale *= 0.85; } URL.revokeObjectURL(img.src); throw new Error('Could not compress ' + file.name + ' under ' + Math.round(cap / 1e6) + ' MB'); } // Breaks text into lines that fit maxWidth on the given 2d context. function wrapText(ctx, text, maxWidth) { const words = text.split(/\s+/); const lines = []; let cur = ''; for (const w of words) { const test = cur ? cur + ' ' + w : w; if (ctx.measureText(test).width > maxWidth && cur) { lines.push(cur); cur = w; } else cur = test; } if (cur) lines.push(cur); return lines; } // Draws a 1200x630 share card for a topic: board's planet color background, // the topic title (auto-shrinks/wraps up to 4 lines), board name, vote // count, and the sharer's handle. Returns a JPEG File ready for uploadBlob. async function topicCardImage(p, board, handle) { const W = 1200, H = 630; const canvas = document.createElement('canvas'); canvas.width = W; canvas.height = H; const ctx = canvas.getContext('2d'); ctx.fillStyle = board?.color || '#7ba3e8'; ctx.fillRect(0, 0, W, H); ctx.fillStyle = 'rgba(8, 15, 35, 0.55)'; ctx.fillRect(0, 0, W, H); ctx.fillStyle = 'rgba(255,255,255,0.85)'; ctx.font = '600 30px "Century Gothic", Futura, sans-serif'; ctx.textBaseline = 'alphabetic'; ctx.fillText((board?.name || 'Asteri').toUpperCase(), 60, 80); const maxWidth = W - 120; let fontSize = 72; let lines = []; const title = p.title || ''; while (fontSize > 32) { ctx.font = `700 ${fontSize}px "ITC Avant Garde Gothic LT", "Century Gothic", Futura, sans-serif`; lines = wrapText(ctx, title, maxWidth); if (lines.length <= 4) break; fontSize -= 4; } if (lines.length > 4) { lines = lines.slice(0, 4); lines[3] = lines[3].replace(/\s*\S*$/, '') + '…'; } ctx.fillStyle = '#ffffff'; ctx.font = `700 ${fontSize}px "ITC Avant Garde Gothic LT", "Century Gothic", Futura, sans-serif`; const lineHeight = fontSize * 1.18; const startY = H / 2 - ((lines.length - 1) * lineHeight) / 2 + fontSize * 0.3; lines.forEach((line, i) => ctx.fillText(line, 60, startY + i * lineHeight)); ctx.font = '600 28px "Century Gothic", Futura, sans-serif'; ctx.fillStyle = 'rgba(255,255,255,0.85)'; const votes = p.voteCount ?? 0; ctx.fillText(`${votes} ${votes === 1 ? 'point' : 'points'} · @${handle || 'asteri'}`, 60, H - 50); const blob = await new Promise((res) => canvas.toBlob(res, 'image/jpeg', 0.92)); return new File([blob], 'topic-card.jpg', { type: 'image/jpeg' }); } // "Share to Bluesky" button on a topic page: generates the planet-colored // card, then opens a small composer prefilled with the card image and a // link back to the topic, so sharing elsewhere carries a real preview. function shareToBlueskyButton(p, board) { if (!session) return null; const b = el('button', 'share-icon-btn'); b.type = 'button'; b.title = 'Share to Bluesky'; b.setAttribute('aria-label', 'Share to Bluesky'); b.innerHTML = ''; b.onclick = async () => { b.disabled = true; try { const prof = await profileOf(myDid); const file = await topicCardImage(p, board, prof?.handle); openShareComposer(p, file, board); } catch (err) { toast('Could not build share card: ' + err.message); } finally { b.disabled = false; } }; return b; } // Overlay composer for sharing a topic: fixed generated card image, editable // text, posts app.bsky.feed.post with an images embed and a link facet. function openShareComposer(p, file, board) { const ov = el('div', 'lightbox'); ov.setAttribute('role', 'dialog'); ov.setAttribute('aria-label', 'Share to Bluesky'); const panel = el('div', 'share-panel'); const close = el('button', 'thread-close', 'Close'); close.type = 'button'; close.onclick = () => ov.remove(); panel.appendChild(close); panel.appendChild(el('h2', null, 'Share to Bluesky')); const link = location.origin + '/p/' + p.rkey; const card = el('div', 'link-card'); card.style.cursor = 'default'; const img = el('img', 'link-card-image'); img.src = URL.createObjectURL(file); img.alt = ''; card.appendChild(img); const body = el('div', 'link-card-body'); const dom = domainOf(link); if (dom) body.appendChild(el('span', 'link-card-domain', dom)); body.appendChild(el('span', 'link-card-title', p.title)); body.appendChild(el('span', 'link-card-desc', board?.name ? board.name + ' · Asteri' : 'Asteri')); card.appendChild(body); panel.appendChild(card); const ta = el('textarea'); ta.rows = 3; ta.maxLength = 300; ta.placeholder = 'Add a comment (optional)'; const count = el('span', 'muted small', '0/300'); ta.oninput = () => { count.textContent = [...ta.value].length + '/300'; }; panel.append(el('label', null, 'Text'), ta, count); const send = el('button', 'primary', 'Post to Bluesky'); send.type = 'button'; send.style.margin = '1.1rem 0 0.4rem'; send.onclick = async () => { send.disabled = true; send.textContent = 'Posting…'; try { const text = ta.value.trim(); const blob = await uploadBlob(file); const record = { $type: 'app.bsky.feed.post', text, createdAt: new Date().toISOString(), embed: { $type: 'app.bsky.embed.external', external: { uri: link, title: p.title, description: board?.name ? board.name + ' · Asteri' : 'Asteri', thumb: blob, }, }, }; const facets = linkFacets(text); if (facets.length) record.facets = facets; await repoWrite('createRecord', { repo: myDid, collection: 'app.bsky.feed.post', record }); toast('Shared to Bluesky!'); ov.remove(); } catch (err) { toast('Share failed: ' + err.message); send.disabled = false; send.textContent = 'Post to Bluesky'; } }; panel.appendChild(send); ov.appendChild(panel); document.body.appendChild(ov); } function mediaPicker(max = 10) { const IMG_ICON = ''; const picks = []; const input = el('input'); input.type = 'file'; input.accept = 'image/png,image/jpeg,image/webp,image/gif,image/avif'; input.multiple = true; input.style.display = 'none'; const button = el('button', 'linklike', ''); button.type = 'button'; button.onclick = () => input.click(); const grid = el('div', 'pick-grid'); const render = () => { button.innerHTML = IMG_ICON + ' Images (' + picks.length + '/' + max + ')'; grid.textContent = ''; for (const [i, p] of picks.entries()) { const cell = el('div', 'pick-cell'); const th = el('img', 'pick-thumb'); th.alt = p.alt || p.file.name; th.src = URL.createObjectURL(p.file); const rm = el('button', 'pick-rm', '×'); rm.type = 'button'; rm.title = 'Remove ' + p.file.name; rm.onclick = () => { picks.splice(i, 1); render(); }; const alt = el('input', 'pick-alt'); alt.placeholder = 'Alt text'; alt.maxLength = 1000; alt.value = p.alt; alt.oninput = () => { p.alt = alt.value; }; cell.append(th, rm, alt); grid.appendChild(cell); } }; render(); input.onchange = () => { for (const f of [...input.files]) { if (picks.length >= max) { toast(`Up to ${max} images.`); break; } if (f.size > 50 * 1024 * 1024) { toast(f.name + ' is over 50 MB — skipped.'); continue; } picks.push({ file: f, alt: '' }); } input.value = ''; render(); }; const wrap = el('div'); wrap.append(input, button, grid); return { wrap, picks, button }; } async function loadMyVotes() { try { const data = await (await session.fetchHandler( myPds + '/xrpc/com.atproto.repo.listRecords?repo=' + myDid + '&collection=ca.astronomi.boards.vote&limit=100')).json(); for (const r of data.records ?? []) { if (r.value?.subject?.uri) myVotes.set(r.value.subject.uri, r.uri); } } catch { /* vote state just starts empty */ } } async function loadMyBallots() { try { const data = await (await session.fetchHandler( myPds + '/xrpc/com.atproto.repo.listRecords?repo=' + myDid + '&collection=ca.astronomi.boards.pollBallot&limit=100')).json(); for (const r of data.records ?? []) { if (r.value?.post?.uri) myBallots.set(r.value.post.uri, { uri: r.uri, option: r.value.option }); } } catch { /* ballot state just starts empty */ } } async function loadMyFollows() { try { const data = await (await session.fetchHandler( myPds + '/xrpc/com.atproto.repo.listRecords?repo=' + myDid + '&collection=ca.astronomi.boards.topicFollow&limit=100')).json(); for (const r of data.records ?? []) { if (r.value?.post?.uri) myFollows.set(r.value.post.uri, r.uri); } } catch { /* follow state just starts empty */ } } async function toggleVote(subjectUri, subjectCid) { const existing = myVotes.get(subjectUri); if (existing) { await repoWrite('deleteRecord', { repo: myDid, collection: 'ca.astronomi.boards.vote', rkey: rkeyOf(existing), }); myVotes.delete(subjectUri); toast('Vote withdrawn'); } else { const res = await repoWrite('createRecord', { repo: myDid, collection: 'ca.astronomi.boards.vote', record: { $type: 'ca.astronomi.boards.vote', subject: { uri: subjectUri, cid: subjectCid ?? '' }, createdAt: new Date().toISOString(), }, }); myVotes.set(subjectUri, res.uri); toast('Upvoted — it will appear as the index updates'); } } async function votePoll(post, option) { const mine = myBallots.get(post.uri); if (mine) { await repoWrite('deleteRecord', { repo: myDid, collection: 'ca.astronomi.boards.pollBallot', rkey: rkeyOf(mine.uri), }); myBallots.delete(post.uri); if (mine.option === option) { toast('Vote withdrawn'); return; } } const res = await repoWrite('createRecord', { repo: myDid, collection: 'ca.astronomi.boards.pollBallot', record: { $type: 'ca.astronomi.boards.pollBallot', post: { uri: post.uri, cid: post.cid ?? '' }, option, createdAt: new Date().toISOString(), }, }); myBallots.set(post.uri, { uri: res.uri, option }); toast('Vote counted — appearing as the index updates'); } async function toggleFollow(post) { const existing = myFollows.get(post.uri); if (existing) { await repoWrite('deleteRecord', { repo: myDid, collection: 'ca.astronomi.boards.topicFollow', rkey: rkeyOf(existing), }); myFollows.delete(post.uri); toast('Unfollowed topic'); } else { const res = await repoWrite('createRecord', { repo: myDid, collection: 'ca.astronomi.boards.topicFollow', record: { $type: 'ca.astronomi.boards.topicFollow', post: { uri: post.uri, cid: post.cid ?? '' }, createdAt: new Date().toISOString(), }, }); myFollows.set(post.uri, res.uri); toast('Following topic'); } } // Edit/delete own content: putRecord overwrites at the same rkey; deleteRecord // removes it. The indexer's firehose applies both within a second or two. async function deleteRecord(collection, uri, label) { if (!window.confirm(`Delete this ${label}? This removes the record from your repo.`)) return false; await repoWrite('deleteRecord', { repo: myDid, collection, rkey: rkeyOf(uri) }); toast(`${label} deleted`); return true; } // '✎ edited' marker shown when a record carries an updatedAt later than its // createdAt (the indexer passes updatedAt through from the record). function editedStamp(createdAt, updatedAt) { if (typeof updatedAt !== 'string' || typeof createdAt !== 'string' || updatedAt <= createdAt) return null; const s = el('span', 'edited', '✎ edited ' + timeAgo(updatedAt)); s.title = 'Edited ' + new Date(updatedAt).toLocaleString(); return s; } // Inline editor for your own topic or comment. Topics can also revise title // and tags. putRecord overwrites at the same rkey; updatedAt marks the edit. function editForm(uri, collection, current, label) { const form = el('form'); form.style.marginTop = '0.6rem'; const isTopic = label === 'topic'; let titleInput = null; let tags = null; if (isTopic) { titleInput = el('input'); titleInput.value = current.title ?? ''; titleInput.required = true; titleInput.maxLength = 150; titleInput.setAttribute('aria-label', 'Title'); tags = tagPicker(3, Array.isArray(current.tags) ? current.tags : []); form.append(el('label', null, 'Title'), titleInput, el('label', null, 'Text')); } const text = richEditor(isTopic ? 'Revise your post…' : 'Revise your comment…'); text.setHTML(typeof current.text === 'string' ? current.text : ''); form.appendChild(text.wrap); // Existing images: edit alt text or remove; attach new ones below. const existing = (Array.isArray(current.media) ? current.media : []) .filter((m) => m?.image?.ref?.$link) .map((m) => ({ blob: m.image, alt: m.alt ?? '' })); const mediaEd = el('div'); const renderMediaEd = () => { mediaEd.textContent = ''; if (!existing.length) return; mediaEd.appendChild(el('label', null, 'Images')); const grid = el('div', 'pick-grid'); for (const [i, m] of existing.entries()) { const cell = el('div', 'pick-cell'); cell.appendChild(blobImg(myDid, m.blob.ref.$link, m.alt, 'pick-thumb')); const rm = el('button', 'pick-rm', '×'); rm.type = 'button'; rm.title = 'Remove image'; rm.onclick = () => { existing.splice(i, 1); renderMediaEd(); }; const alt = el('input', 'pick-alt'); alt.placeholder = 'Alt text'; alt.maxLength = 1000; alt.value = m.alt; alt.oninput = () => { m.alt = alt.value; }; cell.append(rm, alt); grid.appendChild(cell); } mediaEd.appendChild(grid); }; renderMediaEd(); const addMedia = mediaPicker(isTopic ? 10 : 4); form.append(mediaEd, addMedia.wrap); if (isTopic) form.append(el('label', null, 'Tags (up to 3)'), tags.wrap); const row = el('div', 'form-row'); const save = el('button', 'primary', 'Save changes'); save.type = 'submit'; const cancel = el('button', null, 'Cancel'); cancel.type = 'button'; cancel.onclick = () => form.remove(); row.append(save, cancel); form.appendChild(row); form.onsubmit = async (e) => { e.preventDefault(); save.disabled = true; try { const res = await session.fetchHandler( myPds + '/xrpc/com.atproto.repo.getRecord?repo=' + myDid + '&collection=' + collection + '&rkey=' + rkeyOf(uri)); const cur = await res.json(); if (!res.ok) throw new Error(cur.message || 'Could not read your record'); const record = { ...cur.value, updatedAt: new Date().toISOString() }; const html = text.getHTML(); if (isTopic) { const title = titleInput.value.trim(); if (!title) throw new Error('A title is required'); record.title = title; if (html) record.text = html; else delete record.text; const picks = tags.getTags(); if (picks.length) record.tags = picks; else delete record.tags; } else { if (!html) throw new Error('Text can\'t be empty — delete instead.'); record.text = html; } if (addMedia.picks.length) { save.textContent = 'Uploading images…'; for (const p of addMedia.picks) { const blob = await uploadBlob(await toJpeg(p.file, 9_500_000)); existing.push({ blob, alt: p.alt.trim() || p.file.name }); } save.textContent = 'Save changes'; } if (existing.length) record.media = existing.map((m) => ({ image: m.blob, alt: m.alt })); else delete record.media; await repoWrite('putRecord', { repo: myDid, collection, rkey: rkeyOf(uri), record }); toast(label + ' updated — appearing as the index updates'); window.setTimeout(route, 1500); } catch (err) { toast('Edit failed: ' + err.message); save.disabled = false; } }; return form; } function ownerTools(uri, collection, current, label) { if (!session || !uri.includes('/' + myDid + '/')) return null; const wrap = el('span', 'toolpair'); const editB = el('button', 'linklike', 'Edit'); editB.onclick = (e) => { e.preventDefault(); e.stopPropagation(); const card = wrap.closest('.card'); if (!card || card.querySelector('form')) return; card.appendChild(editForm(uri, collection, current, label)); }; const delB = el('button', 'linklike', 'Delete'); delB.style.color = 'var(--danger)'; delB.onclick = async (e) => { e.preventDefault(); e.stopPropagation(); delB.disabled = true; try { if (await deleteRecord(collection, uri, label)) { // A deleted topic's page is gone — go back to its board; a deleted // comment just refreshes the thread. if (label === 'topic') location.hash = '#/boards/' + (current?.board ?? 'sophia'); else window.setTimeout(route, 1500); } else { delB.disabled = false; } } catch (err) { toast('Delete failed: ' + err.message); delB.disabled = false; } }; wrap.append(editB, delB); return wrap; } // Report a post/comment to the Ozone moderation service. Proxied through the // member's own PDS via the rpc:createReport?aud=...atproto_labeler scope — // the PDS signs and forwards it, no direct call to Ozone from the browser. const REPORT_REASONS = [ ['com.atproto.moderation.defs#reasonSpam', 'Spam'], ['com.atproto.moderation.defs#reasonViolation', 'Rule violation'], ['com.atproto.moderation.defs#reasonMisleading', 'Misleading'], ['com.atproto.moderation.defs#reasonSexual', 'Unwanted sexual content'], ['com.atproto.moderation.defs#reasonRude', 'Rude / harassing'], ['com.atproto.moderation.defs#reasonOther', 'Other'], ]; async function submitReport(uri, cid, reasonType, reason) { const res = await session.fetchHandler(myPds + '/xrpc/com.atproto.moderation.createReport', { method: 'POST', headers: { 'content-type': 'application/json', 'atproto-proxy': LABELER_DID + '#atproto_labeler', }, body: JSON.stringify({ reasonType, reason: reason || undefined, subject: { $type: 'com.atproto.repo.strongRef', uri, cid }, }), }); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.message || data.error || `HTTP ${res.status}`); return data; } function reportTools(uri, cid, label) { if (!session) return null; const wrap = el('span', 'toolpair'); const btn = el('button', 'linklike', 'Report'); btn.onclick = (e) => { e.preventDefault(); e.stopPropagation(); const card = wrap.closest('.card'); if (!card || card.querySelector('.report-form')) return; const form = el('div', 'report-form'); form.style.cssText = 'margin-top:0.5rem; display:flex; flex-direction:column; gap:0.4rem;'; const select = el('select'); for (const [val, text] of REPORT_REASONS) { const opt = el('option', null, text); opt.value = val; select.appendChild(opt); } const note = el('input'); note.type = 'text'; note.placeholder = 'Additional details (optional)'; note.maxLength = 300; const row = el('div'); row.style.cssText = 'display:flex; gap:0.4rem;'; const send = el('button', null, 'Submit report'); const cancel = el('button', 'linklike', 'Cancel'); cancel.onclick = (ev) => { ev.preventDefault(); form.remove(); }; send.onclick = async (ev) => { ev.preventDefault(); send.disabled = true; try { await submitReport(uri, cid, select.value, note.value.trim()); toast(`${label} reported — thank you`); form.remove(); } catch (err) { toast('Report failed: ' + err.message); send.disabled = false; } }; row.append(send, cancel); form.append(select, note, row); card.appendChild(form); }; wrap.appendChild(btn); return wrap; } function voteButton(subjectUri, subjectCid, count) { const b = el('button', 'vote', '▲'); const voted = myVotes.has(subjectUri); b.setAttribute('aria-pressed', voted ? 'true' : 'false'); b.setAttribute('aria-label', voted ? 'Remove your upvote' : 'Upvote'); b.title = !session ? 'Sign in to vote' : voted ? 'Remove upvote' : `Upvote (${count} ${count === 1 ? 'point' : 'points'})`; if (!session) { b.disabled = true; return b; } b.onclick = async (e) => { e.preventDefault(); e.stopPropagation(); b.disabled = true; try { await toggleVote(subjectUri, subjectCid); window.setTimeout(route, 1500); } catch (err) { toast('Vote failed: ' + err.message); b.disabled = false; } }; return b; } function followButton(p) { const following = myFollows.has(p.uri); const b = el('button', null, following ? '✓ Following' : 'Follow topic'); b.setAttribute('aria-pressed', following ? 'true' : 'false'); if (following) b.style.cssText = 'border-color:var(--gold);color:var(--gold);'; b.onclick = async () => { b.disabled = true; try { await toggleFollow(p); window.setTimeout(route, 1500); } catch (e) { toast('Follow failed: ' + e.message); b.disabled = false; } }; return b; } // ---------- views ---------- function errorCard(msg) { const box = el('div', 'error-box', msg + ' '); const retry = el('button', null, 'Retry'); retry.onclick = route; box.appendChild(retry); return box; } function viewError(msg) { app.textContent = ''; app.appendChild(errorCard(msg)); } // ---------- home: tab bar + Asteri feed + boards + topics table + media ---------- function boardChip(slug) { const board = BOARDS.find((b) => b.slug === slug); const a = el('a', 'tag', board?.name ?? slug); a.href = '#/boards/' + slug; return a; } const SPACE_ICONS = { lock: '', pds: '', forum: '', }; const MEMBERS_ICON = ''; function membersCard() { const card = el('a', 'card space-card', null); card.href = '#/members'; card.style.cursor = 'pointer'; const ic = el('span', 'space-icon'); ic.innerHTML = MEMBERS_ICON; ic.setAttribute('aria-hidden', 'true'); const body = el('div', 'space-body'); body.appendChild(el('p', 'space-name', 'Members')); body.appendChild(el('p', 'muted small', 'Everyone who has posted on Asteri.')); card.append(ic, body); return card; } function spacesPanel() { const section = el('section', 'spaces'); section.setAttribute('aria-label', 'Spaces'); const head = el('div', 'spaces-head'); head.appendChild(el('h2', null, 'Spaces')); head.appendChild(el('span', 'muted small', 'ATProto Spaces begin shipping December 1st')); section.appendChild(head); const kinds = [ ['lock', 'Private Spaces', 'Invite-only spaces. Only invited members can read or post.'], ['pds', 'PDS Spaces', 'Spaces stored on your own PDS.'], ['forum', 'Forum Spaces', 'Private boards on Asteri for members to chat and discuss.'], ]; for (const [icon, name, text] of kinds) { const card = el('div', 'card frosted space-card'); const ic = el('span', 'space-icon'); ic.innerHTML = SPACE_ICONS[icon]; ic.setAttribute('aria-hidden', 'true'); const body = el('div', 'space-body'); body.appendChild(el('p', 'space-name', name)); body.appendChild(el('p', 'muted small', text)); card.append(ic, body, el('span', 'tag', 'Dec 1')); section.appendChild(card); } return section; } // Small back pill; boards-head puts it left, level with the submit button. function homeBack(onClick, label = '← Home') { const b = el('button', 'backpill', label); b.type = 'button'; b.onclick = onClick; return b; } // Board descriptions: "Best tags:" starts its own line. function boardDesc(text, cls) { const d = el('div', cls); const i = text.indexOf('Best tags:'); if (i === -1) { d.textContent = text; return d; } d.append(document.createTextNode(text.slice(0, i).trim()), el('br'), document.createTextNode(text.slice(i))); return d; } // Floating "back to top + refresh" for the feed tabs: fixed at the left edge, // a bold Neptune-blue caret in a Mercury-silver ring. Clicking scrolls home // and re-runs the current tab so the feed refreshes. function feedTopButton(onRefresh) { const b = el('button', 'feed-top', '^'); b.type = 'button'; b.title = 'Back to top and refresh'; b.setAttribute('aria-label', 'Back to top and refresh'); b.onclick = () => { window.scrollTo({ top: 0, behavior: 'smooth' }); onRefresh?.(); }; return b; } async function renderBoardsTab(box) { const head = el('div', 'boards-head'); const titleWrap = el('div'); titleWrap.appendChild(el('h1', null, 'Boards')); head.appendChild(titleWrap); composeOpener = null; if (session) { const toggle = el('button', 'primary', 'New Boards post'); toggle.setAttribute('aria-expanded', 'false'); const slot = el('div'); const setOpen = (openIt) => { slot.textContent = ''; if (openIt) slot.appendChild(composeForm('sophia')); toggle.textContent = openIt ? 'Cancel' : 'Submit a post'; toggle.setAttribute('aria-expanded', String(openIt)); }; toggle.onclick = () => setOpen(!slot.firstChild); composeOpener = () => setOpen(true); head.appendChild(toggle); box.appendChild(head); box.appendChild(slot); } else { box.appendChild(head); } let data; try { data = await getJSON('/boards'); } catch (e) { box.appendChild(errorCard('Could not load boards: ' + e.message)); return; } const stats = new Map((data.boards ?? []).map((b) => [b.board, b])); for (const b of BOARDS) { const s = stats.get(b.slug); const a = el('a', 'card frosted'); a.href = '#/boards/' + b.slug; const row = el('div', 'board-row'); const left = el('div'); const name = el('span', 'board-name', b.name); const theme = el('span', 'board-theme', '| ' + b.theme); theme.style.color = b.color; left.append(name, theme); if (b.description) left.appendChild(boardDesc(b.description, 'muted small')); left.appendChild(el('div', 'board-stats', s ? `Activity ${timeAgo(s.last)} · ${s.topics} ${s.topics === 1 ? 'topic' : 'topics'}` : 'No activity')); row.append(left, el('span', 'muted', '→')); a.appendChild(row); box.appendChild(a); } } // The Asteri tab: "what's new since your last visit", then the Spaces preview. // Read-state for the Asteri catch-up tab: topics you've opened are marked // read; the tab shows what's still unread, and Clear all marks everything. const READ_KEY = 'asteri:readTopics'; function readSet() { try { return new Set(JSON.parse(localStorage.getItem(READ_KEY) ?? '[]')); } catch { return new Set(); } } function markRead(uri) { const s = readSet(); if (s.has(uri)) return; s.add(uri); try { localStorage.setItem(READ_KEY, JSON.stringify([...s].slice(-2000))); } catch { /* private mode */ } } function clearAllRead(uris) { const s = readSet(); for (const u of uris) s.add(u); try { localStorage.setItem(READ_KEY, JSON.stringify([...s].slice(-2000))); } catch { /* private mode */ } } // The Asteri tab: unread topics ("catch-up"), a Clear all, then the topics // you follow, with the Spaces preview at the bottom. async function renderAsteriTab(box, select) { box.appendChild(el('p', 'muted center pad', 'Loading…')); let posts; try { posts = await loadAllPosts(); } catch (e) { box.textContent = ''; box.appendChild(errorCard('Could not load the forum feed: ' + e.message)); return; } box.textContent = ''; const read = readSet(); const sorted = sortPosts(posts, 'new'); const fresh = sorted.filter((p) => !read.has(p.uri)); const followed = sorted.filter((p) => myFollows.has(p.uri)); if (fresh.length === 0) { const card = el('div', 'card center pad'); card.appendChild(el('p', 'empty-title', 'All caught up')); card.appendChild(el('p', 'muted small', 'Nothing new to read — topics you open drop off this list.')); const browse = el('button', 'textlink', 'Browse the full topic index →'); browse.onclick = () => select('topics'); card.appendChild(browse); box.appendChild(card); } else { const head = el('div', 'form-row'); head.style.marginTop = '0'; head.appendChild(el('p', 'muted small', `${fresh.length} unread ${fresh.length === 1 ? 'topic' : 'topics'}`)); const clear = el('button', 'linklike', 'Clear all'); clear.style.marginLeft = 'auto'; clear.onclick = () => { clearAllRead(sorted.map((p) => p.uri)); box.textContent = ''; renderAsteriTab(box, select); }; head.appendChild(clear); box.appendChild(head); for (const p of fresh) { if (!forumProfiles.has(p.authorDid)) loadForumProfile(p.authorDid); box.appendChild(postCard(p)); } } if (followed.length) { box.appendChild(el('h2', null, 'Followed topics')); for (const p of followed) { if (!forumProfiles.has(p.authorDid)) loadForumProfile(p.authorDid); box.appendChild(postCard(p)); } } box.appendChild(spacesPanel()); const membersSection = el('section', 'spaces'); membersSection.setAttribute('aria-label', 'Members'); membersSection.appendChild(el('h2', null, 'Members')); membersSection.appendChild(membersCard()); box.appendChild(membersSection); } async function renderTopicsTab(box) { box.appendChild(el('h1', null, 'All Topics')); box.appendChild(el('p', 'muted', 'Every thread, with its latest activity.')); const sform = el('form', 'searchform'); const sq = el('input'); sq.type = 'search'; sq.placeholder = 'Search the forum…'; sq.setAttribute('aria-label', 'Search the forum'); const sgo = el('button', null, 'Search'); sgo.type = 'submit'; sform.append(sq, sgo); sform.onsubmit = (e) => { e.preventDefault(); const q2 = sq.value.trim(); if (q2.length >= 2) location.hash = '#/search/' + encodeURIComponent(q2); }; box.appendChild(sform); const activeTags = new Set(); const tagBar = el('div', 'meta board-tagbar'); const tableWrap = el('div'); let lastRows = []; let sortKey = 'activity'; let dir = 'desc'; const renderTable = () => { tableWrap.textContent = ''; const shown = activeTags.size === 0 ? lastRows : lastRows.filter((p) => (p.tags ?? []).some((t) => activeTags.has(t))); if (!shown.length) { tableWrap.appendChild(el('p', 'muted center pad', lastRows.length ? 'No topics match those tags.' : 'No topics yet.')); return; } const val = (p) => sortKey === 'replies' ? (p.commentCount ?? 0) : sortKey === 'top' ? (p.voteCount ?? 0) : +new Date(p.activity ?? p.createdAt); const arr = [...shown].sort((a, b) => val(a) - val(b)); if (dir === 'desc') arr.reverse(); const wrap = el('div', 'topics-wrap'); const table = el('table', 'topics-table'); const thead = el('thead'); const hr = el('tr'); hr.appendChild(el('th', null, 'Topic')); hr.appendChild(el('th', null, 'Category')); hr.appendChild(el('th', null, 'Author')); for (const k of ['replies', 'top', 'activity']) { const th = el('th', 'num'); const b = el('button', 'linklike', (k === 'replies' ? 'Replies' : k === 'top' ? 'Top' : 'Activity') + (sortKey === k ? (dir === 'desc' ? ' ↓' : ' ↑') : '')); b.setAttribute('aria-label', `Sort by ${k}`); b.onclick = () => { if (sortKey === k) dir = dir === 'desc' ? 'asc' : 'desc'; else { sortKey = k; dir = 'desc'; } renderTable(); }; th.appendChild(b); hr.appendChild(th); } thead.appendChild(hr); table.appendChild(thead); const tbody = el('tbody'); for (const p of arr) { const tr = el('tr'); const tdT = el('td'); const a = el('a', 'topic-link', p.title); a.href = '#/post/' + p.rkey; a.style.color = boardColor(p.board); tdT.appendChild(a); if (p.pollOptions || (p.tags && p.tags.length)) { const pills = el('div', 'meta'); if (p.pollOptions) pills.appendChild(el('span', 'tag', 'Poll')); for (const t of p.tags ?? []) pills.appendChild(el('span', 'tag', t)); tdT.appendChild(pills); } const tdB = el('td'); tdB.appendChild(boardChip(p.board)); const tdA = el('td'); tdA.appendChild(authorEl(p.authorDid, p.authorFlairText, p.authorFlairColor)); const tdR = el('td', 'num gold', String(p.commentCount ?? 0)); const tdAct = el('td', 'num muted-cell', timeAgo(p.activity ?? p.createdAt)); tr.append(tdT, tdB, tdA, tdR, tdAct); tbody.appendChild(tr); } table.appendChild(tbody); wrap.appendChild(table); tableWrap.appendChild(wrap); }; for (const t of POST_TAGS) { const b = el('button', 'tag', t); b.type = 'button'; b.setAttribute('aria-pressed', 'false'); b.onclick = () => { if (activeTags.has(t)) { activeTags.delete(t); b.setAttribute('aria-pressed', 'false'); b.style.cssText = ''; } else { activeTags.add(t); b.setAttribute('aria-pressed', 'true'); b.style.cssText = 'color:var(--heading);border-color:var(--dim);background:rgba(159,191,224,0.12)'; } renderTable(); }; tagBar.appendChild(b); } const clear = el('button', 'linklike', 'Clear'); clear.onclick = () => { activeTags.clear(); for (const chip of tagBar.querySelectorAll('button.tag')) { chip.setAttribute('aria-pressed', 'false'); chip.style.cssText = ''; } renderTable(); }; tagBar.appendChild(clear); box.append(tagBar, tableWrap); tableWrap.appendChild(el('p', 'muted center pad', 'Loading…')); try { lastRows = await loadAllPosts(); } catch (e) { tableWrap.textContent = ''; tableWrap.appendChild(errorCard('Could not load the topic index: ' + e.message)); return; } renderTable(); } async function renderMediaInto(box) { box.appendChild(el('p', 'muted center pad', 'Loading…')); let data; try { data = await getJSON('/media'); } catch (e) { box.textContent = ''; box.appendChild(errorCard('Could not load media: ' + e.message)); return; } box.textContent = ''; if (!data.items?.length) { box.appendChild(el('p', 'muted center pad', 'No images yet — attach one to a topic.')); return; } const grid = el('div', 'media-grid'); for (const m of data.items) { const a = el('a'); a.href = '#/post/' + m.postRkey; a.title = m.title; if (m.src) { const img = el('img', 'media-cell'); img.src = m.src; img.alt = m.alt; img.loading = 'lazy'; a.appendChild(img); } else { a.appendChild(blobImg(m.authorDid, m.cid, m.alt, 'media-cell')); } grid.appendChild(a); } box.appendChild(grid); } async function viewHome(initialTab) { app.textContent = ''; document.title = 'Asteri — Boards of Astronomica'; let tab = 'boards'; if (initialTab && (ALL_HOME.some(([id]) => id === initialTab) || initialTab.startsWith('tab:'))) { tab = initialTab; try { localStorage.setItem('asteri:lastTab', tab); } catch { /* private mode */ } } else { try { const t = localStorage.getItem('asteri:lastTab') ?? 'boards'; if (ALL_HOME.some(([id]) => id === t) || t.startsWith('tab:')) tab = t; } catch { /* default tab */ } } const bar = el('div', 'tabbar'); bar.setAttribute('role', 'group'); bar.setAttribute('aria-label', 'Feed tabs'); const content = el('div'); const renderBar = () => { bar.textContent = ''; const mk = (id, label, i) => { const c = TAB_COLORS[i % TAB_COLORS.length]; const b = el('button', null, label); b.setAttribute('aria-pressed', tab === id ? 'true' : 'false'); b.style.cssText = tab === id ? `background:${c};color:#04143d;` : `color:${c};`; b.onclick = () => select(id); return b; }; const left = el('span', 'tabbar-left'); HOME_LEFT.forEach(([id, label], i) => left.appendChild(mk(id, label, i))); const center = el('span', 'tabbar-center'); HOME_CENTER.forEach(([id, label], i) => center.appendChild(mk(id, label, HOME_LEFT.length + i))); const right = el('span', 'tabbar-right'); const rightTabs = [...HOME_RIGHT, ...feedTabsRead().map((t) => [`tab:${t.id}`, t.name])]; rightTabs.forEach(([id, label], i) => right.appendChild(mk(id, label, HOME_LEFT.length + 1 + i))); const plus = el('button', 'tab-plus', '+'); plus.title = 'Add a feed from Browse feeds'; plus.setAttribute('aria-label', 'Add a feed from Browse feeds'); plus.onclick = () => { location.hash = '#/feeds'; }; right.appendChild(plus); bar.append(left, center, right); if (session) { // A solid sun at the left end — your profile. const sun = el('a', 'tab-sun', '●'); sun.href = '#/user/' + myDid; sun.title = 'Your profile'; sun.setAttribute('aria-label', 'Your profile'); bar.prepend(sun); } }; const select = (id) => { tab = id; try { localStorage.setItem('asteri:lastTab', id); } catch { /* private mode */ } renderBar(); renderTab(); }; const renderTab = () => { content.textContent = ''; if (tab === 'boards') renderBoardsTab(content); else if (tab === 'asteri') renderAsteriTab(content, select); else if (tab === 'members') renderMembersInto(content); else if (tab === 'topics') renderTopicsTab(content); else if (tab === 'spaces') renderSpacesTab(content); else if (tab === 'lists') renderListsInto(content); else if (tab === 'following') { content.appendChild(homeBack(() => select('boards'))); const t = bskyComposeToggle(); if (t) content.appendChild(t); const slot = el('div'); content.appendChild(slot); renderFollowingInto(slot); content.appendChild(feedTopButton(() => select(tab))); } else if (tab === 'feeds') { content.appendChild(homeBack(() => select('boards'))); const t = bskyComposeToggle(); if (t) content.appendChild(t); const slot = el('div'); content.appendChild(slot); renderFeedsAggregate(slot); content.appendChild(feedTopButton(() => select(tab))); } else if (tab.startsWith('tab:')) { content.appendChild(homeBack(() => select('boards'))); renderCustomTab(content, tab.slice(4), select); content.appendChild(feedTopButton(() => select(tab))); } }; renderBar(); app.append(bar, content); renderTab(); homeSelect = select; } function sortPosts(posts, mode) { const arr = [...posts]; if (mode === 'top') arr.sort((a, b) => (b.voteCount - a.voteCount) || (+new Date(b.createdAt) - +new Date(a.createdAt))); else if (mode === 'hot') { const now = Date.now(); const score = (p) => (p.voteCount ?? 0) / Math.pow(Math.max(0, (now - +new Date(p.createdAt)) / 3_600_000) + 2, 1.8); arr.sort((a, b) => score(b) - score(a)); } else arr.sort((a, b) => +new Date(b.createdAt) - +new Date(a.createdAt)); return arr; } async function viewBoard(slug, sort = 'new') { const board = BOARDS.find((b) => b.slug === slug) ?? { slug, name: slug, theme: '', color: '#e6ebf1' }; app.textContent = ''; app.appendChild(navTabBar('boards')); const h = el('h1', null, board.name); if (board.theme) { const t = el('span', 'board-theme', ' | ' + board.theme); t.style.color = board.color; h.appendChild(t); } // Header row mirrors the Boards page: title + description left, submit right, // Tab bar for board pages: same pills as home; clicking a tab goes home with // that tab selected (viewHome reads asteri:lastTab on load). function navTabBar(activeId) { const bar = el('div', 'tabbar'); bar.setAttribute('role', 'group'); bar.setAttribute('aria-label', 'Feed tabs'); const mk = (id, label, i) => { const c = TAB_COLORS[i % TAB_COLORS.length]; const b = el('button', null, label); b.setAttribute('aria-pressed', activeId === id ? 'true' : 'false'); b.style.cssText = activeId === id ? `background:${c};color:#04143d;` : `color:${c};`; b.onclick = () => { try { localStorage.setItem('asteri:lastTab', id); } catch { /* private mode */ } location.hash = '#/'; }; return b; }; const left = el('span', 'tabbar-left'); HOME_LEFT.forEach(([id, label], i) => left.appendChild(mk(id, label, i))); const center = el('span', 'tabbar-center'); HOME_CENTER.forEach(([id, label], i) => center.appendChild(mk(id, label, HOME_LEFT.length + i))); const right = el('span', 'tabbar-right'); const rightTabs = [...HOME_RIGHT, ...feedTabsRead().map((t) => [`tab:${t.id}`, t.name])]; rightTabs.forEach(([id, label], i) => right.appendChild(mk(id, label, HOME_LEFT.length + 1 + i))); const plus = el('button', 'tab-plus', '+'); plus.title = 'Add a feed from Browse feeds'; plus.setAttribute('aria-label', 'Add a feed from Browse feeds'); plus.onclick = () => { location.hash = '#/feeds'; }; right.appendChild(plus); bar.append(left, center, right); if (session) { const sun = el('a', 'tab-sun', '●'); sun.href = '#/user/' + myDid; sun.title = 'Your profile'; sun.setAttribute('aria-label', 'Your profile'); bar.prepend(sun); } return bar; } // so the button lands directly above the hot/new/top sort pill. const head = el('div', 'boards-head'); head.prepend(homeBack(goBoardsHome)) const titleWrap = el('div'); const titleRow = el('div', 'board-title-row'); titleRow.appendChild(shareIconButton('/b/' + slug, 'Copy board link')); titleRow.appendChild(h); titleWrap.appendChild(titleRow); if (board.description) titleWrap.appendChild(boardDesc(board.description, 'muted')); head.appendChild(titleWrap); if (session) { const toggle = el('button', 'primary', 'New Boards post'); toggle.setAttribute('aria-expanded', 'false'); const slot = el('div'); toggle.onclick = () => { const showing = !!slot.firstChild; slot.textContent = ''; if (!showing) slot.appendChild(composeForm(slug)); toggle.textContent = showing ? 'Submit a post' : 'Cancel'; toggle.setAttribute('aria-expanded', String(!showing)); }; head.appendChild(toggle); app.appendChild(head); app.appendChild(slot); } else { app.appendChild(head); app.appendChild(el('p', 'muted small', 'Sign in (top right) to post, comment, and vote.')); } // Sort is a segmented control at the right end of the tag row, like the // hosted Site's hot/new/top pill. const sortSeg = el('div', 'sortseg'); sortSeg.setAttribute('role', 'group'); sortSeg.setAttribute('aria-label', 'Sort posts'); for (const mode of ['hot', 'new', 'top']) { const b = el('button', null, mode); b.style.textTransform = 'capitalize'; b.setAttribute('aria-pressed', mode === sort ? 'true' : 'false'); if (mode === sort) b.classList.add('seg-on'); b.onclick = () => viewBoard(slug, mode); sortSeg.appendChild(b); } // Tag filter chips: click to include, click again to clear. Filtering is // client-side over the already-fetched board listing. const activeTags = new Set(); const tagBar = el('div', 'meta board-tagbar'); tagBar.style.gap = '0.4rem'; const listWrap = el('div'); let lastPosts = []; const renderList = (posts) => { listWrap.textContent = ''; const shown = activeTags.size === 0 ? posts : posts.filter((p) => (p.tags ?? []).some((t) => activeTags.has(t))); if (!shown.length) { listWrap.appendChild(el('p', 'muted center pad', 'No topics match those tags.')); return; } for (const p of shown) { if (!forumProfiles.has(p.authorDid)) loadForumProfile(p.authorDid); listWrap.appendChild(postCard(p)); } }; for (const t of POST_TAGS) { const b = el('button', 'tag', t); b.type = 'button'; b.setAttribute('aria-pressed', 'false'); b.onclick = () => { if (activeTags.has(t)) { activeTags.delete(t); b.setAttribute('aria-pressed', 'false'); b.style.cssText = ''; } else { activeTags.add(t); b.setAttribute('aria-pressed', 'true'); b.style.cssText = 'color:var(--heading);border-color:var(--dim);background:rgba(159,191,224,0.12)'; } renderList(lastPosts); }; tagBar.appendChild(b); } tagBar.appendChild(sortSeg); app.appendChild(tagBar); let data; try { data = await getJSON('/boards/' + slug + '/posts'); } catch (e) { return viewError('Could not load this board: ' + e.message); } document.title = board.name + ' — Asteri'; if (!data.posts?.length) { app.appendChild(el('p', 'muted center pad', 'No topics yet — be the first.')); return; } lastPosts = sortPosts(data.posts, sort); renderList(lastPosts); app.appendChild(listWrap); } async function loadForumProfile(did) { try { const data = await getJSON('/members/' + did); forumProfiles.set(did, data.profile ?? null); } catch { forumProfiles.set(did, null); } } // Feed row, matching the hosted Site: vote pill, cream title link, icy domain, // then the meta line. The row itself isn't a link — the title is. // A board's flair color, for titles and accents. function boardColor(slug) { return BOARDS.find((b) => b.slug === slug)?.color ?? '#e6ebf1'; } function postCard(p) { const li = el('div', 'card post-row'); const top = el('div', 'post-row-top'); top.appendChild(voteButton(p.uri, p.cid, p.voteCount ?? 0)); const a = el('a', 'post-title-link', p.title); a.style.color = boardColor(p.board); a.href = '#/post/' + p.rkey; a.style.color = boardColor(p.board); top.appendChild(a); if (p.url) { try { const d = el('a', 'domain-link', '(' + new URL(p.url).hostname + ')'); d.href = p.url; d.target = '_blank'; d.rel = 'noopener noreferrer'; top.appendChild(d); } catch { /* ignore bad urls */ } } li.appendChild(top); const meta = el('div', 'meta'); meta.appendChild(boardChip(p.board)); if (p.pollOptions) meta.appendChild(el('span', 'tag', 'Poll')); for (const t of p.tags ?? []) meta.appendChild(el('span', 'tag', t)); const pChips = labelChips(p.labels); if (pChips) meta.appendChild(pChips); meta.appendChild(el('span', 'points', `${p.voteCount ?? 0} ${p.voteCount === 1 ? 'point' : 'points'}`)); meta.appendChild(el('span', null, 'by ')); meta.appendChild(authorEl(p.authorDid, p.authorFlairText, p.authorFlairColor)); meta.appendChild(el('span', null, timeAgo(p.createdAt))); const pEdited = editedStamp(p.createdAt, p.updatedAt); if (pEdited) meta.appendChild(pEdited); const cLink = el('a', 'post-title-link', `${p.commentCount ?? 0} ${p.commentCount === 1 ? 'comment' : 'comments'}`); cLink.href = '#/post/' + p.rkey; meta.appendChild(cLink); li.appendChild(meta); return li; } async function viewPost(rkey, commentRkey) { currentPostBoard = null; app.textContent = ''; app.appendChild(el('p', 'muted center pad', 'Loading topic…')); let data; try { data = await getJSON('/posts/' + rkey); } catch (e) { return viewError('Could not load this topic: ' + e.message); } const p = data.post; if (!p) { const box = el('div', 'error-box', 'This topic isn\'t here — it may have been deleted, or it\'s still arriving from the network. '); const back = el('button', null, '← Boards'); back.onclick = () => { goBoardsHome(); }; const retry = el('button', null, 'Retry'); retry.onclick = route; box.append(back, retry); app.textContent = ''; app.appendChild(box); return; } document.title = p.title + ' — Asteri'; currentPostBoard = p.board; markRead(p.uri); app.textContent = ''; const back = el('a', 'backbar', '← ' + (BOARDS.find((b) => b.slug === p.board)?.name ?? p.board)); back.href = '#/boards/' + p.board; app.appendChild(back); const card = el('div', 'card'); card.style.marginTop = '0.6rem'; const titleRow = el('div', 'title-row'); titleRow.appendChild(shareIconButton('/p/' + p.rkey, 'Copy post link')); const shareBtn = shareToBlueskyButton(p, BOARDS.find((b) => b.slug === p.board)); if (shareBtn) titleRow.appendChild(shareBtn); titleRow.appendChild(el('h1', null, p.title)); card.appendChild(titleRow); const meta = el('div', 'meta'); meta.appendChild(voteButton(p.uri, p.cid, p.voteCount ?? 0)); meta.appendChild(boardChip(p.board)); if (p.pollOptions) meta.appendChild(el('span', 'tag', 'Poll')); for (const t of p.tags ?? []) meta.appendChild(el('span', 'tag', t)); const pChips2 = labelChips(p.labels); if (pChips2) meta.appendChild(pChips2); meta.appendChild(el('span', 'points', `${p.voteCount ?? 0} ${p.voteCount === 1 ? 'point' : 'points'}`)); meta.appendChild(el('span', null, 'by ')); meta.appendChild(authorEl(p.authorDid, p.authorFlairText, p.authorFlairColor)); meta.appendChild(el('span', null, timeAgo(p.createdAt))); const postEdited = editedStamp(p.createdAt, p.updatedAt); if (postEdited) meta.appendChild(postEdited); const tools = ownerTools(p.uri, 'ca.astronomi.boards.post', p, 'topic'); if (tools) meta.appendChild(tools); const mt = modTools(p.uri, 'post', 'topic', p.board); if (mt) meta.appendChild(mt); const rt = reportTools(p.uri, p.cid, 'Topic'); if (rt) meta.appendChild(rt); const ot = ozoneModTools(p.uri, p.cid, 'topic'); if (ot) meta.appendChild(ot); card.appendChild(meta); if (p.url) { const link = el('a', null, p.url); link.href = p.url; link.target = '_blank'; link.rel = 'noopener noreferrer'; link.style.wordBreak = 'break-all'; card.appendChild(el('p', 'small')).appendChild(link); const emb = linkEmbed(p.url, p.bandcampId); if (!emb) { const lc = linkCard(p); if (lc) card.appendChild(lc); } if (emb) card.appendChild(emb); } if (p.text) card.appendChild(richText(p.text)); { const grid = el('div', 'post-media-grid'); for (const m of p.media ?? []) { const link = m?.image?.ref?.$link ?? m?.image?.ref?.['/']; if (!link) continue; const img = blobImg(p.authorDid, link, m.alt, 'media-thumb'); // Once the blob loads, wide images (≥ 2:1) claim the full row. img.addEventListener('load', () => { if (img.naturalWidth >= img.naturalHeight * 2) img.classList.add('wide'); }); grid.appendChild(img); } if (grid.children.length) card.appendChild(grid); } if (p.pollOptions) card.appendChild(pollSection(p)); const sig = signatureLine(p.authorSignature, p.authorSignatureColor); if (sig) card.appendChild(sig); if (session) { const row = el('div', 'form-row'); row.appendChild(followButton(p)); if ((p.topicFollowers ?? 0) > 0) { row.appendChild(el('span', 'muted small', `${p.topicFollowers} ${p.topicFollowers === 1 ? 'person follows' : 'people follow'} this topic`)); } card.appendChild(row); } app.appendChild(card); app.appendChild(el('h2', null, `${data.comments.length} ${data.comments.length === 1 ? 'comment' : 'comments'}`)); const flat = buildThreads(data.comments ?? []); // Group the flat thread list into top-level threads for pagination. const threadGroups = []; for (const t of flat) { if (t.depth === 0 || threadGroups.length === 0) threadGroups.push([t]); else threadGroups[threadGroups.length - 1].push(t); } if (!flat.length) { app.appendChild(el('p', 'muted', 'No comments yet.')); } else { const commentsBox = el('div'); app.appendChild(commentsBox); let perPage = 20; let page = 0; if (commentRkey) { const idx = threadGroups.findIndex((g) => g.some((t) => rkeyOf(t.comment.uri) === commentRkey)); if (idx >= 0) page = Math.floor(idx / perPage); } const renderComments = () => { commentsBox.textContent = ''; const pageCount = Math.max(1, Math.ceil(threadGroups.length / perPage)); const safePage = Math.min(page, pageCount - 1); for (const g of threadGroups.slice(safePage * perPage, safePage * perPage + perPage)) { for (const t of g) commentsBox.appendChild(commentCard(t.comment, t.depth, p)); } const controls = el('div', 'meta pager'); const per = el('span'); for (const n of [10, 20, 50]) { const b = el('button', 'linklike', String(n)); b.setAttribute('aria-pressed', perPage === n ? 'true' : 'false'); if (perPage === n) { b.style.color = 'var(--heading)'; b.style.textDecoration = 'underline'; } b.onclick = () => { perPage = n; page = 0; renderComments(); }; per.appendChild(b); } per.appendChild(el('span', null, 'replies per page')); controls.appendChild(per); if (pageCount > 1) { const pager = el('span'); const newer = el('button', 'linklike', '← Newer'); newer.disabled = safePage === 0; newer.onclick = () => { page = safePage - 1; renderComments(); }; const older = el('button', 'linklike', 'Older →'); older.disabled = safePage >= pageCount - 1; older.onclick = () => { page = safePage + 1; renderComments(); }; pager.append(newer, el('span', null, ` Page ${safePage + 1} of ${pageCount} `), older); controls.appendChild(pager); } commentsBox.appendChild(controls); }; renderComments(); if (commentRkey) { window.setTimeout(() => document.getElementById('comment-' + commentRkey)?.scrollIntoView({ behavior: 'smooth', block: 'center' }), 300); } } if (session) app.appendChild(commentForm(p, null)); else app.appendChild(el('p', 'muted small', 'Sign in to join the discussion.')); } function buildThreads(comments) { const byDate = (a, b) => +new Date(a.createdAt) - +new Date(b.createdAt); const byUri = new Map(comments.map((c) => [c.uri, c])); const depth = (c) => { let d = 0, cur = c; while (cur.parentUri && byUri.has(cur.parentUri) && d < 6) { d++; cur = byUri.get(cur.parentUri); } return d; }; const replies = new Map(); for (const c of comments) { if (!c.parentUri) continue; const list = replies.get(c.parentUri) ?? []; list.push(c); replies.set(c.parentUri, list); } for (const l of replies.values()) l.sort(byDate); const out = []; const seen = new Set(); const walk = (c) => { out.push({ comment: c, depth: depth(c) }); seen.add(c.uri); for (const r of replies.get(c.uri) ?? []) walk(r); }; for (const c of comments.filter((x) => !x.parentUri).sort(byDate)) walk(c); for (const c of comments) if (!seen.has(c.uri)) out.push({ comment: c, depth: 0 }); return out; } // Comment card, matching the hosted Site: a vote rail on the left, content on // the right; replies carry a single thread line instead of deeper indents. function commentCard(c, depth, post) { const card = el('div', 'card frosted comment' + (depth > 0 ? ' reply' : '')); card.id = 'comment-' + rkeyOf(c.uri); const rail = el('div', 'vote-rail'); rail.appendChild(voteButton(c.uri, c.cid, c.voteCount ?? 0)); const body = el('div', 'comment-main'); const meta = el('div', 'meta'); meta.style.marginTop = '0'; meta.appendChild(authorEl(c.authorDid, c.authorFlairText, c.authorFlairColor)); const cChips = labelChips(c.labels); if (cChips) meta.appendChild(cChips); meta.appendChild(el('span', 'points', `${c.voteCount ?? 0} ${c.voteCount === 1 ? 'point' : 'points'}`)); meta.appendChild(el('span', null, timeAgo(c.createdAt))); const cEdited = editedStamp(c.createdAt, c.updatedAt); if (cEdited) meta.appendChild(cEdited); const tools = ownerTools(c.uri, 'ca.astronomi.boards.comment', c, 'comment'); if (tools) meta.appendChild(tools); const mt = modTools(c.uri, 'comment', 'comment'); if (mt) meta.appendChild(mt); const rt = reportTools(c.uri, c.cid, 'Comment'); if (rt) meta.appendChild(rt); const ot = ozoneModTools(c.uri, c.cid, 'comment'); if (ot) meta.appendChild(ot); body.appendChild(meta); const bodyEl = richText(c.text); body.appendChild(bodyEl); { const a = bodyEl.querySelector('a[href]'); if (a) { const emb = linkEmbed(a.href, c.bandcampId); if (emb) body.appendChild(emb); } } for (const m of c.media ?? []) { if (m?.image?.ref?.$link) body.appendChild(blobImg(c.authorDid, m.image.ref.$link, m.alt)); } const sig = signatureLine(c.authorSignature, c.authorSignatureColor); if (sig) body.appendChild(sig); { const footer = el('div', 'reply-footer'); if (session) { const replyBtn = el('button', 'linklike', 'Reply'); replyBtn.onclick = () => { if (card.querySelector('form')) return; body.appendChild(commentForm(post, c, () => card.querySelector('form')?.remove())); }; footer.appendChild(replyBtn); } footer.appendChild(shareIconButton('/p/' + post.rkey + '?c=' + rkeyOf(c.uri), 'Copy link to this reply')); body.appendChild(footer); } card.append(rail, body); return card; } // Poll options with a gold progress fill, matching the hosted Site. function pollSection(p) { const box = el('section', 'poll'); box.setAttribute('aria-label', 'Poll'); const total = p.pollTotal ?? 0; box.appendChild(el('p', 'poll-head', `Poll · ${total} ${total === 1 ? 'vote' : 'votes'}`)); const ul = el('ul', 'poll-list'); p.pollOptions.forEach((opt, i) => { const count = p.pollTallies?.[i] ?? 0; const pct = total > 0 ? Math.round((count / total) * 100) : 0; const mine = myBallots.get(p.uri)?.option === i; const li = el('li'); const b = el('button', 'poll-opt'); b.setAttribute('aria-pressed', mine ? 'true' : 'false'); const fill = el('span', 'poll-fill'); fill.style.width = pct + '%'; fill.setAttribute('aria-hidden', 'true'); const row = el('span', 'poll-row'); row.appendChild(el('span', 'poll-label', (mine ? '✓ ' : '') + opt)); row.appendChild(el('span', 'poll-nums', `${pct}% · ${count}`)); b.append(fill, row); if (!session) { b.disabled = true; b.title = 'Sign in to vote'; } else { b.title = mine ? 'Withdraw your vote' : 'Vote for this option'; b.onclick = async () => { b.disabled = true; try { await votePoll(p, i); window.setTimeout(route, 1500); } catch (e) { toast('Vote failed: ' + e.message); b.disabled = false; } }; } li.appendChild(b); ul.appendChild(li); }); box.appendChild(ul); box.appendChild(el('p', 'poll-hint', !session ? 'Sign in to vote in this poll.' : myBallots.has(p.uri) ? 'Tap your choice again to withdraw it, or pick another to switch.' : 'Tap an option to vote — you can switch or withdraw it later.')); return box; } // ---------- member profiles ---------- async function viewMember(did) { app.textContent = ''; app.appendChild(el('p', 'muted center pad', 'Loading member…')); let data; try { data = await getJSON('/members/' + did); } catch (e) { return viewError('Could not load this member: ' + e.message); } app.textContent = ''; forumProfiles.set(did, data.profile ?? null); const bp = await profileOf(did); const name = bp?.displayName || (bp?.handle ? '@' + bp.handle : did.slice(0, 18) + '…'); // Banner + overlapping avatar, like the hosted member page. const card = el('div', 'card profile-card'); const banner = el('div', 'profile-banner'); if (bp?.banner) { const img = el('img'); img.src = bp.banner; img.alt = ''; img.loading = 'lazy'; banner.appendChild(img); } const av = el('div', 'profile-avatar'); if (bp?.avatar) { const img = el('img'); img.src = avatarThumb(bp.avatar); img.alt = `${name}'s avatar`; img.loading = 'lazy'; av.appendChild(img); } else { av.appendChild(el('span', null, name.slice(0, 1).toUpperCase())); } banner.appendChild(av); card.appendChild(banner); const body = el('div', 'profile-body'); const titleRow = el('div', 'meta'); titleRow.style.marginTop = '0'; titleRow.appendChild(el('h1', null, name)); if (bp?.verified) { const v = el('span', 'verified', '✓'); v.title = 'Verified on Bluesky'; v.setAttribute('role', 'img'); v.setAttribute('aria-label', 'Verified on Bluesky'); titleRow.appendChild(v); } if (bp?.trustedVerifier) { const v = el('span', 'verified gold', '🛡'); v.title = 'Trusted verifier on Bluesky'; v.setAttribute('role', 'img'); v.setAttribute('aria-label', 'Trusted verifier on Bluesky'); titleRow.appendChild(v); } if (data.profile?.flairText) titleRow.appendChild(flairPill(data.profile.flairText, data.profile.flairColor)); body.appendChild(titleRow); const sub = el('div', 'meta'); if (bp?.handle) sub.appendChild(el('span', null, '@' + bp.handle)); if (data.profile?.pronouns) sub.appendChild(el('span', null, '(' + data.profile.pronouns + ')')); body.appendChild(sub); if (bp?.description) body.appendChild(el('p', 'small', bp.description)); if (data.profile?.about) body.appendChild(richText(data.profile.about)); if (data.profile?.signature) body.appendChild(signatureLine(data.profile.signature, data.profile.signatureColor)); if (data.profile?.links?.length) { const links = el('div', 'meta'); for (const l of data.profile.links) { const a = el('a', 'tag', (() => { try { return new URL(l).hostname; } catch { return l; } })()); a.href = l; a.target = '_blank'; a.rel = 'noopener noreferrer'; links.appendChild(a); } body.appendChild(links); } const stats = el('div', 'meta'); stats.appendChild(el('span', 'points', `${data.posts.length} ${data.posts.length === 1 ? 'topic' : 'topics'}`)); stats.appendChild(el('span', 'points', `${data.comments.length} ${data.comments.length === 1 ? 'comment' : 'comments'}`)); if (data.joinedAt) { stats.appendChild(el('span', null, 'member since ' + new Date(data.joinedAt).toLocaleDateString('en-US', { month: 'short', year: 'numeric' }))); } if (session && myDid === did && typeof data.karma === 'number') { const k = el('span', 'points', `${data.karma} karma`); k.title = 'Net votes on your posts and comments. Only you can see this number.'; stats.appendChild(k); stats.appendChild(el('span', 'muted small', '(only you)')); } body.appendChild(stats); if (session && myDid === did) { const note = el('p', 'muted small', 'Your avatar and banner come from your Bluesky profile — update them there and they appear here automatically.'); note.style.borderTop = '1px solid rgba(159,191,224,0.15)'; note.style.paddingTop = '0.6rem'; body.appendChild(note); } card.appendChild(body); app.appendChild(card); { const bsky = el('a', 'tag', 'Bluesky profile ↗'); bsky.href = 'https://bsky.app/profile/' + did; bsky.target = '_blank'; bsky.rel = 'noopener noreferrer'; stats.appendChild(bsky); } if (session && myDid === did) app.appendChild(profileForm(data.profile)); if (data.posts.length) { app.appendChild(el('h2', null, 'Topics')); for (const p of data.posts) app.appendChild(postCard(p)); } if (data.comments.length) { app.appendChild(el('h2', null, 'Recent comments')); for (const c of data.comments) { const cCard = el('a', 'card'); cCard.href = '#/post/' + c.postUri.split('/').pop(); if (c.postTitle) cCard.appendChild(el('div', 'small muted', 'in “' + c.postTitle + '”')); cCard.appendChild(richText(c.text)); cCard.appendChild(el('div', 'meta', timeAgo(c.createdAt))); app.appendChild(cCard); } } if (!data.posts.length && !data.comments.length) { app.appendChild(el('p', 'muted center pad', 'No activity yet.')); } } function profileForm(existing) { const card = el('div', 'card'); card.appendChild(el('h2', null, 'Your forum profile')); const form = el('form'); const flairText = el('input'); flairText.placeholder = 'Flair (e.g. your role or interests)'; flairText.maxLength = 60; flairText.value = existing?.flairText ?? ''; // Flair color as planet bubbles — the same palette the text editor uses. let flairColorPick = existing?.flairColor ?? '#e6ebf1'; const colorRow = el('div', 'flair-colors'); colorRow.setAttribute('role', 'group'); colorRow.setAttribute('aria-label', 'Flair color'); for (const [name, c] of FLAIR_COLORS) { const dot = el('button', 'color-dot'); dot.type = 'button'; dot.style.background = c; dot.title = name; dot.setAttribute('aria-label', 'Flair color ' + name); dot.setAttribute('aria-pressed', flairColorPick === c ? 'true' : 'false'); dot.onclick = () => { flairColorPick = c; for (const d of colorRow.querySelectorAll('.color-dot')) d.setAttribute('aria-pressed', 'false'); dot.setAttribute('aria-pressed', 'true'); }; colorRow.appendChild(dot); } const pronouns = el('input'); pronouns.placeholder = 'Pronouns (optional)'; pronouns.maxLength = 40; pronouns.value = existing?.pronouns ?? ''; const about = el('textarea'); about.placeholder = 'About — a few lines about you'; about.maxLength = 500; about.value = existing?.about ?? ''; const sig = el('input'); sig.placeholder = 'Signature — shown under your posts'; sig.maxLength = 200; sig.value = existing?.signature ?? ''; // Signature color: the same planet bubbles, plus a Default (site subtle) swatch. let sigColorPick = existing?.signatureColor ?? ''; const sigColorRow = el('div', 'flair-colors'); sigColorRow.setAttribute('role', 'group'); sigColorRow.setAttribute('aria-label', 'Signature color'); const mkSigDot = (name, c, val) => { const dot = el('button', 'color-dot'); dot.type = 'button'; dot.style.background = c; dot.title = name; dot.setAttribute('aria-label', 'Signature color ' + name); dot.setAttribute('aria-pressed', sigColorPick === val ? 'true' : 'false'); dot.onclick = () => { sigColorPick = val; for (const d of sigColorRow.querySelectorAll('.color-dot')) d.setAttribute('aria-pressed', 'false'); dot.setAttribute('aria-pressed', 'true'); }; sigColorRow.appendChild(dot); }; for (const [name, c] of FLAIR_COLORS) mkSigDot(name, c, c); const linkInputs = [0, 1, 2].map((i) => { const l = el('input'); l.type = 'url'; l.placeholder = `Link ${i + 1} (optional)`; l.maxLength = 500; l.value = existing?.links?.[i] ?? ''; l.style.marginTop = '0.4rem'; return l; }); const submit = el('button', 'primary', 'Save profile'); submit.type = 'submit'; form.append( el('label', null, 'Flair'), flairText, el('label', null, 'Flair color'), colorRow, el('label', null, 'Pronouns'), pronouns, el('label', null, 'About'), about, el('label', null, 'Signature'), sig, el('label', null, 'Signature color'), sigColorRow, el('label', null, 'Links'), ...linkInputs, ); const row = el('div', 'form-row'); row.appendChild(submit); form.appendChild(row); form.onsubmit = async (e) => { e.preventDefault(); submit.disabled = true; try { const record = { $type: 'ca.astronomi.boards.profile', updatedAt: new Date().toISOString() }; if (flairText.value.trim()) record.flairText = flairText.value.trim(); record.flairColor = flairColorPick; if (pronouns.value.trim()) record.pronouns = pronouns.value.trim(); if (about.value.trim()) record.about = about.value.trim(); if (sig.value.trim()) record.signature = sig.value.trim(); if (sigColorPick) record.signatureColor = sigColorPick; const links = linkInputs.map((l) => l.value.trim()).filter(Boolean); if (links.length) record.links = links; await repoWrite('putRecord', { repo: myDid, collection: 'ca.astronomi.boards.profile', rkey: 'self', record, }); toast('Profile saved — appearing as the index updates…'); window.setTimeout(route, 1500); } catch (err) { toast('Save failed: ' + err.message); submit.disabled = false; } }; card.appendChild(form); return card; } // ---------- notifications, media, search, members, moderation ---------- async function viewNotifications() { app.textContent = ''; if (!session) { app.appendChild(el('p', 'muted center pad', 'Sign in to see notifications.')); return; } app.appendChild(el('h1', null, 'Notifications')); let data; try { data = await getJSON('/notifications/' + myDid); } catch (e) { return viewError('Could not load notifications: ' + e.message); } try { localStorage.setItem('asteri:notifSeen', new Date().toISOString()); } catch { /* private mode */ } if (!data.items?.length) { app.appendChild(el('p', 'muted center pad', 'Replies to your topics and comments will appear here.')); return; } for (const n of data.items) { const a = el('a', 'card'); a.href = '#/post/' + n.postRkey; const line = el('div', 'small'); line.appendChild(authorEl(n.authorDid)); line.appendChild(document.createTextNode( (n.kind === 'reply-comment' ? ' replied to your comment' : ' replied to your topic') + (n.postTitle ? ` “${n.postTitle}”` : ''))); a.appendChild(line); a.appendChild(el('div', 'muted small', n.text.slice(0, 140))); a.appendChild(el('div', 'meta', timeAgo(n.createdAt))); app.appendChild(a); } } async function viewMedia() { app.textContent = ''; app.appendChild(el('h1', null, 'Media')); app.appendChild(el('p', 'muted', 'Images shared across the forum — each stored in its author\'s own repo.')); await renderMediaInto(app); } // The Spaces tab: the Spaces preview panel as its own destination. function renderSpacesTab(box) { box.appendChild(el('h1', null, 'Spaces')); box.appendChild(el('p', 'muted', 'ATProto Spaces begin shipping December 1st.')); box.appendChild(spacesPanel()); } async function viewSearch(q) { app.textContent = ''; app.appendChild(el('h1', null, `Search: ${q}`)); let data; try { data = await getJSON('/search?q=' + encodeURIComponent(q)); } catch (e) { return viewError('Search failed: ' + e.message); } const { posts = [], comments = [] } = data; if (!posts.length && !comments.length) { app.appendChild(el('p', 'muted center pad', 'Nothing matched — try another phrase.')); return; } if (posts.length) { app.appendChild(el('h2', null, `${posts.length} ${posts.length === 1 ? 'topic' : 'topics'}`)); for (const p of posts) app.appendChild(postCard(p)); } if (comments.length) { app.appendChild(el('h2', null, `${comments.length} ${comments.length === 1 ? 'comment' : 'comments'}`)); for (const c of comments) { const a = el('a', 'card'); a.href = '#/post/' + c.postRkey; const line = el('div', 'small muted'); line.appendChild(authorEl(c.authorDid)); line.appendChild(document.createTextNode(` in “${c.postTitle}” · ${timeAgo(c.createdAt)}`)); a.appendChild(line); a.appendChild(richText(c.text.slice(0, 300))); app.appendChild(a); } } } async function renderMembersInto(box) { box.appendChild(el('h1', null, 'Members')); box.appendChild(el('p', 'muted', 'Everyone who\'s posted, voted, or set up a profile — each row is their own repo.')); let data; try { data = await getJSON('/members'); } catch (e) { box.appendChild(errorCard('Could not load members: ' + e.message)); return; } if (!data.members?.length) { box.appendChild(el('p', 'muted center pad', 'No members yet.')); return; } for (const m of data.members) { const a = el('a', 'card frosted'); a.href = '#/user/' + m.did; const row = el('div', 'board-row'); const left = el('div'); const name = el('div', 'board-name'); name.style.fontSize = '1rem'; name.appendChild(authorEl(m.did)); if (m.flairText) { name.appendChild(document.createTextNode(' ')); name.appendChild(flairPill(m.flairText, m.flairColor)); } left.appendChild(name); left.appendChild(el('div', 'board-stats', `${m.topics} ${m.topics === 1 ? 'topic' : 'topics'} · ${m.comments} ${m.comments === 1 ? 'comment' : 'comments'}` + (m.lastActive ? ` · active ${timeAgo(m.lastActive)}` : ''))); row.append(left, el('span', 'muted', '→')); a.appendChild(row); box.appendChild(a); } } async function viewMembers() { app.textContent = ''; await renderMembersInto(app); } async function viewMod() { app.textContent = ''; if (!isAdmin() && !isOzoneMod) { app.appendChild(el('p', 'muted center pad', 'Admins only.')); return; } app.appendChild(el('h1', null, 'Moderation')); if (isOzoneMod) { app.appendChild(el('h2', null, 'Ozone queue')); const queueWrap = el('div'); queueWrap.appendChild(el('p', 'muted small', 'Loading…')); app.appendChild(queueWrap); try { const [open, escalated] = await Promise.all([ fetchOzoneQueue('tools.ozone.moderation.defs#reviewOpen'), fetchOzoneQueue('tools.ozone.moderation.defs#reviewEscalated'), ]); const items = [...escalated, ...open.filter((o) => !escalated.some((e) => e.id === o.id))]; queueWrap.textContent = ''; if (!items.length) queueWrap.appendChild(el('p', 'muted center pad', 'Queue is empty.')); for (const st of items) queueWrap.appendChild(ozoneQueueItem(st)); } catch (err) { queueWrap.textContent = ''; queueWrap.appendChild(el('p', 'muted small', 'Could not load Ozone queue: ' + err.message)); } } if (!isAdmin()) return; app.appendChild(el('h2', null, 'Hidden from this site')); app.appendChild(el('p', 'muted', 'Hidden from this site\'s index. Records remain in their authors\' repos — hiding is a view, not a deletion.')); const token = localStorage.getItem('asteri:modToken'); if (!token) { app.appendChild(el('p', 'muted center pad', 'Use any Hide button once to set your moderation token.')); return; } const res = await fetch(API + '/mod/hidden', { method: 'POST', headers: { 'content-type': 'application/json', 'x-mod-token': token }, body: '{}' }); const data = await res.json().catch(() => ({})); if (!res.ok) { localStorage.removeItem('asteri:modToken'); return viewError('Token rejected — cleared; use a Hide button to re-enter it.'); } if (!data.items?.length) { app.appendChild(el('p', 'muted center pad', 'Nothing hidden.')); return; } for (const item of data.items) { const card = el('div', 'card'); card.appendChild(el('div', 'small', item.kind + ' · ' + item.uri)); if (item.reason) card.appendChild(el('div', 'muted small', 'Reason: ' + item.reason)); card.appendChild(el('div', 'meta', 'hidden ' + timeAgo(item.hidden_at))); const un = el('button', null, 'Unhide'); un.onclick = async () => { un.disabled = true; try { await modCall('unhide', { uri: item.uri }); toast('Restored'); route(); } catch (e) { toast('Unhide failed: ' + e.message); un.disabled = false; } }; card.appendChild(un); app.appendChild(card); } } // ---------- forms ---------- // Live character counter for rich editors (plain-text length vs the cap). function charCount(editor, max = 5000) { const s = el('span', 'muted small', '0/' + max); s.style.cssText = 'display:block;text-align:right;margin-top:0.2rem'; editor.wrap.addEventListener('input', () => { const n = editor.getHTML().replace(/<[^>]*>/g, '').length; s.textContent = n + '/' + max; s.style.color = n > max ? 'var(--danger)' : ''; }); return s; } function composeForm(defaultBoard) { const card = el('div', 'card'); card.appendChild(el('h2', null, 'New Boards post')); const form = el('form'); const boardSel = el('select'); boardSel.setAttribute('aria-label', 'Board'); for (const b of BOARDS) { const o = el('option', null, b.name + ' | ' + b.theme); o.value = b.slug; if (b.slug === defaultBoard) o.selected = true; boardSel.appendChild(o); } const title = el('input'); title.placeholder = 'Title'; title.required = true; title.maxLength = 150; const url = el('input'); url.placeholder = 'Link (optional)'; url.type = 'url'; const text = richEditor('Share some context or start a discussion…'); const textCount = charCount(text); const media = mediaPicker(4); const tags = tagPicker(3); // Optional poll: toggle reveals 2 option inputs, "+ add option" up to 6. const pollWrap = el('div'); const pollToggle = el('button', null, '+ Make it a poll'); pollToggle.type = 'button'; const pollInputs = []; pollToggle.onclick = () => { pollToggle.remove(); for (let i = 0; i < 2; i++) { const o = el('input'); o.placeholder = 'Option ' + (i + 1); o.maxLength = 80; o.style.marginTop = '0.4rem'; pollInputs.push(o); pollWrap.appendChild(o); } const more = el('button', 'linklike', '+ add option'); more.type = 'button'; more.onclick = () => { if (pollInputs.length >= 6) return; const o = el('input'); o.placeholder = 'Option ' + (pollInputs.length + 1); o.maxLength = 80; o.style.marginTop = '0.4rem'; pollInputs.push(o); pollWrap.insertBefore(o, more); }; pollWrap.appendChild(more); }; pollWrap.appendChild(pollToggle); const submit = el('button', 'primary', 'Submit'); submit.type = 'submit'; form.append(el('label', null, 'Board'), boardSel, el('label', null, 'Title'), title, el('label', null, 'Link'), url, el('label', null, 'Text'), text.wrap, textCount, media.wrap, el('label', null, 'Tags (up to 3)'), tags.wrap, pollWrap); const row = el('div', 'form-row'); row.appendChild(submit); form.appendChild(row); form.onsubmit = async (e) => { e.preventDefault(); submit.disabled = true; try { const record = { $type: 'ca.astronomi.boards.post', title: title.value.trim(), board: boardSel.value, createdAt: new Date().toISOString(), }; if (url.value.trim()) record.url = stripTrackingParams(url.value.trim()); const bodyHtml = text.getHTML(); if (bodyHtml) record.text = bodyHtml; const opts = pollInputs.map((o) => o.value.trim()).filter(Boolean); if (opts.length >= 2) record.pollOptions = opts; const tagPicks = tags.getTags(); if (tagPicks.length) record.tags = tagPicks; if (media.picks.length) { submit.textContent = 'Uploading images…'; const items = []; for (const p of media.picks) { const blob = await uploadBlob(await toJpeg(p.file, 9_500_000)); items.push({ image: blob, alt: p.alt.trim() || p.file.name }); } record.media = items; submit.textContent = 'Submit'; } const res = await repoWrite('createRecord', { repo: myDid, collection: 'ca.astronomi.boards.post', record }); const rkey = res.uri.split('/').pop(); toast('Posted! Opening your topic…'); window.setTimeout(() => { location.hash = '#/post/' + rkey; }, 1200); } catch (err) { toast('Post failed: ' + err.message); submit.disabled = false; submit.textContent = 'Submit'; } }; card.appendChild(form); return card; } function commentForm(post, parent, onCancel) { const form = el('form'); form.style.marginTop = '0.6rem'; const text = richEditor(parent ? 'Write a reply…' : 'Add to the discussion…'); const textCount = charCount(text); const media = mediaPicker(4); const submit = el('button', 'primary', parent ? 'Reply' : 'Comment'); submit.type = 'submit'; const row = el('div', 'form-row'); row.appendChild(submit); if (onCancel) { const cancel = el('button', null, 'Cancel'); cancel.type = 'button'; cancel.onclick = onCancel; row.appendChild(cancel); } form.append(text.wrap, textCount, media.wrap, row); form.onsubmit = async (e) => { e.preventDefault(); if (!text.getHTML()) { toast('Write something first.'); return; } submit.disabled = true; try { const record = { $type: 'ca.astronomi.boards.comment', post: { uri: post.uri, cid: post.cid ?? '' }, text: text.getHTML(), createdAt: new Date().toISOString(), }; if (parent) record.parent = { uri: parent.uri, cid: parent.cid ?? '' }; if (media.picks.length) { submit.textContent = 'Uploading…'; const items = []; for (const p of media.picks) { const blob = await uploadBlob(await toJpeg(p.file, 9_500_000)); items.push({ image: blob, alt: p.alt.trim() || p.file.name }); } record.media = items; submit.textContent = parent ? 'Reply' : 'Comment'; } await repoWrite('createRecord', { repo: myDid, collection: 'ca.astronomi.boards.comment', record }); toast('Comment posted! Appearing as the index updates…'); window.setTimeout(route, 1500); } catch (err) { toast('Comment failed: ' + err.message); submit.disabled = false; } }; return form; } // ---------- Bluesky public reads (Lists / Following / Feeds) ---------- const BSKY_API = 'https://public.api.bsky.app/xrpc/'; async function bskyQuery(method, params = {}) { const qs = new URLSearchParams(); for (const [k, v] of Object.entries(params)) { if (v === undefined || v === null) continue; if (Array.isArray(v)) for (const x of v) qs.append(k, String(x)); else qs.set(k, String(v)); } const res = await fetch(BSKY_API + method + (qs.size ? '?' + qs : '')); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.message || `HTTP ${res.status}`); return data; } // Saved feeds and custom mix tabs are per-account, kept on this device. function readJSON(key, fallback) { try { const v = JSON.parse(localStorage.getItem(key) ?? 'null'); return v ?? fallback; } catch { return fallback; } } function writeJSON(key, value) { try { localStorage.setItem(key, JSON.stringify(value)); } catch { /* private mode */ } } const savedFeedsKey = () => session ? `asteri:savedFeeds:${myDid}` : null; const feedTabsKey = () => session ? `asteri:feedTabs:${myDid}` : null; function savedFeedsRead() { const k = savedFeedsKey(); if (!k) return []; const raw = readJSON(k, []); return Array.isArray(raw) ? raw.filter((f) => typeof f?.uri === 'string' && typeof f?.displayName === 'string') : []; } function savedFeedsWrite(next) { const k = savedFeedsKey(); if (k) writeJSON(k, next); } function feedTabsRead() { const k = feedTabsKey(); if (!k) return []; const raw = readJSON(k, []); return Array.isArray(raw) ? raw.filter((t) => typeof t?.id === 'string' && typeof t?.name === 'string' && Array.isArray(t?.feedUris) && t.feedUris.every((u) => typeof u === 'string')) : []; } function feedTabsWrite(next) { const k = feedTabsKey(); if (k) writeJSON(k, next); } function createFeedTab(name, feedUris) { if (!feedTabsKey() || feedUris.length === 0) return null; const t = { id: Math.random().toString(36).slice(2, 10), name: name.trim().slice(0, 24) || 'My mix', feedUris: [...new Set(feedUris)].slice(0, 10), }; feedTabsWrite([...feedTabsRead(), t]); return t; } // One Bluesky post card: author, text, images, link card, quote, counts. // Quotes (plain or with-media) render with their own embeds; videos play // inline; images use the same 2×2 / 2:1-rectangle grid as forum posts. function feedPostCard(fp, source) { const li = el('li', 'card'); if (contentPrefsCache) { const verdict = contentFilterFor(fp, contentPrefsCache); if (verdict === 'hide') { li.hidden = true; li.style.display = 'none'; return li; } if (verdict === 'warn') { const cover = el('button', 'linklike'); cover.type = 'button'; cover.style.cssText = 'display:block;width:100%;text-align:left;padding:0.6rem 0;color:var(--muted)'; cover.textContent = 'Content warning — tap to show'; let revealed = false; cover.onclick = (e) => { e.stopPropagation(); revealed = !revealed; inner.style.display = revealed ? '' : 'none'; cover.textContent = revealed ? 'Content warning — tap to hide' : 'Content warning — tap to show'; }; li.appendChild(cover); var inner = el('div'); inner.style.display = 'none'; li.appendChild(inner); li._warnInner = inner; } } const target = li._warnInner ?? li; li.style.listStyle = 'none'; li.style.cursor = 'pointer'; li.onclick = (e) => { if (e.target.closest('a, button, img, video, form, textarea, input, select')) return; openFeedThread(fp.uri); }; const rkey = fp.uri.split('/').pop(); const postUrl = fp.author?.did && rkey ? `https://bsky.app/profile/${fp.author.did}/post/${rkey}` : undefined; const when = fp.indexedAt ?? fp.record?.createdAt; const media = fp.embed?.media ?? fp.embed; // Plain quote: embed.record IS the quoted post. Quote-with-media: // embed.record.record. Blocked/detached quotes have neither value nor uri. const quoteRec = fp.embed?.record; const quote = quoteRec?.record ?? (quoteRec?.value ? quoteRec : null); if (source) { const s = el('p', 'muted small', 'from '); s.style.margin = '0 0 0.4rem'; s.appendChild(el('span', null, source)).style.color = 'var(--link)'; target.appendChild(s); } if (fp.reason?.by) { const who = fp.reason.by.displayName || (fp.reason.by.handle ? '@' + fp.reason.by.handle : 'someone'); target.appendChild(el('p', 'muted small', `↻ Reposted by ${who}`)).style.margin = '0 0 0.4rem'; } if (fp._replyTo) { target.appendChild(el('p', 'muted small', '↩ Reply to ' + (fp._replyTo.displayName || '@' + fp._replyTo.handle))).style.margin = '0 0 0.4rem'; } const head = el('div', 'meta'); head.style.marginTop = '0'; if (fp.author?.avatar) { const img = el('img', 'avatar'); img.src = avatarThumb(fp.author.avatar); img.alt = ''; img.loading = 'lazy'; head.appendChild(img); } const who = el('span', null, fp.author?.displayName || (fp.author?.handle ? '@' + fp.author.handle : 'Bluesky member')); who.style.cssText = 'font-weight:600;color:var(--heading)'; head.appendChild(who); if (fp.author?.handle) head.appendChild(el('span', null, '@' + fp.author.handle)); if (when) head.appendChild(el('span', null, timeAgo(when))); target.appendChild(head); if (fp.record?.text) target.appendChild(el('p', 'comment-body', fp.record.text)); appendEmbed(target, media, postUrl); if (quote) { const q = el('div', 'card'); q.style.cssText = 'margin:0.5rem 0 0'; const qm = el('div', 'meta'); qm.style.marginTop = '0'; qm.appendChild(el('span', null, quote.author?.displayName || (quote.author?.handle ? '@' + quote.author.handle : 'Bluesky member'))).style.cssText = 'font-weight:600;color:var(--heading)'; q.appendChild(qm); if (quote.value?.text) q.appendChild(el('p', 'small', quote.value.text)); const qMedia = quote.embeds?.[0]; if (qMedia) { const qRkey = quote.uri?.split('/').pop(); const qUrl = quote.author?.did && qRkey ? `https://bsky.app/profile/${quote.author.did}/post/${qRkey}` : undefined; appendEmbed(q, qMedia.media ?? qMedia, qUrl); } target.appendChild(q); } else if (quoteRec && !quoteRec.value && !quoteRec.record) { target.appendChild(el('p', 'muted small', 'Quoted post is unavailable — it may have been deleted or blocked.')); } target.appendChild(fpActions(fp, postUrl)); return li; } // Images (2×2 grid, ≥2:1 spans the row), link card, and inline video. function appendEmbed(box, media, postUrl) { const images = media?.images ?? []; const external = media?.external; // app.bsky.embed.video#view is flat (cid/playlist/thumbnail live // directly on the embed/media object) -- it's never nested under .video. const video = media?.$type === 'app.bsky.embed.video#view' ? media : media?.video; if (images.length > 0) { const grid = el('div', 'post-media-grid'); for (const img of images.slice(0, 4)) { const src = img.thumb ?? img.fullsize; if (!src) continue; const i = el('img', 'media-thumb'); i.src = src; i.alt = img.alt ?? ''; i.loading = 'lazy'; const ar = img.aspectRatio; if (ar?.width && ar?.height && ar.width >= ar.height * 2) i.classList.add('wide'); i.onclick = () => openLightbox(img.fullsize ?? src, img.alt ?? '', 'image.jpg', img.fullsize ?? src); grid.appendChild(i); } if (grid.children.length) box.appendChild(grid); } if (external?.uri) { const a = el('a', 'card'); a.href = external.uri; a.target = '_blank'; a.rel = 'noopener noreferrer'; a.style.cssText = 'margin:0.5rem 0 0;display:flex;gap:0.7rem;align-items:center'; if (external.thumb) { const t = el('img'); t.src = external.thumb; t.alt = ''; t.loading = 'lazy'; t.style.cssText = 'width:64px;height:64px;object-fit:cover;border-radius:8px;flex-shrink:0'; a.appendChild(t); } const tx = el('span'); tx.appendChild(el('span', 'small', external.title || domainOf(external.uri) || 'Link')).style.cssText = 'display:block;font-weight:600;color:var(--heading)'; tx.appendChild(el('span', 'muted small', domainOf(external.uri) ?? '')); a.appendChild(tx); box.appendChild(a); const emb2 = linkEmbed(external.uri); if (emb2) box.appendChild(emb2); } if (video?.playlist) { box.appendChild(videoPlayer(video)); } else if (video?.thumbnail && postUrl) { const a = el('a'); a.href = postUrl; a.target = '_blank'; a.rel = 'noopener noreferrer'; const t = el('img', 'media-img'); t.src = video.thumbnail; t.alt = 'Video thumbnail'; t.loading = 'lazy'; a.appendChild(t); box.appendChild(a); } } // Bluesky video is HLS: Safari plays it natively; elsewhere hls.js (from the // same CDN as the OAuth client) wires it up. function videoPlayer(video) { const v = el('video', 'media-img'); v.controls = true; v.preload = 'none'; if (video.thumbnail) v.poster = video.thumbnail; v.style.cssText = 'width:100%;border-radius:10px;margin-top:0.6rem;display:block;background:#000'; // Route through our own indexer to work around a Chromium bug where // video.bsky.app's playlist.m3u8 omits CORS headers (hls.js's manifest // fetch gets silently blocked). Safari, which can set src directly, is // unaffected and unchanged below. let src = video.playlist; try { const u = new URL(src); const m = u.pathname.match(/\/watch\/([^/]+)\/([^/]+)\/playlist\.m3u8$/); if (m) src = API + '/video/' + m[1] + '/' + m[2] + '/playlist.m3u8'; } catch { /* not a URL we recognize -- fall back to the original */ } if (v.canPlayType('application/vnd.apple.mpegurl')) { v.src = src; } else { import('https://cdn.jsdelivr.net/npm/hls.js/+esm').then(({ default: Hls }) => { if (Hls.isSupported()) { const h = new Hls(); h.loadSource(src); h.attachMedia(v); } }).catch(() => {}); } return v; } // Action row with site-styled outline icons: reply (opens the thread on // Bluesky), repost (Earth green when on) + like (Mars rose when on) toggles // that write app.bsky.feed.repost / .like records in the member's own repo. const FP_ICON = { reply: '', repost: '', like: '', }; function fpActions(fp, postUrl) { const row = el('div', 'fp-actions'); const reply = el('button', null, ''); reply.type = 'button'; reply.innerHTML = FP_ICON.reply + ' ' + (fp.replyCount ?? 0); reply.title = 'View thread / reply'; reply.onclick = () => openFeedThread(fp.uri); row.appendChild(reply); const mkToggle = (kind, icon, count, viewerUri, onClass) => { const b = el('button', null, ''); b.type = 'button'; let current = viewerUri; let n = count; const paint = () => { b.innerHTML = icon + ' ' + n; b.classList.toggle(onClass, !!current); if (current && kind === 'Like') b.querySelector('svg')?.setAttribute('fill', 'currentColor'); }; paint(); if (!session) { b.disabled = true; b.title = 'Sign in to ' + kind.toLowerCase(); return b; } b.title = kind; b.onclick = async () => { b.disabled = true; try { if (current) { await repoWrite('deleteRecord', { repo: myDid, collection: 'app.bsky.feed.' + kind.toLowerCase(), rkey: current.split('/').pop() }); current = null; n = Math.max(0, n - 1); } else { const res = await repoWrite('createRecord', { repo: myDid, collection: 'app.bsky.feed.' + kind.toLowerCase(), record: { $type: 'app.bsky.feed.' + kind.toLowerCase(), subject: { uri: fp.uri, cid: fp.cid }, createdAt: new Date().toISOString() }, }); current = res.uri; n += 1; } paint(); } catch (err) { toast(kind + ' failed: ' + err.message); } b.disabled = false; }; return b; }; row.appendChild(mkToggle('Repost', FP_ICON.repost, fp.repostCount ?? 0, fp.viewer?.repost, 'on-repost')); row.appendChild(mkToggle('Like', FP_ICON.like, fp.likeCount ?? 0, fp.viewer?.like, 'on-like')); if (postUrl) { const open = el('a', null, 'Open ↗'); open.href = postUrl; open.target = '_blank'; open.rel = 'noopener noreferrer'; row.appendChild(open); } return row; } // Shape a timeline/feed item into a card-ready post, keeping repost and // reply context (the reply's parent author drives the "Replying to" label). function feedItemPost(it, feedName) { if (!it.post) return null; const p = it.reason ? { ...it.post, reason: it.reason } : { ...it.post }; const ra = it.reply?.parent?.author; if (ra) p._replyTo = ra; if (feedName) p._feedName = feedName; return p; } // In-app thread view: parent chain, the post, its replies, and an inline // reply composer (writes app.bsky.feed.post to the member's own repo). async function openFeedThread(uri) { const ov = el('div', 'lightbox'); ov.setAttribute('role', 'dialog'); ov.setAttribute('aria-label', 'Thread'); const panel = el('div', 'thread-panel'); panel.appendChild(el('p', 'muted center pad', 'Loading…')); const close = el('button', 'thread-close', 'Close'); close.type = 'button'; close.onclick = () => ov.remove(); ov.append(close, panel); ov.onclick = (e) => { if (e.target === ov) ov.remove(); }; const onKey = (e) => { if (e.key === 'Escape') { ov.remove(); document.removeEventListener('keydown', onKey); } }; document.addEventListener('keydown', onKey); document.body.appendChild(ov); let data; try { data = await bskyQuery('app.bsky.feed.getPostThread', { uri, depth: 6, parentHeight: 10 }); } catch (err) { panel.textContent = ''; panel.appendChild(errorCard('Could not load the thread: ' + err.message)); return; } panel.textContent = ''; const t = data.thread; if (!t?.post) { panel.appendChild(el('p', 'muted center pad', 'That post is unavailable.')); return; } const parents = []; let cur = t.parent; while (cur?.post && parents.length < 10) { parents.unshift(cur.post); cur = cur.parent; } for (const p of parents) panel.appendChild(feedPostCard(p)); panel.appendChild(feedPostCard(t.post)); if (session) panel.appendChild(feedReplyForm(t.post, parents[0] ?? t.post)); for (const r of t.replies ?? []) if (r.post) panel.appendChild(feedPostCard(r.post)); } // Inline reply on a Bluesky thread. Links in the text get facets so they're // clickable; typed @handles stay plain text (mention resolution not wired). function feedReplyForm(post, root) { const form = el('form'); const ta = el('textarea'); ta.placeholder = 'Write your reply…'; ta.maxLength = 300; ta.rows = 3; ta.required = true; const send = el('button', 'primary', 'Reply'); send.type = 'submit'; const row = el('div', 'form-row'); row.appendChild(send); form.append(ta, row); form.onsubmit = async (e) => { e.preventDefault(); send.disabled = true; try { const text = ta.value.trim(); const record = { $type: 'app.bsky.feed.post', text, createdAt: new Date().toISOString(), reply: { root: { uri: root.uri, cid: root.cid }, parent: { uri: post.uri, cid: post.cid } }, }; const facets = linkFacets(text); if (facets.length) record.facets = facets; await repoWrite('createRecord', { repo: myDid, collection: 'app.bsky.feed.post', record }); toast('Reply posted!'); form.remove(); } catch (err) { toast('Reply failed: ' + err.message); send.disabled = false; } }; return form; } // Clickable links: wrap each URL in a link facet at UTF-8 byte offsets. function linkFacets(text) { const enc = new TextEncoder(); const out = []; for (const m of text.matchAll(/https?:\/\/[^\s<>"']+/g)) { out.push({ index: { byteStart: enc.encode(text.slice(0, m.index)).length, byteEnd: enc.encode(text.slice(0, m.index + m[0].length)).length }, features: [{ $type: 'app.bsky.richtext.facet#link', uri: m[0] }], }); } return out; } // Strips YouTube's per-share tracking param (si=...) so the same video // posted by different people (or re-shared) normalizes to one clean URL. // Only touches youtube.com/youtu.be; every other link passes through untouched. function stripTrackingParams(url) { try { const u = new URL(url); const h = u.hostname.replace(/^www\./, ''); if (h === 'youtube.com' || h === 'm.youtube.com' || h === 'youtu.be') { u.searchParams.delete('si'); return u.toString(); } } catch { /* not a URL -- leave it alone */ } return url; } function domainOf(url) { if (!url) return null; try { return new URL(url).hostname.replace(/^www\./, ''); } catch { return null; } } // A standard Bluesky post: app.bsky.feed.post in the member's repo, plain // text with clickable links, up to 10 images (JPEG re-encode, same as boards). function bskyComposeForm(onDone) { const form = el('form'); form.appendChild(el('h2', null, 'New Bluesky post')); const ta = el('textarea'); ta.placeholder = "What's up?"; ta.maxLength = 300; ta.rows = 4; const count = el('span', 'muted small', '0/300'); count.style.marginLeft = 'auto'; ta.oninput = () => { count.textContent = [...ta.value].length + '/300'; }; const media = mediaPicker(4); const send = el('button', 'primary', 'Post'); send.type = 'submit'; const row = el('div', 'form-row'); row.append(send, count); form.append(el('label', null, 'Text'), ta, media.wrap, row); form.onsubmit = async (e) => { e.preventDefault(); const text = ta.value.trim(); if (!text && !media.picks.length) { toast('Write something or add an image.'); return; } send.disabled = true; try { const record = { $type: 'app.bsky.feed.post', text, createdAt: new Date().toISOString() }; const facets = linkFacets(text); if (facets.length) record.facets = facets; if (media.picks.length) { send.textContent = 'Uploading…'; const images = []; for (const p of media.picks) { const blob = await uploadBlob(await toJpeg(p.file)); images.push({ image: blob, alt: p.alt.trim() }); } record.embed = { $type: 'app.bsky.embed.images', images }; send.textContent = 'Post'; } await repoWrite('createRecord', { repo: myDid, collection: 'app.bsky.feed.post', record }); toast('Posted to Bluesky!'); onDone?.(); } catch (err) { toast('Post failed: ' + err.message); send.disabled = false; } }; return form; } // "New Bluesky post" on Feeds / Following — opens the composer as a card overlay. function bskyComposeToggle() { if (!session) return null; const wrap = el('div', 'bsky-compose'); const b = el('button', 'primary', 'New Bluesky post'); b.type = 'button'; b.onclick = () => openBskyCompose(); wrap.append(b); return wrap; } // The Bluesky composer as an overlay — works from any page. function openBskyCompose() { const ov = el('div', 'lightbox'); const panel = el('div', 'thread-panel compose-panel') const close = el('button', 'thread-close', 'Close'); close.type = 'button'; close.onclick = () => ov.remove(); panel.appendChild(bskyComposeForm(() => ov.remove())); ov.append(close, panel); ov.onclick = (e) => { if (e.target === ov) ov.remove(); }; const onKey = (e) => { if (e.key === 'Escape') { ov.remove(); document.removeEventListener('keydown', onKey); } }; document.addEventListener('keydown', onKey); document.body.appendChild(ov); } // Header pencil → choose what to write. function composeChooser(anchor) { const existing = document.getElementById('composeMenu'); if (existing) { existing.remove(); return; } const menu = el('div', 'pds-menu'); menu.id = 'composeMenu'; const b1 = el('button', 'pds-opt', 'New Boards post'); b1.type = 'button'; b1.onclick = () => { menu.remove(); openCompose(); }; const b2 = el('button', 'pds-opt', 'New Bluesky post'); b2.type = 'button'; b2.onclick = () => { menu.remove(); openBskyCompose(); }; menu.append(b1, b2); anchor.parentNode.style.position = 'relative'; anchor.parentNode.appendChild(menu); const onDown = (e) => { if (!menu.contains(e.target) && e.target !== anchor) { menu.remove(); document.removeEventListener('mousedown', onDown); } }; document.addEventListener('mousedown', onDown); } // Feeds tab: the feeds your account is actually subscribed to on Bluesky, // combined into one stream (device-saved feeds as a fallback). async function renderFeedsAggregate(box) { if (!session) { box.appendChild(el('p', 'muted center pad', 'Sign in to see the feeds you\'ve saved, combined into one stream.')); return; } // Prefer the account's real Bluesky subscriptions (read from the member's // own PDS); fall back to feeds saved on this device. let feeds = null; let source = 'saved'; try { const r = await session.fetchHandler(myPds + '/xrpc/app.bsky.actor.getPreferences'); const d = await r.json().catch(() => ({})); const prefs = d.preferences ?? []; const prefV2 = prefs.find((p) => p.$type === 'app.bsky.actor.defs#savedFeedsPrefV2'); const prefV1 = prefs.find((p) => p.$type === 'app.bsky.actor.defs#savedFeedsPref'); let uris = null; if (prefV2?.items?.length) { uris = prefV2.items.filter((it) => it.type !== 'timeline').map((it) => it.value); } else if (prefV1?.saved?.length) { uris = prefV1.saved; } if (r.ok && uris?.length) { const gens = await bskyQuery('app.bsky.feed.getFeedGenerators', { feeds: uris.slice(0, 25) }).catch(() => null); const byUri = {}; for (const g of gens?.feeds ?? []) byUri[g.uri] = g.displayName ?? 'Untitled feed'; feeds = uris.slice(0, 25).map((uri) => ({ uri, displayName: byUri[uri] ?? 'Feed' })); source = 'subs'; } } catch { /* fall back to device-saved feeds */ } if (!feeds) feeds = savedFeedsRead(); if (feeds.length === 0) { const card = el('div', 'card center pad'); card.appendChild(el('p', 'empty-title', 'No feeds yet')); card.appendChild(el('p', 'muted small', 'Subscribe to feeds on Bluesky, or save them from Browse feeds — they\'ll appear here, combined.')); const b = el('button', 'textlink', 'Browse feeds →'); b.onclick = () => { location.hash = '#/feeds'; }; card.appendChild(b); box.appendChild(card); return; } box.appendChild(el('p', 'muted center pad', 'Loading…')); const results = await Promise.all(feeds.slice(0, 25).map((f) => session.fetchHandler(BSKY_API + 'app.bsky.feed.getFeed?' + new URLSearchParams({ feed: f.uri, limit: '10' })) .then((r) => r.json()) .then((r) => (r.feed ?? []).flatMap((it) => { const p = feedItemPost(it, f.displayName); return p ? [p] : []; })) .catch(() => []), )); box.textContent = ''; const seen = new Set(); const all = results.flat().filter((p) => (seen.has(p.uri) ? false : (seen.add(p.uri), true))); all.sort((a, b) => +new Date(b.indexedAt ?? b.record?.createdAt ?? 0) - +new Date(a.indexedAt ?? a.record?.createdAt ?? 0)); if (!all.length) { box.appendChild(el('p', 'muted center pad', 'Your feeds are quiet right now.')); return; } const head = el('div', 'form-row'); head.style.marginTop = '0'; head.appendChild(el('h2', null, source === 'subs' ? 'Your subscribed feeds' : 'Your saved feeds')); const more = el('button', 'textlink', '+ Add feeds'); more.style.marginLeft = 'auto'; more.onclick = () => { location.hash = '#/feeds'; }; head.appendChild(more); box.appendChild(head); const filterBar = el('div', 'meta'); filterBar.style.cssText = 'flex-wrap:wrap;gap:0.4rem'; const picked = new Set(); const chipLabel = source === 'subs' ? 'Your subscriptions — click to filter:' : 'Your saved feeds — click to filter:'; filterBar.appendChild(el('span', 'muted small', chipLabel)); const chipsRow = el('span'); const clearBtn = el('button', 'linklike', 'Clear'); clearBtn.type = 'button'; clearBtn.hidden = true; clearBtn.onclick = () => { picked.clear(); renderChips(); renderList(); }; filterBar.append(chipsRow, clearBtn); box.appendChild(filterBar); const ul = el('ul'); ul.style.cssText = 'margin:0;padding:0;display:flex;flex-direction:column;gap:0.75rem'; box.appendChild(ul); const CHIP_ON = 'color:var(--heading);border-color:var(--dim);background:rgba(159,191,224,0.12)'; function renderChips() { chipsRow.textContent = ''; for (const f of feeds.slice(0, 25)) { const chip = el('button', 'tag', f.displayName); chip.type = 'button'; chip.style.marginRight = '0.3rem'; const on = picked.has(f.displayName); chip.setAttribute('aria-pressed', on ? 'true' : 'false'); if (on) chip.style.cssText += CHIP_ON; chip.onclick = () => { if (picked.has(f.displayName)) picked.delete(f.displayName); else picked.add(f.displayName); renderChips(); renderList(); }; chipsRow.appendChild(chip); } clearBtn.hidden = picked.size === 0; } function renderList() { ul.textContent = ''; const shown = picked.size === 0 ? all : all.filter((p) => picked.has(p._feedName)); if (!shown.length) { ul.appendChild(el('p', 'muted center pad', 'No posts from the selected feeds.')); return; } for (const fp of shown.slice(0, 40)) ul.appendChild(feedPostCard(fp, fp._feedName)); } renderChips(); renderList(); } // A custom mix tab: aggregate of whichever feeds its owner picked. async function renderCustomTab(box, id, select) { const t = feedTabsRead().find((x) => x.id === id); if (!t) { box.appendChild(el('p', 'muted center pad', 'That tab was deleted.')); return; } const head = el('div', 'form-row'); head.appendChild(el('h1', null, t.name)); const rename = el('button', null, 'Rename'); rename.onclick = () => { const name = window.prompt('Tab name:', t.name)?.trim().slice(0, 24); if (!name) return; feedTabsWrite(feedTabsRead().map((x) => x.id === id ? { ...x, name } : x)); route(); }; const del = el('button', null, 'Delete tab'); del.style.color = 'var(--danger)'; del.onclick = () => { if (!window.confirm(`Delete the tab “${t.name}”?`)) return; feedTabsWrite(feedTabsRead().filter((x) => x.id !== id)); select('feeds'); }; head.append(rename, del); box.appendChild(head); box.appendChild(el('p', 'muted center pad', 'Loading…')); const gens = await bskyQuery('app.bsky.feed.getFeedGenerators', { feeds: t.feedUris }).catch(() => null); const names = {}; for (const g of gens?.feeds ?? []) names[g.uri] = g.displayName ?? 'Untitled feed'; const results = await Promise.all(t.feedUris.map((uri) => bskyQuery('app.bsky.feed.getFeed', { feed: uri, limit: 10 }) .then((r) => (r.feed ?? []).flatMap((it) => { const p = feedItemPost(it, names[uri] ?? 'Feed'); return p ? [p] : []; })) .catch(() => []), )); box.querySelector('p.muted.center')?.remove(); const pills = el('p', 'muted small'); for (const u of t.feedUris) pills.appendChild(el('span', 'tag', names[u] ?? 'Feed')), pills.appendChild(document.createTextNode(' ')); box.appendChild(pills); const seen = new Set(); const all = results.flat().filter((p) => (seen.has(p.uri) ? false : (seen.add(p.uri), true))); all.sort((a, b) => +new Date(b.indexedAt ?? b.record?.createdAt ?? 0) - +new Date(a.indexedAt ?? a.record?.createdAt ?? 0)); if (!all.length) { box.appendChild(el('p', 'muted center pad', 'These feeds are quiet right now.')); return; } const ul = el('ul'); ul.style.cssText = 'margin:0;padding:0;display:flex;flex-direction:column;gap:0.75rem'; for (const fp of all.slice(0, 40)) ul.appendChild(feedPostCard(fp, fp._feedName)); box.appendChild(ul); } // Following tab: latest posts from the people you follow on Bluesky. // Following = your real Bluesky timeline: everyone you follow, newest first, // reposts included. Read through your own PDS so it's authenticated. async function renderFollowingInto(box) { if (!session) { box.appendChild(el('p', 'muted center pad', 'This feed is personal — sign in to read the people you follow on Bluesky.')); return; } box.appendChild(el('p', 'muted center pad', 'Loading…')); let posts; try { const res = await session.fetchHandler(myPds + '/xrpc/app.bsky.feed.getTimeline?limit=50'); const data = await res.json().catch(() => ({})); if (!res.ok) throw new Error(data.message || `HTTP ${res.status}`); posts = (data.feed ?? []).flatMap((it) => { const p = feedItemPost(it); return p ? [p] : []; }); } catch (e) { box.textContent = ''; box.appendChild(errorCard('Could not read your Bluesky following feed: ' + e.message)); return; } box.textContent = ''; if (!posts.length) { const card = el('div', 'card center pad'); card.appendChild(el('p', 'empty-title', 'No recent posts')); card.appendChild(el('p', 'muted small', 'Posts from the people you follow on Bluesky will appear here as they share them.')); box.appendChild(card); return; } const ul = el('ul'); ul.style.cssText = 'margin:0;padding:0;display:flex;flex-direction:column;gap:0.75rem'; for (const fp of posts) ul.appendChild(feedPostCard(fp)); box.appendChild(ul); } // Lists tab: lists you made, plus moderation lists you follow (when readable). // Lists open inside the forum — getListFeed reads a list's posts live. async function renderListsInto(box) { if (!session) { box.appendChild(el('p', 'muted center pad', 'Lists live on your account — sign in to see the ones you made or follow.')); return; } box.appendChild(el('h1', null, 'Lists')); box.appendChild(el('p', 'muted', 'The lists on your Bluesky account — made by you, or moderation lists you follow.')); const loading = el('p', 'muted center pad', 'Loading…'); box.appendChild(loading); let made = [], muted = [], blocked = []; try { const res = await bskyQuery('app.bsky.graph.getLists', { actor: myDid, limit: 100 }); made = res.lists ?? []; } catch (e) { loading.remove(); box.appendChild(errorCard('Could not load your lists: ' + e.message)); return; } // Muted/blocked lists are viewer-private on the AppView; skip quietly if unavailable. const mutes = await bskyQuery('app.bsky.graph.getListMutes', { limit: 100 }).catch(() => null); if (mutes?.lists) muted = mutes.lists; const blocks = await bskyQuery('app.bsky.graph.getListBlocks', { limit: 100 }).catch(() => null); if (blocks?.lists) blocked = blocks.lists; loading.remove(); if (!made.length && !muted.length && !blocked.length) { box.appendChild(el('p', 'muted center pad', 'No lists yet — make a list on Bluesky and it will show up here.')); return; } const renderListView = async (l) => { box.textContent = ''; const back = el('button', 'backbar', '← Lists'); back.type = 'button'; back.onclick = () => { box.textContent = ''; renderListsInto(box); }; box.appendChild(back); box.appendChild(el('h1', null, l.name ?? 'Untitled list')); if (l.description) box.appendChild(el('p', 'muted', l.description)); box.appendChild(el('p', 'muted small', (l.purpose?.includes('modlist') ? 'Moderation list' : 'User list') + (typeof l.listItemCount === 'number' ? ` · ${l.listItemCount.toLocaleString()} members` : '') + ' · live from Bluesky')); box.appendChild(el('p', 'muted center pad', 'Loading…')); try { const r = await bskyQuery('app.bsky.feed.getListFeed', { list: l.uri, limit: 30 }); box.querySelector('p.muted.center')?.remove(); const batch = (r.feed ?? []).flatMap((it) => it.post ? [it.reason ? { ...it.post, reason: it.reason } : it.post] : []); if (!batch.length) { box.appendChild(el('p', 'muted center pad', 'This list is quiet right now.')); return; } const ul = el('ul'); ul.style.cssText = 'margin:0;padding:0;display:flex;flex-direction:column;gap:0.75rem'; for (const fp of batch) ul.appendChild(feedPostCard(fp)); box.appendChild(ul); } catch (e) { box.querySelector('p.muted.center')?.remove(); box.appendChild(errorCard('Could not load this list: ' + e.message)); } }; const group = (title, lists) => { if (!lists.length) return; box.appendChild(el('h2', null, title)); for (const l of lists) { const a = el('button', 'card frosted'); a.type = 'button'; a.onclick = () => renderListView(l); const row = el('div', 'board-row'); const left = el('div'); left.appendChild(el('div', 'board-name', l.name ?? 'Untitled list')).style.fontSize = '1rem'; if (l.description) left.appendChild(el('div', 'muted small', l.description)); left.appendChild(el('div', 'board-stats', (l.purpose?.includes('modlist') ? 'Moderation list' : 'User list') + (typeof l.listItemCount === 'number' ? ` · ${l.listItemCount.toLocaleString()} members` : ''))); row.append(left, el('span', 'muted', '→')); a.appendChild(row); box.appendChild(a); } }; group('Lists you made', made); group('Muted lists', muted); group('Blocked lists', blocked); } // Browse feeds page: search, popular; tick feeds to build a custom home tab, // or save one with +. Feeds open as a live stream right here. async function viewFeedsPage() { app.textContent = ''; app.appendChild(el('h1', null, 'Bluesky feeds')); app.appendChild(el('p', 'muted', 'Read custom Bluesky feeds without leaving Asteri.')); const saved = savedFeedsRead(); const isSaved = (uri) => saved.some((f) => f.uri === uri); const picked = new Set(); const createBar = el('div'); const renderCreateBar = () => { createBar.textContent = ''; if (!session || picked.size === 0) return; const bar = el('div', 'card form-row'); bar.style.marginTop = '0'; bar.appendChild(el('span', 'small', `New tab from ${picked.size} ${picked.size === 1 ? 'feed' : 'feeds'}:`)); const name = el('input'); name.placeholder = 'Name it — e.g. Space & Art'; name.maxLength = 24; name.style.cssText = 'flex:1;min-width:10rem'; const create = el('button', 'primary', 'Create tab'); create.onclick = () => { const t = createFeedTab(name.value, [...picked]); if (!t) return; try { localStorage.setItem('asteri:lastTab', `tab:${t.id}`); } catch { /* private mode */ } location.hash = '#/'; }; const clear = el('button', null, 'Clear'); clear.onclick = () => { picked.clear(); renderCreateBar(); route(); }; bar.append(name, create, clear); createBar.appendChild(bar); }; app.appendChild(createBar); const searchForm = el('form', 'form-row'); const q = el('input'); q.placeholder = 'Search feeds — e.g. astronomy, art, science…'; q.setAttribute('aria-label', 'Search Bluesky feeds'); q.style.cssText = 'flex:1;min-width:0'; const go = el('button', 'primary', 'Search'); go.type = 'submit'; searchForm.append(q, go); app.appendChild(searchForm); const results = el('div'); app.appendChild(results); const feedRow = (f) => { const li = el('li', 'card frosted'); li.style.cssText = 'list-style:none;display:flex;gap:0.5rem;align-items:stretch'; const open = el('button', null); open.style.cssText = 'flex:1;min-width:0;text-align:left;border:none;padding:0;min-height:0'; open.appendChild(el('div', 'board-name', f.displayName ?? 'Untitled feed')).style.fontSize = '1.05rem'; if (f.description) open.appendChild(el('div', 'muted small', f.description)); open.appendChild(el('div', 'board-stats', (f.creator?.handle ? `by @${f.creator.handle}` : '') + (typeof f.likeCount === 'number' ? ` · ${f.likeCount.toLocaleString()} likes` : ''))); open.onclick = () => renderFeedView(f); li.appendChild(open); if (session) { const pick = el('button', null, picked.has(f.uri) ? '✓' : '☐'); pick.title = picked.has(f.uri) ? 'Remove from the new tab' : 'Include in a new tab'; pick.setAttribute('aria-pressed', picked.has(f.uri) ? 'true' : 'false'); pick.onclick = () => { if (picked.has(f.uri)) picked.delete(f.uri); else if (picked.size < 10) picked.add(f.uri); pick.textContent = picked.has(f.uri) ? '✓' : '☐'; pick.setAttribute('aria-pressed', picked.has(f.uri) ? 'true' : 'false'); renderCreateBar(); }; li.appendChild(pick); } const save = el('button', null, isSaved(f.uri) ? '✓' : '+'); save.title = isSaved(f.uri) ? 'Remove from your homepage tabs' : 'Save as a tab on the homepage'; save.setAttribute('aria-pressed', isSaved(f.uri) ? 'true' : 'false'); if (!session) { save.disabled = true; save.title = 'Sign in to save feeds'; } save.onclick = () => { const cur = savedFeedsRead(); if (cur.some((x) => x.uri === f.uri)) savedFeedsWrite(cur.filter((x) => x.uri !== f.uri)); else savedFeedsWrite([...cur, { uri: f.uri, displayName: f.displayName ?? 'Untitled feed', creatorHandle: f.creator?.handle }]); route(); }; li.appendChild(save); return li; }; const renderList = (title, feeds) => { results.textContent = ''; results.appendChild(el('h2', null, title)); if (!feeds.length) { results.appendChild(el('p', 'muted', 'No feeds matched. Try another phrase.')); return; } const ul = el('ul'); ul.style.cssText = 'margin:0;padding:0;display:flex;flex-direction:column;gap:0.75rem'; for (const f of feeds) ul.appendChild(feedRow(f)); results.appendChild(ul); }; const renderFeedView = async (f) => { results.textContent = ''; results.appendChild(el('h2', null, f.displayName ?? 'Untitled feed')); if (f.description) results.appendChild(el('p', 'muted', f.description)); results.appendChild(el('p', 'muted small', (f.creator?.handle ? `by @${f.creator.handle}` : '') + (typeof f.likeCount === 'number' ? ` · ${f.likeCount.toLocaleString()} likes` : '') + ' · live from Bluesky')); results.appendChild(el('p', 'muted center pad', 'Loading…')); try { const r = await bskyQuery('app.bsky.feed.getFeed', { feed: f.uri, limit: 30 }); results.querySelector('p.muted.center')?.remove(); const batch = (r.feed ?? []).flatMap((it) => it.post ? [it.reason ? { ...it.post, reason: it.reason } : it.post] : []); if (!batch.length) { results.appendChild(el('p', 'muted center pad', 'This feed is quiet right now.')); return; } const ul = el('ul'); ul.style.cssText = 'margin:0;padding:0;display:flex;flex-direction:column;gap:0.75rem'; for (const fp of batch) ul.appendChild(feedPostCard(fp)); results.appendChild(ul); } catch (e) { results.textContent = ''; results.appendChild(errorCard('Could not load this feed from Bluesky: ' + e.message)); } }; searchForm.onsubmit = async (e) => { e.preventDefault(); const query = q.value.trim(); if (!query) return; go.disabled = true; go.textContent = 'Searching…'; try { const r = await bskyQuery('app.bsky.unspecced.getPopularFeedGenerators', { query, limit: 30 }); renderList('Matching feeds', r.feeds ?? []); } catch { renderList('Matching feeds', []); } finally { go.disabled = false; go.textContent = 'Search'; } }; renderCreateBar(); results.appendChild(el('p', 'muted center pad', 'Loading…')); try { const r = await bskyQuery('app.bsky.feed.getSuggestedFeeds', { limit: 50 }) .catch(() => bskyQuery('app.bsky.unspecced.getPopularFeedGenerators', { limit: 50 })); renderList('Explore feeds', r.feeds ?? []); } catch (e) { results.textContent = ''; results.appendChild(errorCard('Could not load feeds from Bluesky: ' + e.message)); } } function backBar() { const b = el('button', 'backbar', '← Home'); b.type = 'button'; b.onclick = () => { location.hash = '#/'; }; return b; } // ---------- router ---------- // Pull-to-refresh: only on pages whose content is a Bluesky feed, where a // fresh pull genuinely fetches new data (route() already refetches these // cleanly, same as clicking the banner on #/). function isPullRefreshablePage() { const h = location.hash || '#/'; if (h === '#/following' || h === '#/feeds') return true; if (h === '#/') { try { return ['following', 'feeds'].includes(localStorage.getItem('asteri:lastTab')); } catch { return false; } } return false; } function setupPullToRefresh() { const indicator = document.getElementById('ptrIndicator'); if (!indicator) return; const THRESHOLD = 70; let startY = 0, pulling = false, refreshing = false; window.addEventListener('touchstart', (e) => { if (refreshing || !isPullRefreshablePage() || window.scrollY > 0) { pulling = false; return; } startY = e.touches[0].clientY; pulling = true; }, { passive: true }); window.addEventListener('touchmove', (e) => { if (!pulling || refreshing) return; const dy = e.touches[0].clientY - startY; if (dy <= 0) { indicator.style.transform = 'translate(-50%, -100%)'; return; } const dist = Math.min(dy * 0.5, 80); indicator.style.transform = `translate(-50%, ${dist - 36}px)`; indicator.classList.toggle('spin', dist >= THRESHOLD); }, { passive: true }); window.addEventListener('touchend', () => { if (!pulling || refreshing) { pulling = false; return; } pulling = false; const shownPx = parseFloat((indicator.style.transform.match(/,\s*(-?\d+(?:\.\d+)?)px\)/) || [0, -36])[1]); if (shownPx >= 0) { refreshing = true; indicator.classList.add('spin'); indicator.style.transform = 'translate(-50%, 8px)'; Promise.resolve(route()).finally(() => { refreshing = false; indicator.classList.remove('spin'); indicator.style.transform = 'translate(-50%, -100%)'; }); } else { indicator.style.transform = 'translate(-50%, -100%)'; indicator.classList.remove('spin'); } }); } async function route() { const h = location.hash || '#/'; window.scrollTo(0, 0); const board = h.match(/^#\/boards?\/([a-z0-9-]+)$/); const post = h.match(/^#\/post\/([A-Za-z0-9._-]+)$/); const commentLink = h.match(/^#\/post\/([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+)$/); const user = h.match(/^#\/user\/(did:[a-z0-9:]+)$/); const search = h.match(/^#\/search\/(.+)$/); // Post pages carry their own board-named back link — no '← Home' there. const isPost = !!(post || commentLink); const needsBack = !isPost && (!!(user || search) || ['#/feeds', '#/following', '#/lists', '#/notifications', '#/media', '#/members', '#/mod'].includes(h)); try { if (commentLink) await viewPost(commentLink[1], commentLink[2]); else if (h === '#/feeds') await viewFeedsPage(); else if (h === '#/following') { app.textContent = ''; app.appendChild(el('h1', null, 'Following')); app.appendChild(el('p', 'muted', 'The latest posts from the people you follow on Bluesky.')); await renderFollowingInto(app); } else if (h === '#/lists') { app.textContent = ''; await renderListsInto(app); } else if (board) await viewBoard(board[1]); else if (post) await viewPost(post[1]); else if (user) await viewMember(user[1]); else if (search) await viewSearch(decodeURIComponent(search[1])); else if (h === '#/topics') await viewHome('topics'); else if (h === '#/asteri') await viewHome('asteri'); else if (h === '#/spaces') await viewHome('spaces'); else if (h === '#/notifications') await viewNotifications(); else if (h === '#/media') await viewMedia(); else if (h === '#/members') await viewMembers(); else if (h === '#/mod') await viewMod(); else await viewHome(); if (needsBack && app.firstChild && !app.querySelector('.backbar')) app.prepend(backBar()); } catch (e) { viewError(e.message); } } // ---------- boot ---------- (async () => { try { await bootAuth(); } catch (e) { toast('Sign-in setup failed: ' + e.message); } window.addEventListener('hashchange', route); setupPullToRefresh(); window.addEventListener('asteri:compose', () => { if (composeOpener) composeOpener(); }); // Banner title refreshes the current view (only the text area is clickable). const bannerLink = document.getElementById('bannerLink'); if (bannerLink) bannerLink.onclick = (e) => { e.preventDefault(); const h = location.hash || '#/'; if (h === '#/') { route(); return; } const postMatch = h.match(/^#\/post\/([A-Za-z0-9._-]+)(?:\/[A-Za-z0-9._-]+)?$/); if (postMatch && currentPostBoard) { location.hash = '#/boards/' + currentPostBoard; return; } const boardMatch = h.match(/^#\/boards?\/([a-z0-9-]+)$/); if (boardMatch || postMatch) { location.hash = '#/'; return; } location.hash = '#/'; }; await route(); })();