import { AppBskyRichtextFacet, RichText } from "@atproto/api"; import { TID } from "@atproto/common-web"; import { useAtom } from "jotai"; import { Dialog, Switch } from "radix-ui"; import { useEffect, useRef, useState } from "react"; import { useAuth } from "~/providers/UnifiedAuthProvider"; import { composerAtom } from "~/utils/atoms"; import { useQueryPost } from "~/utils/useQuery"; import { ProfileThing } from "./Login"; import { useOGGenerator } from "./OGPoll"; import { UniversalPostRendererATURILoader } from "./UniversalPostRenderer"; const MAX_POST_LENGTH = 300; // Helper to calculate expiry dates const addHours = (date: Date, h: number) => { const newDate = new Date(date); newDate.setTime(newDate.getTime() + h * 60 * 60 * 1000); return newDate; }; export function Composer() { const { generate, element: generatorElement } = useOGGenerator(); const [composerState, setComposerState] = useAtom(composerAtom); const { agent } = useAuth(); const [postText, setPostText] = useState(""); const [posting, setPosting] = useState(false); const [postSuccess, setPostSuccess] = useState(false); const [postError, setPostError] = useState(null); // Poll State const [showPoll, setShowPoll] = useState(false); const [pollData, setPollData] = useState({ a: "", b: "", c: "", d: "", duration: "24", expiry: addHours(new Date(), 24), }); useEffect(() => { // Reset Everything on Open/Close setPostText(""); setPosting(false); setPostSuccess(false); setPostError(null); setShowPoll(false); setPollData({ a: "", b: "", c: "", d: "", duration: "24", expiry: addHours(new Date(), 24), }); }, [composerState.kind]); const parentUri = composerState.kind === "reply" ? composerState.parent : composerState.kind === "quote" ? composerState.subject : undefined; const { data: parentPost, isLoading: isParentLoading } = useQueryPost(parentUri); async function handlePost() { if (!agent || !postText.trim() || postText.length > MAX_POST_LENGTH) return; setPosting(true); setPostError(null); try { const rkey = TID.nextStr(); const rt = new RichText({ text: postText }); await rt.detectFacets(agent); if (rt.facets?.length) { rt.facets = rt.facets.filter((item) => { if (item.$type !== "app.bsky.richtext.facet") return true; if (!item.features?.length) return true; item.features = item.features.filter((feature) => { if (feature.$type !== "app.bsky.richtext.facet#mention") return true; const did = feature.$type === "app.bsky.richtext.facet#mention" ? (feature as AppBskyRichtextFacet.Mention)?.did : undefined; return typeof did === "string" && did.startsWith("did:"); }); return item.features.length > 0; }); } let uploadedPollImageBlob = null; // Only generate if we actually have poll data AND the user wants a poll if (showPoll && pollData.a && pollData.b) { // A. Generate the Base64 Data URL using the Client-Side Generator const dataUrl = await generate({ a: pollData.a, b: pollData.b, c: pollData.c || undefined, d: pollData.d || undefined, expiry: pollData.expiry, multiple: true, }); if (dataUrl) { // B. Convert DataURL to Blob const blob = await fetch(dataUrl).then((res) => res.blob()); // C. Upload Blob to Bluesky/ATProto PDS const { data } = await agent.uploadBlob(blob, { encoding: "image/png", }); uploadedPollImageBlob = data.blob; } } const record: Record = { $type: "app.bsky.feed.post", text: rt.text, facets: rt.facets, createdAt: new Date().toISOString(), }; let externalEmbed = null; // todo get real way of doing this better getting domain const domain = window.location.hostname; if (uploadedPollImageBlob) { externalEmbed = { $type: "app.bsky.embed.external", external: { uri: `https://${domain}/profile/${agent.did}/post/${rkey}`, // Todo: update to your actual poll viewer URL title: "Poll created by " + agent.did, description: "Click to participate in this poll", thumb: uploadedPollImageBlob, }, }; } // Handle Replies if (composerState.kind === "reply" && parentPost) { record.reply = { root: parentPost.value?.reply?.root ?? { uri: parentPost.uri, cid: parentPost.cid, }, parent: { uri: parentPost.uri, cid: parentPost.cid, }, }; } // Handle Quotes + Embeds if (composerState.kind === "quote" && parentPost) { const quoteEmbed = { $type: "app.bsky.embed.record", record: { uri: parentPost.uri, cid: parentPost.cid }, }; if (externalEmbed) { record.embed = { $type: "app.bsky.embed.recordWithMedia", media: externalEmbed, record: quoteEmbed, }; } else { record.embed = quoteEmbed; } } else if (externalEmbed) { record.embed = externalEmbed; } const postResponse = await agent.com.atproto.repo.createRecord({ collection: "app.bsky.feed.post", repo: agent.assertDid, record, rkey: rkey, }); // Create poll embed record if poll data exists if (showPoll && pollData.a && pollData.b) { const pollRecord = { $type: "app.reddwarf.embed.poll", subject: { $type: "com.atproto.repo.strongRef", uri: `at://${agent.assertDid}/app.bsky.feed.post/${rkey}`, cid: postResponse.data.cid, }, a: pollData.a, b: pollData.b, c: pollData.c || undefined, d: pollData.d || undefined, multiple: true, createdAt: new Date().toISOString(), }; try { await agent.com.atproto.repo.createRecord({ collection: "app.reddwarf.embed.poll", repo: agent.assertDid, record: pollRecord, rkey: rkey, }); } catch (pollError) { console.error("Failed to create poll embed record:", pollError); // Don't fail the entire post if poll record creation fails } } setPostSuccess(true); setPostText(""); setTimeout(() => { setPostSuccess(false); setComposerState({ kind: "closed" }); }, 1500); } catch (e: any) { setPostError(e?.message || "Failed to post"); } finally { setPosting(false); } } const getPlaceholder = () => { switch (composerState.kind) { case "reply": return "Post your reply"; case "quote": return "Add a comment..."; case "root": default: return "What's happening?!"; } }; const charsLeft = MAX_POST_LENGTH - postText.length; // Disable if empty text OR if poll is active but only 1 option is filled const isPollInvalid = showPoll && (!pollData.a || !pollData.b); const isPostButtonDisabled = posting || !postText.trim() || isParentLoading || charsLeft < 0 || isPollInvalid; return ( <> { if (!open) setComposerState({ kind: "closed" }); }} >
{/* HEADER */}
{charsLeft}
{/* BODY */} {postSuccess ? (
✓ Posted!
) : (
{/* REPLY CONTEXT */} {composerState.kind === "reply" && (
{isParentLoading ? (
Loading parent post...
) : parentUri ? ( ) : null}
)}
setPostText(e.target.value)} disabled={posting} autoFocus />
{/* QUOTE CONTEXT */} {composerState.kind === "quote" && (
{isParentLoading ? (
Loading parent post...
) : parentUri ? ( ) : null}
)} {/* POLL FORM */}
{showPoll && ( )}
{/* TOOLS BAR (Switch) */}
Create a Poll
{postError && (
{postError}
)}
)}
{generatorElement} ); } /** * Poll Creation Form * Follows Material Design 3 spacing and filled input styles */ function PollCreator({ data, onChange, disabled, }: { data: any; onChange: any; disabled: boolean; }) { const handleChange = (field: string, val: string) => { onChange((prev: any) => ({ ...prev, [field]: val })); }; // const handleDuration = (val: string) => { // const hours = parseInt(val, 10); // onChange((prev: any) => ({ // ...prev, // duration: val, // expiry: addHours(new Date(), hours), // })); // }; return (
{/* Option A */}
handleChange("a", e.target.value)} disabled={disabled} />
{/* Option B */}
handleChange("b", e.target.value)} disabled={disabled} />
{/* Option C */}
handleChange("c", e.target.value)} disabled={disabled} />
{/* Option D */}
handleChange("d", e.target.value)} disabled={disabled} />
{/*
*/}
); } function AutoGrowTextarea({ value, className, onChange, ...props }: React.DetailedHTMLProps< React.TextareaHTMLAttributes, HTMLTextAreaElement >) { const ref = useRef(null); useEffect(() => { const el = ref.current; if (!el) return; el.style.height = "auto"; el.style.height = el.scrollHeight + "px"; }, [value]); return (