Something went wrong. Try again.
Mirror of https://github.com/kualta/site — web infrastructure
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284import CommentMedia from "./CommentMedia";import type { ComposerAttachment } from "@/lib/bluesky/media";import { blueskyProfileUrl } from "@/lib/bluesky/urls";import { AppBskyFeedPost } from "@atproto/api";import { useEffect, useRef, useState, useSyncExternalStore } from "react";import BlueskyComposer from "./BlueskyComposer";import { getBlueskyAgent, getBlueskyAuthSnapshot, getBlueskyAuthServerSnapshot, subscribeBlueskyAuth,} from "@/lib/bluesky/auth";import { publishArticleComment, linksToArticle, commentUrl, loadArticleComments, mergeComments, publicCommentsAgent, type CommentPost,} from "@/lib/bluesky/comments";import "@/styles/article-comments.css";
export default function ArticleComments({ url, title }: { url: string; title: string }) { const auth = useSyncExternalStore(subscribeBlueskyAuth, getBlueskyAuthSnapshot, getBlueskyAuthServerSnapshot); const [posts, setPosts] = useState<CommentPost[]>([]); const [cursor, setCursor] = useState<string>(); const [loading, setLoading] = useState(true); const [error, setError] = useState(""); const [notice, setNotice] = useState(""); const [text, setText] = useState(""); const [images, setImages] = useState<ComposerAttachment[]>([]); const [parent, setParent] = useState<CommentPost>(); const [publishing, setPublishing] = useState(false); const [deleting, setDeleting] = useState<string>(); const deleted = useRef(new Set<string>()); const pending = useRef(new Map<string, CommentPost>()); const textarea = useRef<HTMLTextAreaElement>(null); const generation = useRef(0); const submitting = useRef(false);
const draftKey = `bluesky-comment-draft:${url}`; useEffect(() => { try { setText(sessionStorage.getItem(draftKey) ?? ""); } catch { /* Storage may be unavailable. */ } }, [draftKey]);
function updateDraft(value: string) { setText(value); try { if (value) sessionStorage.setItem(draftKey, value); else sessionStorage.removeItem(draftKey); } catch { /* Keep the editable draft in memory. */ } }
async function load(more = false) { const request = ++generation.current; setLoading(true); setError(""); try { const result = await loadArticleComments(auth.agent ?? publicCommentsAgent, url, more ? cursor : undefined); if (request !== generation.current) return; for (const post of result.posts) pending.current.delete(post.uri); const incoming = mergeComments( [...pending.current.values()].filter((post) => linksToArticle(post, url)), result.posts, ); setPosts((previous) => (more ? mergeComments(previous, incoming) : incoming).filter((post) => !deleted.current.has(post.uri)), ); setCursor(result.cursor); if (result.incomplete) setError("Some replies could not load. Retry loading to try again."); } catch { if (request === generation.current) setError("Comments could not load from Bluesky. Please try again."); } finally { if (request === generation.current) setLoading(false); } } useEffect(() => { setPosts([]); setParent(undefined); setCursor(undefined); void load(); return () => { generation.current += 1; }; }, [url, auth.agent]);
async function publish(event: React.FormEvent) { event.preventDefault(); if (submitting.current) return; submitting.current = true; setPublishing(true); setError(""); setNotice(""); try { const agent = await getBlueskyAgent(); if (!agent || !auth.profile) throw new Error("Sign in to Bluesky before posting."); const result = await publishArticleComment(agent, text, url, title, parent, images); const { record } = result; // The successful repo write is authoritative, even before search indexing catches up. const published: CommentPost = { uri: result.uri, cid: result.cid, record, author: auth.profile, indexedAt: record.createdAt, }; pending.current.set(published.uri, published); setPosts((previous) => mergeComments([published], previous)); updateDraft(""); setImages([]); if (images.length) void agent .getPosts({ uris: [result.uri] }) .then(({ data }) => { const hydrated = data.posts[0]; if (hydrated) { pending.current.set(hydrated.uri, hydrated); setPosts((previous) => mergeComments( [hydrated], previous.filter((post) => post.uri !== hydrated.uri), ), ); } }) .catch(() => { /* The published record is already available; media may still be processing. */ }); setParent(undefined); } catch (cause) { setError(cause instanceof Error ? cause.message : "Your comment could not be posted. Try again."); } finally { submitting.current = false; setPublishing(false); } }
async function deleteComment(post: CommentPost) { if (deleting || !window.confirm("Delete this comment from Bluesky? This cannot be undone.")) return; setDeleting(post.uri); setError(""); try { const agent = await getBlueskyAgent(); if (!agent || auth.profile?.did !== post.author.did) throw new Error("Sign in as the author to delete this comment."); await agent.deletePost(post.uri); deleted.current.add(post.uri); pending.current.delete(post.uri); setPosts((previous) => previous.filter((candidate) => candidate.uri !== post.uri)); if (parent?.uri === post.uri) setParent(undefined); setNotice("Comment deleted from Bluesky."); } catch (cause) { setError(cause instanceof Error ? cause.message : "Could not delete this comment."); } finally { setDeleting(undefined); } }
return ( <section className="article-comments" aria-label="Comments"> <BlueskyComposer mediaTextSuffix={url} images={images} onImagesChange={setImages} text={text} onChange={updateDraft} onSubmit={publish} busy={publishing} label={parent ? "Your reply" : "Your comment"} placeholder={`Comment on ${title}`} loginLabel="Log in to comment" submitLabel={parent ? "Reply" : "Comment"} textareaRef={textarea} context={ parent && ( <div className="comment-reply-context"> Replying to @{parent.author.handle}{" "} <button type="button" className="comments-text-button" onClick={() => setParent(undefined)}> Cancel reply </button> </div> ) } /> {error && ( <p role="alert" className="comment-error"> {error}{" "} <button type="button" className="comments-text-button" onClick={() => void load()} disabled={loading}> Retry loading </button> </p> )} {notice && ( <p role="status" className="comments-description"> {notice} </p> )} <div className="comments-list" aria-busy={loading}> {posts.map((post) => { const record = AppBskyFeedPost.isRecord(post.record) ? (post.record as AppBskyFeedPost.Record) : null; if (!record) return null; const replyTo = record.reply?.parent.uri; const parentPost = posts.find((candidate) => candidate.uri === replyTo); return ( <article key={post.uri} className="article-comment"> <div className="comment-author-row"> <a href={blueskyProfileUrl(post.author.did)} target="_blank" rel="noopener noreferrer" className="comment-author" > {post.author.avatar && <img src={post.author.avatar} width={28} height={28} alt="" loading="lazy" />} <span> {post.author.displayName || post.author.handle}{" "} <span className="comment-handle">@{post.author.handle}</span> </span> </a> <a href={commentUrl(post)} target="_blank" rel="noopener noreferrer" className="comment-date"> <time dateTime={record.createdAt}> {new Date(record.createdAt).toLocaleDateString(undefined, { month: "short", day: "numeric", year: "numeric", })} </time> </a> </div> {parentPost && <p className="comment-reply-context">Reply to @{parentPost.author.handle}</p>} <p className="comment-body">{record.text}</p> <CommentMedia post={post} /> <div className="comment-actions"> {auth.agent && !post.viewer?.replyDisabled && ( <button type="button" className="comments-text-button" onClick={() => { setParent(post); textarea.current?.focus(); textarea.current?.scrollIntoView({ block: "center", behavior: "smooth" }); }} > Reply </button> )} <a href={commentUrl(post)} target="_blank" rel="noopener noreferrer"> View on Bluesky </a> {auth.profile?.did === post.author.did && ( <button type="button" className="comments-text-button" onClick={() => void deleteComment(post)} disabled={Boolean(deleting)} > {deleting === post.uri ? "Deleting…" : "Delete"} </button> )} </div> </article> ); })} </div> {cursor && ( <button type="button" className="comments-text-button comments-load-more" onClick={() => void load(true)} disabled={loading} > Load more conversations </button> )} </section> );}