"use client"; import Link from "next/link"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { api, errorText } from "@/lib/api"; import { type ForumPost, INTENTS, REACTIONS, type ReactionKind, type ThreadPage, ago, memberHref } from "@/lib/forum"; import { signGlyphs } from "./AuthorLine"; import { Avatar } from "./Avatar"; import { Composer } from "./Composer"; import { PostBody } from "./PostBody"; import type { LiveNotice } from "./ForumNav"; import { ReactionIcon } from "./ReactionIcon"; import { ReportForm } from "./ReportButton"; import { TypingLine, useTypingSender, useTypingWatch } from "./typing"; import { Badge, RankBadge } from "./Badges"; /** How often the open thread looks for new replies (while the page is in front). */ const POLL_MS = 30_000; type Actions = { busy: boolean; react: (post: ForumPost, kind: ReactionKind | "down") => void; replyTo: (post: ForumPost) => void; edit: (post: ForumPost, body: string) => Promise; remove: (post: ForumPost) => void; restore: (post: ForumPost) => void; helped: (post: ForumPost) => void; }; function ReactionRow({ post, enabled, canDownvote, onReact, }: { post: ForumPost; enabled: boolean; canDownvote: boolean; onReact: Actions["react"]; }) { const [open, setOpen] = useState(false); const given = REACTIONS.filter((r) => post.reactions[r.kind] > 0 || post.mine === r.kind); return (
{given.map((r) => ( ))} {enabled && ( setOpen(false)} button={ } > {REACTIONS.map((r) => ( ))} )} {canDownvote && enabled && ( )}
); } /** A small menu under a button (closes on a click elsewhere or Escape). */ function Popover({ open, onClose, button, children, align = "left", }: { open: boolean; onClose: () => void; button: React.ReactNode; children: React.ReactNode; align?: "left" | "right"; }) { const box = useRef(null); useEffect(() => { if (!open) return; const outside = (e: MouseEvent) => { if (box.current && !box.current.contains(e.target as Node)) onClose(); }; const escape = (e: KeyboardEvent) => { if (e.key === "Escape") onClose(); }; document.addEventListener("mousedown", outside); document.addEventListener("keydown", escape); return () => { document.removeEventListener("mousedown", outside); document.removeEventListener("keydown", escape); }; }, [open, onClose]); return ( {button} {open && ( {children} )} ); } /** The site's own mark as an avatar (the daily sky thread). */ function SiteMark({ size }: { size: number }) { return ( ); } function PostCard({ post, page, actions, isNew, nested = false, }: { post: ForumPost; page: ThreadPage; actions: Actions; isNew: boolean; nested?: boolean; }) { const [editing, setEditing] = useState(false); const [reporting, setReporting] = useState(false); const [menu, setMenu] = useState(false); const [showCollapsed, setShowCollapsed] = useState(false); const { viewer, thread, access } = page; const writer = viewer.member !== null && !viewer.member.banned; const starter = post.author !== null && post.author.nickname === thread.author?.nickname; const canReact = writer && !post.own && !post.deleted && !thread.locked; const author = post.author; const glyphs = signGlyphs(author?.signs); const size = post.is_opening ? 40 : nested ? 26 : 32; if (post.deleted && !viewer.moderator) { return (
{post.deleted.by_moderator ? "A moderátor eltávolította ezt a hozzászólást." : "A szerző törölte ezt a hozzászólást."} {post.deleted.reason && Ok: {post.deleted.reason}}
); } const menuItems: { label: string; run: () => void; danger?: boolean }[] = []; if (!post.deleted) { if (access?.is_thread_author && !post.is_opening && !post.own && writer) { menuItems.push({ label: post.helped ? "Mégsem segített" : "Ez segített", run: () => actions.helped(post) }); } if (post.own && writer && !thread.locked) menuItems.push({ label: "Szerkesztés", run: () => setEditing(true) }); if (post.own) menuItems.push({ label: "Törlés", run: () => actions.remove(post), danger: true }); if (viewer.logged_in && !post.own) menuItems.push({ label: "Jelentés", run: () => setReporting(true) }); if (viewer.moderator && !post.own) menuItems.push({ label: "Eltávolítás", run: () => actions.remove(post), danger: true }); } else if (viewer.moderator) { menuItems.push({ label: "Visszaállítás (admin)", run: () => actions.restore(post) }); } const classes = ["fp", post.is_opening && "fp-opening", nested && "fp-nested"].filter(Boolean).join(" "); return (
{post.system ? ( ) : author ? ( ) : ( )}
{post.system ? ( Sorsfonalak ) : author ? ( {author.nickname} ) : ( Törölt tag )} {post.reply_to?.nickname && nested && ( válasz neki: {post.reply_to.nickname} )} {author?.online && (online)} {author && } {post.system && } {author?.moderator && } {author?.listener && } {author?.supporter && } {starter && !post.is_opening && } {isNew && új} {glyphs && !nested && ( {glyphs.text} )}
{post.deleted && (

Eltávolítva{post.deleted.reason ? ` (ok: ${post.deleted.reason})` : " a szerző által"}. Csak a moderátorok látják.

)} {post.collapsed && !showCollapsed ? ( ) : editing ? ( setEditing(false)} onSubmit={async (text) => { const ok = await actions.edit(post, text); if (ok) setEditing(false); return ok; }} /> ) : ( post.body !== null && )}
{!editing && (!post.deleted || menuItems.length > 0) && (
{post.helped && ( Segített )} {!post.deleted && ( )} {viewer.moderator && typeof post.down === "number" && post.down > 0 && ( ⌄ {post.down} )} {!post.deleted && access?.can_reply && writer && !post.is_opening && ( )} {menuItems.length > 0 && ( setMenu(false)} align="right" button={ } > {menuItems.map((item) => ( ))} )}
)} {reporting && (
setReporting(false)} />
)}
); } /** The thread page: posts, reactions, replies, read marks, new replies while open. */ export function ThreadView({ initial }: { initial: ThreadPage }) { const [page, setPage] = useState(initial); const [incoming, setIncoming] = useState(null); const [replyTo, setReplyTo] = useState(null); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); // Where the visitor stopped reading when they opened the page. const [readUpTo] = useState(initial.access?.last_read_post_id ?? null); const typingNow = useTypingWatch("thread", initial.thread.id); const imTyping = useTypingSender("thread", initial.thread.id); const composer = useRef(null); // Replying to a post: the box opens at the bottom of its branch (the // first-level post and the replies under it); what was typed moves along. const inline = useRef(null); const draft = useRef(""); const replyBranch = replyTo ? (replyTo.parent_id ?? replyTo.id) : null; useEffect(() => { if (replyBranch === null) return; const box = inline.current; box?.scrollIntoView({ behavior: "smooth", block: "center" }); box?.querySelector("textarea")?.focus({ preventScroll: true }); }, [replyBranch, replyTo]); const { viewer, thread, access } = page; const member = viewer.member !== null; const base = `/forum/threads/${thread.id}`; const lastId = page.posts.length ? page.posts[page.posts.length - 1].id : 0; // Mark read up to the newest post shown. useEffect(() => { if (!member || lastId === 0) return; api(`${base}/read`, { body: { post_id: lastId } }) // The answers read here leave the count on the "Válaszok" tab. .then(() => window.dispatchEvent(new Event("forum:nav"))) .catch(() => {}); }, [member, lastId, base]); // New replies while the page is open: offered, not pushed into the text being read. const poll = useCallback(async () => { if (document.visibilityState !== "visible" || thread.deleted) return; try { const fresh = await api(base); const freshLast = fresh.posts.length ? fresh.posts[fresh.posts.length - 1].id : 0; if (freshLast > lastId) setIncoming(fresh); } catch { /* a missed poll is retried later */ } }, [base, lastId, thread.deleted]); useEffect(() => { const timer = window.setInterval(poll, POLL_MS); // The live connection rings for this thread: look at once. const live = (e: Event) => { const notice = (e as CustomEvent).detail; if (notice.t === "thread" && notice.id === thread.id) void poll(); }; window.addEventListener("forum:live", live); return () => { window.clearInterval(timer); window.removeEventListener("forum:live", live); }; }, [poll, thread.id]); const newCount = incoming ? incoming.posts.filter((p) => p.id > lastId && !p.own).length : 0; async function run(work: () => Promise): Promise { setBusy(true); setError(null); try { return await work(); } catch (e) { setError(errorText(e)); return null; } finally { setBusy(false); } } const replacePost = useCallback((post: ForumPost) => { setPage((p) => ({ ...p, posts: p.posts.map((x) => (x.id === post.id ? post : x)) })); }, []); const reload = useCallback(async () => { const fresh = await api(base); setPage(fresh); setIncoming(null); }, [base]); const actions: Actions = { busy, react: (post, kind) => void run(async () => { const updated = post.mine === kind ? await api(`/forum/posts/${post.id}/reaction`, { method: "DELETE" }) : await api(`/forum/posts/${post.id}/reaction`, { method: "PUT", body: { kind } }); replacePost(updated); }), replyTo: (post) => setReplyTo(post), edit: async (post, body) => { const updated = await run(() => api(`/forum/posts/${post.id}`, { method: "PATCH", body: { body } })); if (updated) replacePost(updated); return updated !== null; }, remove: (post) => { let reason: string | null = null; if (post.own) { if (!window.confirm("Biztosan törlöd a hozzászólásodat?")) return; } else { reason = window.prompt("Miért távolítod el? Az indoklás a hozzászólás helyén látszik."); if (!reason) return; } void run(async () => { await api(`/forum/posts/${post.id}`, { method: "DELETE", body: { reason } }); await reload(); }); }, restore: (post) => void run(async () => { await api(`/forum/posts/${post.id}/restore`, { method: "POST" }); await reload(); }), helped: (post) => void run(async () => { const updated = await api(`/forum/posts/${post.id}/helped`, { method: post.helped ? "DELETE" : "PUT", }); replacePost(updated); }), }; /** A first-level reply (the box at the bottom), or one to `replyTo` (the box in its branch). */ async function sendReply(text: string, to: ForumPost | null): Promise { const post = await run(() => api(`${base}/posts`, { body: { body: text, parent_id: to?.id ?? null } })); if (!post) return false; if (to) { draft.current = ""; setReplyTo(null); } await reload().catch(() => setPage((p) => ({ ...p, posts: [...p.posts, post] }))); requestAnimationFrame(() => document.getElementById(`h${post.id}`)?.scrollIntoView({ block: "center" })); return true; } async function toggleFollow() { const following = access?.following ?? false; await run(() => api(`${base}/follow`, { method: following ? "DELETE" : "PUT" })); setPage((p) => (p.access ? { ...p, access: { ...p.access, following: !following } } : p)); } async function moderateThread(change: { locked?: boolean; pinned?: boolean }) { await run(() => api(base, { method: "PATCH", body: change })); await reload(); } async function removeThread() { const reason = window.prompt("Miért távolítod el az egész szálat? Az indoklás látszik a helyén."); if (!reason) return; await run(() => api(base, { method: "DELETE", body: { reason } })); await reload(); } const opening = page.posts.find((p) => p.is_opening); const replies = useMemo(() => page.posts.filter((p) => !p.is_opening), [page.posts]); const tops = replies.filter((p) => p.parent_id === null); const childrenOf = (id: number) => replies.filter((p) => p.parent_id === id); // "Itt hagytad abba": before the first post by someone else after the last visit. const firstUnread = readUpTo !== null ? (replies.find((p) => p.id > readUpTo && !p.own)?.id ?? null) : null; const unreadCount = firstUnread !== null ? replies.filter((p) => p.id >= firstUnread && !p.own).length : 0; const topOf = (id: number) => { const p = replies.find((x) => x.id === id); return p?.parent_id ?? id; }; const markerTop = firstUnread !== null ? topOf(firstUnread) : null; const intent = thread.intent ? INTENTS[thread.intent] : null; const starter = thread.author?.nickname ?? "A szál indítója"; return (
{member && access && ( )} {viewer.moderator && !thread.deleted && (
Moderálás
)}
{thread.deleted ? (
A moderátor eltávolította ezt a szálat. {thread.deleted.reason && Ok: {thread.deleted.reason}}
) : null}

{thread.pinned && Kitűzve} {thread.locked && Lezárva} {thread.title}

{intent && (

{intent.label} {thread.intent === "listen" ? "tanács helyett elég, ha jelen vagy, és leírod, ha veled is történt hasonló" : `${starter} kíváncsi a véleményetekre és a tapasztalataitokra`}

)} {opening && } {(replies.length > 0 || !thread.deleted) && (

{replies.filter((p) => !p.deleted).length} válasz

időrendben
)} {tops.map((top) => (
{markerTop === top.id && (
Itt hagytad abba · {unreadCount} új
)} = firstUnread && !top.own} /> {childrenOf(top.id).length > 0 && (
{childrenOf(top.id).map((child) => ( = firstUnread && !child.own} /> ))}
)} {replyTo && replyBranch === top.id && (

Válasz neki: {replyTo.author?.nickname ?? "Törölt tag"}

{ draft.current = text; }} busy={busy} onSubmit={(text) => sendReply(text, replyTo)} onCancel={() => { draft.current = ""; setReplyTo(null); }} />
)}
))} {newCount > 0 && ( )} {error && (

{error}

)}
{thread.deleted ? null : !viewer.logged_in ? (

Lépj be, hogy hozzászólhass.

) : viewer.needs_nickname ? (

Válassz álnevet, hogy hozzászólhass.

) : viewer.member?.banned ? (

Most nem írhatsz a fórumba.

) : !access?.can_reply ? (

Ez a szál le van zárva, új hozzászólás nem írható.

) : ( <> sendReply(text, null)} /> )}
); }