"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, memberHref } from "@/lib/forum"; import { AuthorLine, signsText } from "./AuthorLine"; import { Avatar } from "./Avatar"; import { Composer } from "./Composer"; import { PostBody } from "./PostBody"; import type { LiveNotice } from "./ForumNav"; import { ReportButton } from "./ReportButton"; import { TypingLine, useTypingSender, useTypingWatch } from "./typing"; /** 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 ReactionGrid({ post, enabled, onReact }: { post: ForumPost; enabled: boolean; onReact: Actions["react"] }) { return (
{REACTIONS.map((r) => ( ))}
); } 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 && ( {open && ( {REACTIONS.map((r) => ( ))} )} )} {canDownvote && enabled && ( )}
); } /** The author column of wide screens: avatar, nickname, rank, badges, signs one per line. */ function AuthorPanel({ author, starter }: { author: ForumPost["author"]; starter: boolean }) { if (!author) { return ( ); } const signs = signsText(author.signs); return ( ); } function PostCard({ post, page, actions, isNew, }: { post: ForumPost; page: ThreadPage; actions: Actions; isNew: boolean; }) { const [editing, setEditing] = 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; 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}}
); } return (
{/* Wide screens: the old forums' author column. */}
{starter && !post.is_opening && Szálindító} {isNew && új} } />

{post.edited_at && " · szerkesztve"} {isNew && új}

{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 && )} {post.helped && (

{thread.author?.nickname ?? "A szál indítója"} szerint ez segített

)} {!post.deleted && !editing && ( <> {post.is_opening ? ( ) : (
{access?.can_reply && writer && ( )}
)}
{access?.is_thread_author && !post.is_opening && !post.own && writer && ( )} {post.own && writer && !thread.locked && ( )} {post.own && ( )} {viewer.logged_in && !post.own && } {viewer.moderator && !post.own && ( )} {viewer.moderator && typeof post.down === "number" && post.down > 0 && ( ⌄ {post.down} )}
)} {post.deleted && viewer.moderator && (
)}
); } /** 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); 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 } }).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); composer.current?.scrollIntoView({ behavior: "smooth", block: "center" }); }, 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); }), }; async function sendReply(text: string): Promise { const post = await run(() => api(`${base}/posts`, { body: { body: text, parent_id: replyTo?.id ?? null } }), ); if (!post) return false; 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} {intent && thread.intent === "listen" && (
{intent.label} {starter} most nem kér tanácsot. Elég, ha jelen vagy, és leírod, ha veled is történt hasonló.
)} {intent && thread.intent === "advice" && (
{intent.label} {starter} kíváncsi a véleményetekre és a tapasztalataitokra.
)}

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

{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} /> ))}
)}
))} {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ó.

) : ( <> {thread.intent === "listen" && (

{starter} meghallgatást kér: tanács helyett írd le, ha veled is történt hasonló, vagy csak azt, hogy itt vagy.

)} {replyTo && (

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

)} )}
); }