'use client'; import { useEffect, useRef, useState } from 'react'; import Image from 'next/image'; interface Reply { uri: string; author: { did: string; handle: string; displayName?: string; avatar?: string; }; record: { text: string; createdAt: string; facets?: Facet[]; }; likeCount?: number; } interface ParentPost { uri: string; author: Reply['author']; record: Reply['record']; likeCount: number; repostCount: number; replyCount: number; } interface Facet { index: { byteStart: number; byteEnd: number }; features: FacetFeature[]; } type FacetFeature = | { $type: 'app.bsky.richtext.facet#link'; uri: string } | { $type: 'app.bsky.richtext.facet#mention'; did: string } | { $type: string }; type LoadState = 'loading' | 'loaded' | 'error' | 'no-ref'; const PLATFORMS = [ { key: 'bluesky', name: 'Bluesky', domain: 'bsky.app' }, { key: 'blacksky', name: 'Blacksky', domain: 'blacksky.app' }, { key: 'witchsky', name: 'Witchsky', domain: 'witchsky.app' }, { key: 'mu', name: 'mu.social', domain: 'mu.social' }, ] as const; type PlatformKey = (typeof PLATFORMS)[number]['key']; interface PostCommentsProps { atUri?: string; } export function PostComments({ atUri }: PostCommentsProps) { const [replies, setReplies] = useState([]); const [parentPost, setParentPost] = useState(null); const [postUri, setPostUri] = useState(null); const [state, setState] = useState('loading'); useEffect(() => { if (!atUri) { setState('no-ref'); return; } setState('loading'); resolveComments(atUri) .then((data) => { if (!data.bskyPostRef) { setState('no-ref'); return; } setPostUri(data.bskyPostRef); setParentPost(data.parentPost); setReplies(data.replies); setState('loaded'); }) .catch(() => setState('error')); }, [atUri]); const retry = () => { setState('loading'); if (!atUri) return; resolveComments(atUri) .then((data) => { if (!data.bskyPostRef) { setState('no-ref'); return; } setPostUri(data.bskyPostRef); setParentPost(data.parentPost); setReplies(data.replies); setState('loaded'); }) .catch(() => setState('error')); }; if (state === 'no-ref') return null; if (state === 'loading') { return (
{[1, 2].map((i) => (
))}
); } if (state === 'error') { return (

Comments

Comments couldn't be loaded.{' '}

); } return (

Comments

{parentPost && } {replies.length === 0 && (

No comments yet.

)} {replies.length > 0 && (
{replies.map((reply) => ( ))}
)}
); } function PlatformButtonGroup({ postUri }: { postUri: string }) { const [platform, setPlatform] = useState('bluesky'); const [open, setOpen] = useState(false); const groupRef = useRef(null); useEffect(() => { try { const saved = localStorage.getItem('preferred-comment-platform'); if (saved && PLATFORMS.some((p) => p.key === saved)) { setPlatform(saved as PlatformKey); } } catch { // localStorage unavailable } }, []); useEffect(() => { if (!open) return; const handleClick = (e: MouseEvent) => { if (!groupRef.current?.contains(e.target as Node)) setOpen(false); }; const handleKey = (e: KeyboardEvent) => { if (e.key === 'Escape') setOpen(false); }; window.addEventListener('click', handleClick, true); window.addEventListener('keydown', handleKey); return () => { window.removeEventListener('click', handleClick, true); window.removeEventListener('keydown', handleKey); }; }, [open]); const current = PLATFORMS.find((p) => p.key === platform)!; const url = platformPostUrl(postUri, current.domain); return (
Join the conversation
{open && (
{PLATFORMS.map((p) => ( ))}
)}
); } const PLATFORM_FAVICONS: Record = { bluesky: 'https://bsky.app/static/favicon-32x32.png', blacksky: 'https://blacksky.app/favicon.ico', witchsky: 'https://witchsky.app/favicon.ico', mu: 'https://mu.social/favicon.ico', }; function PlatformIcon({ platform }: { platform: PlatformKey }) { return ( // eslint-disable-next-line @next/next/no-img-element ); } function ParentPostCard({ post }: { post: ParentPost }) { const displayName = post.author.displayName || post.author.handle; const date = new Date(post.record.createdAt); return (
{post.author.avatar && ( {displayName} )}
{displayName} @{post.author.handle}
{post.replyCount} {post.repostCount} {post.likeCount}
); } function Comment({ reply }: { reply: Reply }) { const displayName = reply.author.displayName || reply.author.handle; const date = new Date(reply.record.createdAt); return (
{reply.author.avatar && ( {displayName} )} {displayName} @{reply.author.handle}
); } function RichText({ text, facets }: { text: string; facets?: Facet[] }) { if (!facets || facets.length === 0) return <>{text}; const encoder = new TextEncoder(); const decoder = new TextDecoder(); const bytes = encoder.encode(text); const sorted = [...facets].sort((a, b) => a.index.byteStart - b.index.byteStart); const parts: React.ReactNode[] = []; let lastByte = 0; for (const facet of sorted) { if (facet.index.byteStart > lastByte) { parts.push(decoder.decode(bytes.slice(lastByte, facet.index.byteStart))); } const segment = decoder.decode(bytes.slice(facet.index.byteStart, facet.index.byteEnd)); const link = facet.features.find((f) => f.$type === 'app.bsky.richtext.facet#link') as | Extract | undefined; const mention = facet.features.find((f) => f.$type === 'app.bsky.richtext.facet#mention') as | Extract | undefined; if (link) { parts.push( {segment} , ); } else if (mention) { parts.push( {segment} , ); } else { parts.push(segment); } lastByte = facet.index.byteEnd; } if (lastByte < bytes.length) { parts.push(decoder.decode(bytes.slice(lastByte))); } return <>{parts}; } async function resolveComments(atUri: string): Promise<{ bskyPostRef: string | null; parentPost: ParentPost | null; replies: Reply[]; }> { const match = atUri.match(/^at:\/\/(did:[^/]+)\/([^/]+)\/(.+)$/); if (!match) throw new Error('Invalid AT URI'); const [, did, collection, rkey] = match; const plcRes = await fetch(`https://plc.directory/${did}`); if (!plcRes.ok) throw new Error('DID resolution failed'); const plcDoc = await plcRes.json(); const pdsEndpoint = plcDoc.service?.find( (s: { id: string; type: string; serviceEndpoint: string }) => s.id === '#atproto_pds', )?.serviceEndpoint; if (!pdsEndpoint) throw new Error('No PDS endpoint'); const recordRes = await fetch( `${pdsEndpoint}/xrpc/com.atproto.repo.getRecord?repo=${did}&collection=${collection}&rkey=${rkey}`, ); if (!recordRes.ok) throw new Error('Record fetch failed'); const recordData = await recordRes.json(); const rawRef = recordData.value?.bskyPostRef; const bskyPostRef = typeof rawRef === 'string' ? rawRef : rawRef?.uri; if (typeof bskyPostRef !== 'string') return { bskyPostRef: null, parentPost: null, replies: [] }; const threadRes = await fetch( `https://public.api.bsky.app/xrpc/app.bsky.feed.getPostThread?uri=${encodeURIComponent(bskyPostRef)}&depth=1`, ); if (!threadRes.ok) return { bskyPostRef, parentPost: null, replies: [] }; const threadData = await threadRes.json(); const threadPost = threadData.thread?.post; const parentPost: ParentPost | null = threadPost ? { uri: threadPost.uri, author: threadPost.author, record: threadPost.record, likeCount: threadPost.likeCount ?? 0, repostCount: threadPost.repostCount ?? 0, replyCount: threadPost.replyCount ?? 0, } : null; const replies: Reply[] = (threadData.thread?.replies ?? []) .filter((r: { $type: string }) => r.$type === 'app.bsky.feed.defs#threadViewPost') .map((r: { post: { uri: string; author: Reply['author']; record: Reply['record']; likeCount?: number } }) => ({ uri: r.post.uri, author: r.post.author, record: r.post.record, likeCount: r.post.likeCount, })) .sort( (a: Reply, b: Reply) => new Date(a.record.createdAt).getTime() - new Date(b.record.createdAt).getTime(), ); return { bskyPostRef, parentPost, replies }; } function platformPostUrl(atUri: string, domain: string): string { const match = atUri.match(/^at:\/\/(did:[^/]+)\/[^/]+\/(.+)$/); if (!match) return `https://${domain}`; return `https://${domain}/profile/${match[1]}/post/${match[2]}`; }