Files
sorsfonalak/services/frontend/src/components/forum/ThreadView.tsx
T

633 lines
22 KiB
TypeScript
Raw Normal View History

"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";
/** 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<boolean>;
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 (
<div className="fr-grid" role="group" aria-label="Reakciók">
{REACTIONS.map((r) => (
<button
key={r.kind}
type="button"
className="fr-big"
aria-pressed={post.mine === r.kind}
disabled={!enabled}
onClick={() => onReact(post, r.kind)}
>
<span aria-hidden="true">{r.emoji}</span>
<span className="fr-big-label">{r.label}</span>
<span className="fr-count">{post.reactions[r.kind]}</span>
</button>
))}
</div>
);
}
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 (
<div className="fr-row" role="group" aria-label="Reakciók">
{given.map((r) => (
<button
key={r.kind}
type="button"
className="fr-chip"
aria-pressed={post.mine === r.kind}
aria-label={`${r.label}, ${post.reactions[r.kind]}`}
disabled={!enabled}
onClick={() => onReact(post, r.kind)}
>
{r.emoji} {post.reactions[r.kind]}
</button>
))}
{enabled && (
<span className="fr-more">
<button
type="button"
className="fr-chip fr-add"
aria-label="Reakció hozzáadása"
aria-expanded={open}
onClick={() => setOpen((o) => !o)}
>
+
</button>
{open && (
<span className="fr-pop" role="menu">
{REACTIONS.map((r) => (
<button
key={r.kind}
type="button"
role="menuitem"
className="fr-pop-item"
onClick={() => {
setOpen(false);
onReact(post, r.kind);
}}
>
<span aria-hidden="true">{r.emoji}</span> {r.label}
</button>
))}
</span>
)}
</span>
)}
{canDownvote && enabled && (
<button
type="button"
className="fr-chip fr-down"
aria-pressed={post.mine === "down"}
aria-label="Nem visz előre"
title="Nem visz előre"
onClick={() => onReact(post, "down")}
>
⌄
</button>
)}
</div>
);
}
/** 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 (
<aside className="fp-author">
<Avatar avatar={null} size={56} />
<span className="fp-author-name muted">Törölt tag</span>
</aside>
);
}
const signs = signsText(author.signs);
return (
<aside className="fp-author">
<Link href={memberHref(author.nickname)} tabIndex={-1} aria-hidden="true">
<Avatar avatar={author.avatar} size={56} online={author.online} />
</Link>
<Link href={memberHref(author.nickname)} className="fp-author-name">
{author.nickname}
</Link>
{author.online && <span className="sr-only">(online)</span>}
<span className="fa-rank">{author.rank_name}</span>
{author.moderator && <span className="fa-badge fa-badge-mod">Moderátor</span>}
{starter && <span className="fa-badge fa-badge-starter">Szálindító</span>}
{signs && (
<span className="fp-author-signs sym">
{signs.split(" · ").map((line) => (
<span key={line}>{line}</span>
))}
</span>
)}
</aside>
);
}
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 (
<article className="fp fp-removed" id={`h${post.id}`}>
<span>
{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."}
</span>
{post.deleted.reason && <span className="hint">Ok: {post.deleted.reason}</span>}
</article>
);
}
return (
<article className={post.is_opening ? "fp fp-opening" : "fp"} id={`h${post.id}`}>
{/* Wide screens: the old forums' author column. */}
<AuthorPanel author={post.author} starter={starter && !post.is_opening} />
<div className="fp-content">
<div className="fp-head">
<AuthorLine
author={post.author}
size={post.is_opening ? 44 : 36}
time={post.created_at}
edited={post.edited_at !== null}
badges={
<>
{starter && !post.is_opening && <span className="fa-badge fa-badge-starter">Szálindító</span>}
{isNew && <span className="fa-badge fa-badge-new">új</span>}
</>
}
/>
</div>
<p className="fp-when">
<time suppressHydrationWarning dateTime={post.created_at}>
{new Date(post.created_at).toLocaleString("hu-HU", {
timeZone: "Europe/Budapest",
month: "long",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
})}
</time>
{post.edited_at && " · szerkesztve"}
{isNew && <span className="fa-badge fa-badge-new">új</span>}
</p>
{post.deleted && (
<p className="fp-mod-note">
Eltávolítva{post.deleted.reason ? ` (ok: ${post.deleted.reason})` : " a szerző által"}. Csak a moderátorok
látják.
</p>
)}
{post.collapsed && !showCollapsed ? (
<button type="button" className="fp-collapsed" onClick={() => setShowCollapsed(true)}>
Sokan jelezték, hogy ez nem visz előre. Megjelenítés
</button>
) : editing ? (
<Composer
id={`szerk-${post.id}`}
label="Hozzászólás szerkesztése"
initial={post.body ?? ""}
submitLabel="Mentés"
busy={actions.busy}
autoFocus
onCancel={() => setEditing(false)}
onSubmit={async (text) => {
const ok = await actions.edit(post, text);
if (ok) setEditing(false);
return ok;
}}
/>
) : (
post.body !== null && <PostBody text={post.body} />
)}
{post.helped && (
<p className="fp-helped">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M5 12.5l4.5 4.5L19 7.5" />
</svg>
{thread.author?.nickname ?? "A szál indítója"} szerint ez segített
</p>
)}
{!post.deleted && !editing && (
<>
{post.is_opening ? (
<ReactionGrid post={post} enabled={canReact} onReact={actions.react} />
) : (
<div className="fp-actions">
<ReactionRow
post={post}
enabled={canReact}
canDownvote={access?.can_downvote ?? false}
onReact={actions.react}
/>
<span className="fp-spacer" />
{access?.can_reply && writer && (
<button type="button" className="fp-link" onClick={() => actions.replyTo(post)}>
Válasz
</button>
)}
</div>
)}
<div className="fp-tools">
{access?.is_thread_author && !post.is_opening && !post.own && writer && (
<button
type="button"
className="fp-tool"
onClick={() => actions.helped(post)}
aria-pressed={post.helped}
>
{post.helped ? "Segített ✓" : "Ez segített"}
</button>
)}
{post.own && writer && !thread.locked && (
<button type="button" className="fp-tool" onClick={() => setEditing(true)}>
Szerkesztés
</button>
)}
{post.own && (
<button type="button" className="fp-tool" onClick={() => actions.remove(post)}>
Törlés
</button>
)}
{viewer.moderator && !post.own && (
<button type="button" className="fp-tool fp-tool-mod" onClick={() => actions.remove(post)}>
Eltávolítás
</button>
)}
{viewer.moderator && typeof post.down === "number" && post.down > 0 && (
<span className="hint">⌄ {post.down}</span>
)}
</div>
</>
)}
{post.deleted && viewer.moderator && (
<div className="fp-tools">
<button type="button" className="fp-tool" onClick={() => actions.restore(post)}>
Visszaállítás (admin)
</button>
</div>
)}
</div>
</article>
);
}
/** 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<ThreadPage | null>(null);
const [replyTo, setReplyTo] = useState<ForumPost | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
// Where the visitor stopped reading when they opened the page.
const [readUpTo] = useState(initial.access?.last_read_post_id ?? null);
const composer = useRef<HTMLDivElement>(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<ThreadPage>(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);
return () => window.clearInterval(timer);
}, [poll]);
const newCount = incoming ? incoming.posts.filter((p) => p.id > lastId && !p.own).length : 0;
async function run<T>(work: () => Promise<T>): Promise<T | null> {
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<ThreadPage>(base);
setPage(fresh);
setIncoming(null);
}, [base]);
const actions: Actions = {
busy,
react: (post, kind) =>
void run(async () => {
const updated =
post.mine === kind
? await api<ForumPost>(`/forum/posts/${post.id}/reaction`, { method: "DELETE" })
: await api<ForumPost>(`/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<ForumPost>(`/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<ForumPost>(`/forum/posts/${post.id}/helped`, {
method: post.helped ? "DELETE" : "PUT",
});
replacePost(updated);
}),
};
async function sendReply(text: string): Promise<boolean> {
const post = await run(() =>
api<ForumPost>(`${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 (
<div className="ftv">
<nav className="forum-crumbs" aria-label="Morzsamenü">
<Link href="/forum">Fórum</Link>
<span aria-hidden="true">›</span>
<Link href={`/forum/${thread.topic.slug}`}>{thread.topic.name}</Link>
</nav>
<div className="ftv-toolbar">
{member && access && (
<button type="button" className="btn btn-sm" aria-pressed={access.following} onClick={toggleFollow}>
{access.following ? "Követem ✓" : "Követem"}
</button>
)}
{viewer.moderator && !thread.deleted && (
<details className="ftv-mod">
<summary className="btn btn-sm btn-ghost">Moderálás</summary>
<div className="ftv-mod-menu">
<button type="button" onClick={() => moderateThread({ locked: !thread.locked })}>
{thread.locked ? "Szál feloldása" : "Szál lezárása"}
</button>
<button type="button" onClick={() => moderateThread({ pinned: !thread.pinned })}>
{thread.pinned ? "Kitűzés levétele" : "Kitűzés"}
</button>
<button type="button" className="danger" onClick={removeThread}>
Szál eltávolítása
</button>
</div>
</details>
)}
</div>
{thread.deleted ? (
<div className="fp fp-removed">
<span>A moderátor eltávolította ezt a szálat.</span>
{thread.deleted.reason && <span className="hint">Ok: {thread.deleted.reason}</span>}
</div>
) : null}
{intent && thread.intent === "listen" && (
<div className="ftv-intent">
<strong>{intent.label}</strong>
<span>{starter} most nem kér tanácsot. Elég, ha jelen vagy, és leírod, ha veled is történt hasonló.</span>
</div>
)}
{intent && thread.intent === "advice" && (
<div className="ftv-intent ftv-intent-advice">
<strong>{intent.label}</strong>
<span>{starter} kíváncsi a véleményetekre és a tapasztalataitokra.</span>
</div>
)}
<h1 className="ftv-title">
{thread.pinned && <span className="ft-pin">Kitűzve</span>}
{thread.locked && <span className="ft-pin">Lezárva</span>}
{thread.title}
</h1>
{opening && <PostCard post={opening} page={page} actions={actions} isNew={false} />}
{(replies.length > 0 || !thread.deleted) && (
<div className="ftv-count">
<h2>{replies.filter((p) => !p.deleted).length} válasz</h2>
<span className="hint">időrendben</span>
</div>
)}
{tops.map((top) => (
<div key={top.id} className="ftv-branch">
{markerTop === top.id && (
<div className="ftv-marker" role="separator" aria-label={`Itt hagytad abba, ${unreadCount} új`}>
<span>Itt hagytad abba · {unreadCount} új</span>
</div>
)}
<PostCard
post={top}
page={page}
actions={actions}
isNew={firstUnread !== null && top.id >= firstUnread && !top.own}
/>
{childrenOf(top.id).length > 0 && (
<div className="ftv-children">
{childrenOf(top.id).map((child) => (
<PostCard
key={child.id}
post={child}
page={page}
actions={actions}
isNew={firstUnread !== null && child.id >= firstUnread && !child.own}
/>
))}
</div>
)}
</div>
))}
{newCount > 0 && (
<button
type="button"
className="ftv-incoming"
onClick={() => incoming && (setPage(incoming), setIncoming(null))}
>
{newCount === 1 ? "1 új válasz érkezett" : `${newCount} új válasz érkezett`}
</button>
)}
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
<div className="ftv-compose" id="valasz" ref={composer}>
{thread.deleted ? null : !viewer.logged_in ? (
<p className="ftv-gate">
<Link href={`/belepes?vissza=/forum/szal/${thread.id}-${thread.slug}`}>Lépj be</Link>, hogy hozzászólhass.
</p>
) : viewer.needs_nickname ? (
<p className="ftv-gate">
<Link href={`/forum/beallitasok?vissza=/forum/szal/${thread.id}-${thread.slug}`}>Válassz álnevet</Link>,
hogy hozzászólhass.
</p>
) : viewer.member?.banned ? (
<p className="ftv-gate">Most nem írhatsz a fórumba.</p>
) : !access?.can_reply ? (
<p className="ftv-gate">Ez a szál le van zárva, új hozzászólás nem írható.</p>
) : (
<>
{thread.intent === "listen" && (
<p className="ftv-hint">
{starter} meghallgatást kér: tanács helyett írd le, ha veled is történt hasonló, vagy csak azt, hogy itt
vagy.
</p>
)}
{replyTo && (
<p className="ftv-replyto">
Válasz neki: <strong>{replyTo.author?.nickname ?? "Törölt tag"}</strong>
<button
type="button"
className="fp-link"
onClick={() => setReplyTo(null)}
aria-label="Válasz visszavonása"
>
×
</button>
</p>
)}
<Composer
id="valasz-szoveg"
label="Válaszod"
placeholder={thread.topic.listening ? "Írd le, ami benned van…" : "Írd meg a válaszod…"}
busy={busy}
onSubmit={sendReply}
/>
</>
)}
</div>
</div>
);
}