3dom4wf7p: Publish public text posts from a feed composer

This commit is contained in:
2026-10-19 14:19:12 -06:00
parent 28037a2849
commit de535a500d
8 changed files with 404 additions and 0 deletions
+26
View File
@@ -0,0 +1,26 @@
import { NextResponse, type NextRequest } from "next/server";
import { SESSION_COOKIE } from "@/lib/cookie";
import { createTextPost } from "@/lib/post-create";
// POST /api/posts { content }
// Creates a public text draft on the feed, then publishes it. Returns { id }.
// The create call can report status "draft" for a post already on the home
// feed, so the browser reloads the first page and confirms the id there.
// 401 { error: "sign_in" } without a session.
export const runtime = "nodejs";
export async function POST(req: NextRequest) {
const sessionId = req.cookies.get(SESSION_COOKIE)?.value;
let content: unknown = null;
try {
content = ((await req.json()) as { content?: unknown }).content;
} catch {
content = null;
}
const result = await createTextPost(sessionId, content);
if (!result.ok) {
return NextResponse.json({ error: result.error }, { status: result.status });
}
return NextResponse.json({ id: result.id });
}
+5
View File
@@ -42,3 +42,8 @@ button:disabled { opacity: .5; cursor: not-allowed; }
.like-btn:disabled:not(.liked) { color: var(--grey); }
.like-error { color: #a8141b; font-size: 13px; align-self: center; }
.post-stats { align-items: center; }
.composer { background: #fff; border: 1px solid var(--line); border-radius: 0; padding: 16px; display: flex; flex-direction: column; gap: 8px; }
.composer-label { margin: 0; }
.composer textarea { font: inherit; width: 100%; padding: 12px; border: 1px solid #999; border-radius: 0; resize: vertical; background: #fff; color: var(--ink); }
.composer textarea:focus-visible { outline: 2px solid var(--ink); outline-offset: 2px; }
.composer .composer-post { align-self: flex-end; margin: 0; padding: 10px 24px; border-radius: 0; }
+36
View File
@@ -0,0 +1,36 @@
import type { FormEvent } from "react";
export interface ComposerProps {
value: string;
busy: boolean;
error: boolean;
onChange: (value: string) => void;
onSubmit: () => void;
}
export function Composer({ value, busy, error, onChange, onSubmit }: ComposerProps) {
const empty = value.trim().length === 0;
function submit(e: FormEvent) {
e.preventDefault();
if (!empty && !busy) onSubmit();
}
return (
<form className="composer" onSubmit={submit}>
<label htmlFor="composer-text" className="composer-label">New post</label>
<textarea
id="composer-text"
value={value}
rows={3}
placeholder="Share something with the feed"
disabled={busy}
onChange={(e) => onChange(e.target.value)}
/>
{error ? (
<p className="error" role="alert">Publishing the post failed. Your text is still here.</p>
) : null}
<button type="submit" className="composer-post" disabled={empty || busy}>
{busy ? "Posting" : "Post"}
</button>
</form>
);
}
+33
View File
@@ -4,6 +4,7 @@ import { useCallback, useEffect, useRef, useState } from "react";
import { fetchFeedPage, FeedLoadError } from "@/lib/feed-client";
import { applyLikeOutcome, LikeError, sendLike } from "@/lib/like-client";
import { mergePosts, toCardPosts, type CardPost } from "@/lib/feed-model";
import { PostError, publishAndConfirm } from "@/lib/post-client";
import { FeedView, type FeedStatus } from "./FeedView";
const POLL_MS = 45_000;
@@ -17,6 +18,12 @@ export function Feed({ onSignedOut }: { onSignedOut: () => void }) {
const [pending, setPending] = useState<CardPost[]>([]);
const [likeBusy, setLikeBusy] = useState<ReadonlySet<string>>(new Set());
const [likeErrors, setLikeErrors] = useState<ReadonlySet<string>>(new Set());
const [draft, setDraft] = useState("");
const [posting, setPosting] = useState(false);
const [postFailed, setPostFailed] = useState(false);
// Id of a post already created but not yet seen on the first page. A retry
// re-checks the feed instead of creating a duplicate.
const unconfirmed = useRef<{ id: string | null }>({ id: null });
const sentinel = useRef<HTMLDivElement | null>(null);
const busy = useRef(false);
const shown = useRef<Set<string>>(new Set());
@@ -149,6 +156,31 @@ export function Feed({ onSignedOut }: { onSignedOut: () => void }) {
[fail],
);
const publish = useCallback(async () => {
const text = draft.trim();
if (!text || posting) return;
setPosting(true);
setPostFailed(false);
try {
const page = await publishAndConfirm(text, unconfirmed.current);
setPosts(mergePosts(toCardPosts(page.items)));
setNextCursor(page.nextCursor);
setPending([]);
setDraft("");
} catch (e) {
if (e instanceof PostError && e.signedOut) onSignedOut();
setPostFailed(true);
} finally {
setPosting(false);
}
}, [draft, posting, onSignedOut]);
function changeDraft(v: string) {
// New text is a new post; forget a stale unconfirmed id.
if (v !== draft) unconfirmed.current = { id: null };
setDraft(v);
}
function showNew() {
setPosts((cur) => mergePosts(cur, pending));
setPending([]);
@@ -167,6 +199,7 @@ export function Feed({ onSignedOut }: { onSignedOut: () => void }) {
onToggleLike={(p) => void toggleLike(p)}
likeBusy={likeBusy}
likeErrors={likeErrors}
composer={{ value: draft, busy: posting, error: postFailed, onChange: changeDraft, onSubmit: () => void publish() }}
sentinelRef={sentinel}
/>
);
+3
View File
@@ -1,5 +1,6 @@
import type { Ref } from "react";
import type { CardPost } from "@/lib/feed-model";
import { Composer, type ComposerProps } from "./Composer";
import { PostCard } from "./PostCard";
export type FeedStatus = "loading" | "ready" | "error";
@@ -15,6 +16,7 @@ export interface FeedViewProps {
onToggleLike?: (post: CardPost) => void;
likeBusy?: ReadonlySet<string>;
likeErrors?: ReadonlySet<string>;
composer?: ComposerProps;
sentinelRef?: Ref<HTMLDivElement>;
now?: number;
}
@@ -45,6 +47,7 @@ export function FeedView(p: FeedViewProps) {
}
return (
<section className="feed">
{p.composer ? <Composer {...p.composer} /> : null}
{p.newCount > 0 ? (
<button type="button" className="new-posts" onClick={p.onShowNew}>
{p.newCount === 1 ? "1 new post" : `${p.newCount} new posts`}
+80
View File
@@ -0,0 +1,80 @@
// Browser-side text-post publishing. The composer text is only cleared after
// the new post id shows up on the reloaded first page of the home feed.
import { fetchFeedPage, FeedLoadError, type FeedPage } from "./feed-client";
export class PostError extends Error {
constructor(public readonly signedOut: boolean) {
super(signedOut ? "sign_in" : "publish_failed");
}
}
export async function sendPost(content: string, fetchImpl: typeof fetch = fetch): Promise<string> {
let res: Response;
try {
res = await fetchImpl("/api/posts", {
method: "POST",
credentials: "same-origin",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content }),
});
} catch {
throw new PostError(false);
}
if (res.status === 401) throw new PostError(true);
if (!res.ok) throw new PostError(false);
try {
const b = (await res.json()) as { id?: unknown };
if ((typeof b.id === "string" && b.id) || typeof b.id === "number") return String(b.id);
} catch {
/* fall through */
}
throw new PostError(false);
}
function pageHasPost(page: FeedPage, id: string): boolean {
return page.items.some((item) => {
const post = (item as { post?: { id?: unknown } } | null)?.post;
return post != null && String(post.id) === id;
});
}
/**
* Reload the first page. Returns the page when it holds the post id, else null.
* Throws PostError when the person is signed out or the reload fails.
*/
export async function confirmOnFirstPage(
id: string,
fetchPage: (cursor: string | null) => Promise<FeedPage> = fetchFeedPage,
): Promise<FeedPage | null> {
try {
const page = await fetchPage(null);
return pageHasPost(page, id) ? page : null;
} catch (e) {
throw new PostError(e instanceof FeedLoadError && e.signedOut);
}
}
export interface PublishDeps {
send?: (content: string) => Promise<string>;
fetchPage?: (cursor: string | null) => Promise<FeedPage>;
}
/**
* Publish text and confirm it on the reloaded first page. Returns that page
* only when the post id is on it. `unconfirmed` holds an id that was created
* earlier but not yet seen, so a retry re-checks the feed and does not create
* a duplicate. Throws PostError otherwise; the caller keeps the composer text.
*/
export async function publishAndConfirm(
content: string,
unconfirmed: { id: string | null },
deps: PublishDeps = {},
): Promise<FeedPage> {
const id = unconfirmed.id ?? (await (deps.send ?? sendPost)(content));
unconfirmed.id = id;
const page = await confirmOnFirstPage(id, deps.fetchPage);
if (!page) throw new PostError(false);
unconfirmed.id = null;
return page;
}
+94
View File
@@ -0,0 +1,94 @@
import { FEED_BASE_URL } from "./env";
import { ensureFreshSession, refreshSession } from "./session-refresh";
// Text-post creation proxy. Two feed calls with the person's server-held feed
// token: create a public draft, then publish it with the same content. Neither
// the token nor the post text is logged.
export type CreatePostResult =
| { ok: true; id: string; status: string | null }
| { ok: false; status: 400 | 401 | 502; error: "sign_in" | "empty_post" | "post_failed" };
interface CreateOptions {
fetchImpl?: typeof fetch;
now?: number;
}
export const MAX_POST_LENGTH = 20_000;
function rec(v: unknown): Record<string, unknown> {
return v && typeof v === "object" && !Array.isArray(v) ? (v as Record<string, unknown>) : {};
}
function readCreated(body: unknown): { id: string; status: string | null } | null {
const root = rec(body);
const data = rec(root.data);
const post = rec(data.post);
for (const v of [data.id, post.id, root.id]) {
if ((typeof v === "string" && v) || typeof v === "number") {
const status = [data.status, post.status, root.status].find((s) => typeof s === "string");
return { id: String(v), status: (status as string | undefined) ?? null };
}
}
return null;
}
function send(token: string, path: string, payload: unknown, doFetch: typeof fetch) {
return doFetch(`${FEED_BASE_URL}${path}`, {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
},
body: JSON.stringify(payload),
});
}
export async function createTextPost(
sessionId: string | undefined,
content: unknown,
options: CreateOptions = {},
): Promise<CreatePostResult> {
const signIn = { ok: false, status: 401, error: "sign_in" } as const;
const failed = { ok: false, status: 502, error: "post_failed" } as const;
const doFetch = options.fetchImpl ?? fetch;
let session = await ensureFreshSession(sessionId, options);
if (!session || !sessionId) return signIn;
if (typeof content !== "string" || !content.trim() || content.length > MAX_POST_LENGTH) {
return { ok: false, status: 400, error: "empty_post" };
}
// One call with a single refresh-and-retry on a 401 token rejection.
const call = async (path: string, payload: unknown): Promise<Response | "sign_in"> => {
let res = await send(session!.feedAccessToken, path, payload, doFetch);
if (res.status === 401) {
session = await refreshSession(sessionId, options);
if (!session) return "sign_in";
res = await send(session.feedAccessToken, path, payload, doFetch);
if (res.status === 401) return "sign_in";
}
return res;
};
try {
const created = await call("/api/v1/posts", {
content,
type: "text",
status: "draft",
visibility: "public",
});
if (created === "sign_in") return signIn;
if (created.status !== 200 && created.status !== 201) return failed;
const info = readCreated(await created.json().catch(() => null));
if (!info) return failed;
const published = await call(`/api/v1/posts/${encodeURIComponent(info.id)}/publish`, { content });
if (published === "sign_in") return signIn;
if (published.status < 200 || published.status > 299) return failed;
return { ok: true, id: info.id, status: info.status };
} catch {
return failed;
}
}