Merge the forum (community module) into main

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
This commit is contained in:
feco
2026-11-26 16:43:19 +00:00
co-authored by Claude Opus 5.5
131 changed files with 17773 additions and 357 deletions
@@ -0,0 +1,91 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { api, errorText } from "@/lib/api";
import { Modal } from "./Modal";
type Kind = "chart" | "synastry" | "forecast";
const WHAT: Record<Kind, { button: string; shown: string; extra?: string }> = {
chart: {
button: "Kérdezek róla a fórumon",
shown: "a képleted rajzát a bolygók fokaival és házaival, és a rövid összefoglalót, ha már van",
},
synastry: {
button: "Kérdezek róla a fórumon",
shown: "a két képlet közös rajzát, a köztük lévő fényszögeket és házakat",
extra: "A másik fél nevét és születési adatait sem mutatjuk, de az ő képlete is látszik.",
},
forecast: {
button: "Kérdezek róla a fórumon",
shown: "az év kulcsait, az idővonalat, a tranzitokat és a részletes előrejelzést, ha már elkészült",
extra: "Az előrejelzés éve a születésnapodon kezdődik, ezért abból a születésnapod kiderül.",
},
};
/**
* "Kérdezek róla a fórumon": a link made for the forum (no birth data, no
* names), then a new thread in "Égbolt és képletek" with it attached.
*/
export function AskOnForum({ kind, targetId }: { kind: Kind; targetId: string }) {
const router = useRouter();
const [open, setOpen] = useState(false);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const what = WHAT[kind];
async function go() {
setBusy(true);
setError(null);
try {
const share = await api<{ slug: string }>("/shares", { body: { kind, target_id: targetId, for_forum: true } });
router.push(`/forum/uj?tema=egbolt-es-kepletek&kepletkartya=${encodeURIComponent(share.slug)}`);
} catch (e) {
setError(errorText(e));
setBusy(false);
}
}
return (
<>
<button type="button" className="btn btn-sm ask-forum" onClick={() => setOpen(true)}>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M4 5h12a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H9l-4 3v-3H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z" />
<path d="M20 9h1a1 1 0 0 1 1 1v8l-3-2h-6" />
</svg>
{what.button}
</button>
{open && (
<Modal title="Kérdés a fórumon" onClose={() => setOpen(false)}>
<div className="ask-forum-body">
<p>
A kérdésed mellé csatoljuk {what.shown}. A fórum belépett tagjai látják, a látogatók és a keresők nem.
</p>
<p className="hint">
Neved, születési dátumod, időd és helyed nem kerül ki.
{what.extra && ` ${what.extra}`} A fokokból egy jártas asztrológus nagyjából kiszámolhatja a születési
napot és időt. A csatolt képletet bármikor leveheted a kérdésedről, és ha törlöd a kérdést, a link is
megszűnik.
</p>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
<div className="ask-forum-actions">
<button type="button" className="btn btn-ghost" onClick={() => setOpen(false)}>
Mégse
</button>
<button type="button" className="btn btn-primary" disabled={busy} onClick={go}>
{busy ? "Egy pillanat…" : "Tovább a kérdéshez"}
</button>
</div>
</div>
</Modal>
)}
</>
);
}
@@ -0,0 +1,103 @@
"use client";
import { useEffect } from "react";
const NOT_TYPED = new Set([
"checkbox",
"radio",
"button",
"submit",
"reset",
"range",
"file",
"color",
"image",
"hidden",
]);
function typedInto(el: Element | null): el is HTMLElement {
if (el instanceof HTMLTextAreaElement) return true;
if (el instanceof HTMLInputElement) return !NOT_TYPED.has(el.type);
return el instanceof HTMLElement && el.isContentEditable;
}
/**
* On phones the on-screen keyboard must not cover the box being typed in.
* While a text field has the focus: `kb-open` on <html> (the forum's bottom
* menu and other fixed bars step aside), `--vv-top` and `--vv-height` give
* the part of the screen the keyboard leaves free (for full-screen panels),
* and the field, with its send button when the form is small, is scrolled
* into that part.
*/
export function KeyboardSafe() {
useEffect(() => {
if (!window.matchMedia("(pointer: coarse)").matches) return;
const root = document.documentElement;
const vv = window.visualViewport;
let timer: number | undefined;
let closing: number | undefined;
const measure = () => {
root.style.setProperty("--vv-top", `${vv ? vv.offsetTop : 0}px`);
root.style.setProperty("--vv-height", `${vv ? vv.height : window.innerHeight}px`);
};
const reveal = () => {
const el = document.activeElement;
if (!typedInto(el)) return;
measure();
const top = vv ? vv.offsetTop : 0;
const height = vv ? vv.height : window.innerHeight;
const form = el.closest("form");
const target = form && form.getBoundingClientRect().height < height * 0.6 ? form : el;
const rect = target.getBoundingClientRect();
const free = { top: top + 12, bottom: top + height - 12 };
if (rect.bottom > free.bottom) {
window.scrollBy({ top: Math.min(rect.bottom - free.bottom, rect.top - free.top), behavior: "smooth" });
} else if (rect.top < free.top) {
window.scrollBy({ top: rect.top - free.top, behavior: "smooth" });
}
};
// After the keyboard has slid up, and again whenever the free part changes.
const later = (ms: number) => {
window.clearTimeout(timer);
timer = window.setTimeout(reveal, ms);
};
const onFocusIn = (e: FocusEvent) => {
if (!typedInto(e.target as Element)) return;
window.clearTimeout(closing);
root.classList.add("kb-open");
measure();
later(350);
};
const onFocusOut = () => {
// Moving to another field keeps it open.
window.clearTimeout(closing);
closing = window.setTimeout(() => {
if (!typedInto(document.activeElement)) root.classList.remove("kb-open");
}, 150);
};
const onViewport = () => {
if (!root.classList.contains("kb-open")) return;
measure();
later(120);
};
document.addEventListener("focusin", onFocusIn);
document.addEventListener("focusout", onFocusOut);
vv?.addEventListener("resize", onViewport);
vv?.addEventListener("scroll", measure);
return () => {
window.clearTimeout(timer);
window.clearTimeout(closing);
document.removeEventListener("focusin", onFocusIn);
document.removeEventListener("focusout", onFocusOut);
vv?.removeEventListener("resize", onViewport);
vv?.removeEventListener("scroll", measure);
root.classList.remove("kb-open");
};
}, []);
return null;
}
@@ -12,6 +12,7 @@ export type NavIconName =
| "moon"
| "retro"
| "packages"
| "forum"
| "admin";
const GLYPHS: Partial<Record<NavIconName, string>> = {
@@ -62,6 +63,12 @@ export function NavIcon({ name }: { name: NavIconName }) {
<path d="M3.5 7.2L12 12l8.5-4.8M12 12v9.5" />
</>
)}
{name === "forum" && (
<>
<path d="M4 5h12a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H9l-4 3v-3H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z" />
<path d="M20 9h1a1 1 0 0 1 1 1v8l-3-2h-6" />
</>
)}
{name === "admin" && (
<>
<circle cx="12" cy="12" r="3" />
@@ -1,5 +1,6 @@
import Link from "next/link";
import { forumEnabled } from "@/lib/forumServer";
import type { Me, SkyNow } from "@/lib/types";
import { MobileMenu } from "./MobileMenu";
@@ -42,10 +43,11 @@ export function PublicHeader({
current,
}: {
onHome?: boolean;
current?: "pelda" | "horoszkop" | "csillagjegyek" | "hires" | "holdnaptar" | "retrograd";
current?: "pelda" | "horoszkop" | "csillagjegyek" | "hires" | "holdnaptar" | "retrograd" | "forum";
}) {
const home = onHome ? "" : "/";
const here = (page: typeof current) => (current === page ? "page" : undefined);
const forum = forumEnabled();
return (
<header className="site-header lp-header">
<Logo />
@@ -56,6 +58,11 @@ export function PublicHeader({
<Link href="/pelda" aria-current={here("pelda")}>
Példa
</Link>
{forum && (
<Link href="/forum" aria-current={here("forum")}>
Fórum
</Link>
)}
</nav>
<nav className="lp-free" aria-label="Ingyenes, belépés nélkül">
<span className="lp-free-label">Ingyenes</span>
@@ -81,6 +88,7 @@ export function PublicHeader({
{ href: `${home}#elorejelzes`, label: "Előrejelzés" },
{ href: `${home}#osszevetes`, label: "Összevetés" },
{ href: "/pelda", label: "Példa" },
...(forum ? [{ href: "/forum", label: "Fórum" }] : []),
],
},
{
@@ -148,6 +156,7 @@ export function SiteHeader({ me, sky }: { me: Me; sky?: SkyNow | null }) {
{ href: "/szemelyek", label: "Személyek", icon: "persons" },
{ href: "/osszevetesek", label: "Összevetések", icon: "compare" },
{ href: "/kartyajoslas", label: "Kártyajóslás", icon: "tarot" },
...(forumEnabled() ? [{ href: "/forum", label: "Fórum", icon: "forum" as const }] : []),
];
const packages: NavItem = { href: "/csomagok", label: "Csomagok", icon: "packages" };
const team: NavItem[] = me.user.roles.includes("admin")
@@ -0,0 +1,134 @@
import Link from "next/link";
import { POINTS, SIGNS } from "@/lib/astro";
import { type ForumAuthor, ago, memberHref } from "@/lib/forum";
import { Avatar } from "./Avatar";
import { Badge, RankBadge } from "./Badges";
/** "☉ Halak · ☽ Rák · Asz Szűz": the signs a member chose to share. */
export function signsText(signs: Record<string, string> | null | undefined): string | null {
if (!signs) return null;
const parts = Object.entries(signs)
.sort(([a], [b]) => order(a) - order(b))
.map(([point, sign]) => {
const name = SIGNS[sign]?.hu ?? sign;
return point === "ascendant" ? `Asz ${name}` : `${POINTS[point]?.glyph ?? point} ${name}`;
});
return parts.length ? parts.join(" · ") : null;
}
/**
* The short form next to a post: Sun, Moon and Ascendant as glyphs
* ("☉♓ ☽♋ ↑♍"), with the names in `title`. Every planet only on the profile.
*/
export function signGlyphs(signs: Record<string, string> | null | undefined): { text: string; title: string } | null {
if (!signs) return null;
const parts: string[] = [];
const names: string[] = [];
for (const [point, label] of [
["sun", "Nap"],
["moon", "Hold"],
["ascendant", "Aszcendens"],
] as const) {
const sign = signs[point];
if (!sign) continue;
const mark = point === "ascendant" ? "↑" : (POINTS[point]?.glyph ?? "");
parts.push(`${mark}${SIGNS[sign]?.glyph ?? ""}`);
names.push(`${label}: ${SIGNS[sign]?.hu ?? sign}`);
}
return parts.length ? { text: parts.join(" "), title: names.join(", ") } : null;
}
const ORDER = [
"sun",
"moon",
"ascendant",
"mercury",
"venus",
"mars",
"jupiter",
"saturn",
"uranus",
"neptune",
"pluto",
];
function order(point: string) {
const i = ORDER.indexOf(point);
return i < 0 ? 99 : i;
}
/**
* Who wrote it: avatar with the online dot, nickname, rank, badges, the
* shared signs and the time. A deleted account shows as "Törölt tag".
*/
export function AuthorLine({
author,
size = 40,
time,
edited = false,
badges,
signs = true,
}: {
author: ForumAuthor | null;
size?: number;
time?: string;
edited?: boolean;
badges?: React.ReactNode;
signs?: boolean;
}) {
if (!author) {
return (
<div className="fa-line">
<Avatar avatar={null} size={size} />
<span className="fa-meta">
<span className="fa-name muted">Törölt tag</span>
{time && <span className="fa-sub">{ago(time)}</span>}
</span>
</div>
);
}
const glyphs = signs ? signGlyphs(author.signs) : null;
const shown = glyphs?.text ?? null;
return (
<div className="fa-line">
<Link href={memberHref(author.nickname)} className="fa-avatar" tabIndex={-1} aria-hidden="true">
<Avatar avatar={author.avatar} size={size} online={author.online} />
</Link>
<span className="fa-meta">
<span className="fa-names">
<Link href={memberHref(author.nickname)} className="fa-name">
{author.nickname}
</Link>
{author.online && <span className="sr-only">(online)</span>}
<RankBadge rank={author.rank} name={author.rank_name} />
{author.moderator && <Badge kind="mod" />}
{author.founder && <Badge kind="founder" />}
{author.listener && <Badge kind="listener" />}
{author.supporter && <Badge kind="supporter" />}
{badges}
</span>
{(shown || time) && (
<span className="fa-sub">
{shown && (
<span className="sym" title={glyphs?.title}>
{shown}
</span>
)}
{shown && time && " · "}
{time && (
<time
suppressHydrationWarning
dateTime={time}
title={new Date(time).toLocaleString("hu-HU", { timeZone: "Europe/Budapest" })}
>
{ago(time)}
</time>
)}
{edited && " · szerkesztve"}
</span>
)}
</span>
</div>
);
}
@@ -0,0 +1,106 @@
// The starter avatars, `<glyph>-<colour>` (the forum service checks the same
// lists): a gold glyph on a night colour in the dark theme, a darker glyph on
// a pale tint in the light one (forum.css: .av-<colour>). With `online`, the
// green dot.
import { uploadedAvatar } from "@/lib/forum";
export const AVATAR_GLYPHS = ["hold", "csillag", "nap", "hullam", "level", "lotusz", "kristaly", "toll"] as const;
export const AVATAR_COLOURS = ["ejkek", "lila", "tenger", "borostyan", "rozsa", "erdo"] as const;
export const GLYPH_NAMES: Record<string, string> = {
hold: "Hold",
csillag: "Csillag",
nap: "Nap",
hullam: "Hullám",
level: "Levél",
lotusz: "Lótusz",
kristaly: "Kristály",
toll: "Toll",
};
function Glyph({ name }: { name: string }) {
switch (name) {
case "hold":
return <path d="M23 10A10 10 0 1 0 23 30A8 8 0 1 1 23 10Z" className="av-fill" />;
case "csillag":
return <path d="M20 9 L22.5 17.5 L31 20 L22.5 22.5 L20 31 L17.5 22.5 L9 20 L17.5 17.5 Z" className="av-fill" />;
case "nap":
return (
<>
<circle cx="20" cy="20" r="5" className="av-fill" />
<path d="M20 8v4M20 28v4M8 20h4M28 20h4M11.5 11.5l2.8 2.8M25.7 25.7l2.8 2.8M28.5 11.5l-2.8 2.8M14.3 25.7l-2.8 2.8" />
</>
);
case "hullam":
return (
<>
<path d="M9 18 q5.5-6 11 0 t11 0" />
<path d="M12 25 q4-4 8 0 t8 0" opacity="0.6" />
</>
);
case "level":
return (
<>
<path d="M12 28 C12 16 20 11 29 11 C29 20 24 28 12 28 Z" />
<path d="M12 28 L22 18" />
</>
);
case "lotusz":
return (
<>
<path d="M20 11c3 4 3 9 0 14c-3-5-3-10 0-14z" />
<path d="M20 25c-4-1-8-4-9-9c4 0 7 3 9 9zM20 25c4-1 8-4 9-9c-4 0-7 3-9 9z" />
<path d="M12 29h16" />
</>
);
case "kristaly":
return (
<>
<path d="M20 9l7 9-7 13-7-13z" />
<path d="M13 18h14" />
</>
);
default:
return (
<>
<path d="M28 10c-8 1-13 7-15 18l3-1c1-6 5-11 12-17z" />
<path d="M13 29l9-11" />
</>
);
}
}
export function Avatar({
avatar,
size = 40,
online = false,
}: {
avatar: string | null | undefined;
size?: number;
online?: boolean;
}) {
const picture = uploadedAvatar(avatar);
if (picture) {
return (
<span className="av av-picture" style={{ width: size, height: size }}>
{/* A member's own picture, served by the forum (already small and square). */}
<img src={picture} alt="" width={size} height={size} loading="lazy" />
{online && <span className="av-online" title="Most online" />}
</span>
);
}
const [glyph, colour] = (avatar ?? "hold-ejkek").split("-");
const known = (AVATAR_COLOURS as readonly string[]).includes(colour) ? colour : "ejkek";
return (
<span className={`av av-${known}`} style={{ width: size, height: size }}>
<svg viewBox="0 0 40 40" width={size} height={size} aria-hidden="true">
<circle cx="20" cy="20" r="20" className="av-bg" />
<g className="av-glyph">
<Glyph name={glyph} />
</g>
</svg>
{online && <span className="av-online" title="Most online" />}
</span>
);
}
@@ -0,0 +1,143 @@
// The small labels next to a nickname, each with its own line icon: the rank
// (from Vándor to Sorsfonó, a thread being spun), and the badges.
import type { Rank } from "@/lib/forum";
const RANK_ICONS: Record<Rank, React.ReactNode> = {
// Vándor: on the way (a path from a starting point).
vandor: (
<>
<circle cx="5.5" cy="18.5" r="1.8" />
<path d="M8 17.5c3-1 2.5-4.5 6-5.5s3.5-3.5 5-6" strokeDasharray="2.2 2.6" />
</>
),
// Kereső: a compass.
kereso: (
<>
<circle cx="12" cy="12" r="8.5" />
<path d="M14.8 9.2l-1.6 4-4 1.6 1.6-4z" />
</>
),
// Fonó: a spool with thread.
fono: (
<>
<path d="M6.5 4.5h11M6.5 19.5h11" />
<path d="M8.5 4.5v15M15.5 4.5v15" />
<path d="M8.5 8.5l7 2.5M8.5 13l7 2.5" />
</>
),
// Csillagfonó: a star with a thread from it.
csillagfono: (
<>
<path d="M10 3.5l1.5 4 4 1.5-4 1.5-1.5 4-1.5-4-4-1.5 4-1.5z" />
<path d="M14 15c2.5 0 3.5 1.5 3.5 3s-1.5 2.5-3 2" />
</>
),
// Sorsfonó: the thread of fate around the circle (the site's mark).
sorsfono: (
<>
<circle cx="12" cy="12" r="7" />
<path d="M4.5 16.5c4.5-.5 6-7 11-8.5" />
<circle cx="18.5" cy="6" r="1.4" />
</>
),
};
export type BadgeKind = "mod" | "founder" | "listener" | "supporter" | "starter" | "sky";
const BADGES: Record<BadgeKind, { label: string; title: string; icon: React.ReactNode }> = {
// A shield with a tick.
mod: {
label: "Moderátor",
title: "A fórum moderátora",
icon: (
<>
<path d="M12 3.5l7 2.5v5.5c0 4.5-3 7.5-7 9-4-1.5-7-4.5-7-9V6z" />
<path d="M9 12l2.2 2.2L15.5 10" />
</>
),
},
// A sprout: there from the beginning.
founder: {
label: "Alapító tag",
title: "A fórum első tizenöt tagja közül való",
icon: (
<>
<path d="M12 20.5V11" />
<path d="M12 12.5c0-4 2.8-6.5 7-6.5 0 4-2.8 6.5-7 6.5z" />
<path d="M12 14.5c0-3.2-2.4-5.5-6-5.5 0 3.2 2.4 5.5 6 5.5z" />
<path d="M8 20.5h8" />
</>
),
},
// Two walking side by side.
listener: {
label: "Kísérő",
title: "Önkéntes kísérő: szívesen válaszol annak, aki meghallgatást kér",
icon: (
<>
<circle cx="8" cy="6.5" r="2.5" />
<circle cx="16" cy="6.5" r="2.5" />
<path d="M3.5 20v-3.5a4.5 4.5 0 0 1 9 0V20" />
<path d="M11.5 20v-3.5a4.5 4.5 0 0 1 9 0V20" />
</>
),
},
// A gem.
supporter: {
label: "Támogató",
title: "Vásárlásával támogatja a Sorsfonalakat",
icon: (
<>
<path d="M7.5 5h9l3.5 4.5L12 19.5 4 9.5z" />
<path d="M4 9.5h16M10 5l-1.5 4.5L12 19.5l3.5-10L14 5" />
</>
),
},
// A quill.
starter: {
label: "Szálindító",
title: "Ő indította a szálat",
icon: (
<>
<path d="M19.5 4.5c-6 .5-10.5 4.5-11.5 11l-1.5 4" />
<path d="M8.3 13.5c4.5 0 8.5-3 11.2-9" />
</>
),
},
// A crescent Moon.
sky: {
label: "napi égbolt",
title: "A Sorsfonalak napi szála az égboltról",
icon: <path d="M19 14.5A7.5 7.5 0 0 1 9.5 5a7.5 7.5 0 1 0 9.5 9.5z" />,
},
};
function Icon({ children }: { children: React.ReactNode }) {
return (
<svg className="fa-icon" viewBox="0 0 24 24" aria-hidden="true">
{children}
</svg>
);
}
/** The member's rank, with its icon. */
export function RankBadge({ rank, name }: { rank: Rank; name: string }) {
return (
<span className={`fa-rank fa-rank-${rank}`} title={`Rang: ${name}`}>
<Icon>{RANK_ICONS[rank] ?? RANK_ICONS.vandor}</Icon>
{name}
</span>
);
}
/** A badge (Moderátor, Alapító tag, Kísérő, Támogató, Szálindító, napi égbolt), with its icon. */
export function Badge({ kind }: { kind: BadgeKind }) {
const b = BADGES[kind];
return (
<span className={`fa-badge fa-badge-${kind === "sky" ? "starter" : kind}`} title={b.title}>
<Icon>{b.icon}</Icon>
{b.label}
</span>
);
}
@@ -0,0 +1,158 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { api } from "@/lib/api";
import { convertEmoticons, withEmoji } from "@/lib/emoticons";
import type { ForumAuthor } from "@/lib/forum";
import { Avatar } from "./Avatar";
/** "@Ho" right before the caret: what was typed after the "@", and where it starts. */
function mentionAt(text: string, caret: number): { query: string; start: number } | null {
const before = text.slice(0, caret);
const match = /(?:^|\s)@([^\s@]{1,24})$/.exec(before);
if (!match) return null;
return { query: match[1], start: caret - match[1].length - 1 };
}
/**
* The text box and the send button. Character smileys (`:)`, `<3`) turn into
* emoji as they are typed; phones bring their own emoji keyboard.
* `onTyping`: called on every keystroke (the "… gépel" notice).
* `mentions`: typing "@Ho" offers the members whose nickname starts so.
* `onChange`: the text as it is typed (to keep a draft when the box moves).
*/
export function Composer({
id,
label,
placeholder,
initial = "",
submitLabel = "Küldés",
busy,
onSubmit,
onCancel,
onTyping,
onChange,
mentions = false,
rows = 3,
autoFocus = false,
}: {
id: string;
label: string;
placeholder?: string;
initial?: string;
submitLabel?: string;
busy: boolean;
onSubmit: (text: string) => Promise<boolean>;
onCancel?: () => void;
onTyping?: () => void;
onChange?: (text: string) => void;
mentions?: boolean;
rows?: number;
autoFocus?: boolean;
}) {
const [text, setText] = useState(initial);
const [suggest, setSuggest] = useState<{ query: string; start: number; members: ForumAuthor[] } | null>(null);
const area = useRef<HTMLTextAreaElement>(null);
const timer = useRef<number | undefined>(undefined);
useEffect(() => () => window.clearTimeout(timer.current), []);
useEffect(() => {
onChange?.(text);
}, [text, onChange]);
function lookUp(value: string, caret: number) {
window.clearTimeout(timer.current);
const at = mentions ? mentionAt(value, caret) : null;
if (!at) {
setSuggest(null);
return;
}
timer.current = window.setTimeout(() => {
api<{ members: ForumAuthor[] }>(`/forum/members/search?q=${encodeURIComponent(at.query)}`)
.then((res) => setSuggest(res.members.length ? { ...at, members: res.members } : null))
.catch(() => setSuggest(null));
}, 200);
}
function pick(nickname: string) {
if (!suggest) return;
const el = area.current;
const caret = el?.selectionStart ?? text.length;
const inserted = `@${nickname} `;
const next = text.slice(0, suggest.start) + inserted + text.slice(caret);
setText(next);
setSuggest(null);
requestAnimationFrame(() => {
el?.focus();
const at = suggest.start + inserted.length;
el?.setSelectionRange(at, at);
});
}
async function submit(e: React.FormEvent) {
e.preventDefault();
if (!text.trim() || busy) return;
const final = convertEmoticons(text, text.length, true).text;
if (await onSubmit(final)) {
setText("");
setSuggest(null);
}
}
return (
<form className="fc" onSubmit={submit}>
<label htmlFor={id} className="sr-only">
{label}
</label>
<textarea
id={id}
ref={area}
className="fc-text"
rows={rows}
placeholder={placeholder}
value={text}
onChange={(e) => {
withEmoji(e, setText);
lookUp(e.target.value, e.target.selectionStart ?? e.target.value.length);
onTyping?.();
}}
onKeyDown={(e) => {
if (e.key === "Escape") setSuggest(null);
}}
maxLength={10000}
autoFocus={autoFocus}
aria-autocomplete={mentions ? "list" : undefined}
/>
{suggest && (
<div className="fc-suggest" role="listbox" aria-label="Tagok">
{suggest.members.map((m) => (
<button
key={m.nickname}
type="button"
role="option"
aria-selected="false"
className="fc-suggest-item"
onClick={() => pick(m.nickname)}
>
<Avatar avatar={m.avatar} size={24} online={m.online} />
{m.nickname}
</button>
))}
</div>
)}
<div className="fc-actions">
<span className="fc-spacer" />
{onCancel && (
<button type="button" className="btn btn-ghost btn-sm" onClick={onCancel}>
Mégse
</button>
)}
<button type="submit" className="btn btn-primary btn-sm" disabled={busy || !text.trim()}>
{busy ? "Küldés…" : submitLabel}
</button>
</div>
</form>
);
}
@@ -0,0 +1,244 @@
"use client";
import Link from "next/link";
import { usePathname } from "next/navigation";
import { useCallback, useEffect, useRef, useState } from "react";
import { api } from "@/lib/api";
import type { ForumNavData } from "@/lib/forum";
/** The menu's counts. */
export interface NavCounts {
/** Unread answers to the member: the only count on the "Válaszok" tab. */
replies: number;
messages: number;
reports: number;
}
/** The live notice a page listens to (`window` event `forum:live`). */
export interface LiveNotice {
t: "thread" | "conversation" | "nav" | "typing";
id?: number;
/** For `typing`: where (`thread` or `conversation`) and who. */
kind?: string;
who?: string;
}
/** How often the counts are asked for while there is no live connection (also the online dot). */
const POLL_MS = 30_000;
function counts(data: ForumNavData): NavCounts {
return { replies: data.replies ?? 0, messages: data.messages ?? 0, reports: data.reports ?? 0 };
}
/**
* The live connection (a member's): the server rings when something changed,
* the menu fetches its counts, and an open thread or conversation is told
* (`forum:live` events). Without a connection, the counts are polled.
*/
function useLive(member: boolean, wsUrl: string, refresh: () => void) {
const open = useRef(false);
useEffect(() => {
if (!member) return;
let socket: WebSocket | null = null;
let retry = 1000;
let timer: number | undefined;
let stopped = false;
const url = new URL(wsUrl, window.location.href);
url.protocol = url.protocol === "https:" ? "wss:" : url.protocol === "http:" ? "ws:" : url.protocol;
const connect = () => {
if (stopped) return;
socket = new WebSocket(url);
socket.onopen = () => {
open.current = true;
retry = 1000;
refresh();
};
socket.onmessage = (e) => {
let notice: LiveNotice;
try {
notice = JSON.parse(String(e.data)) as LiveNotice;
} catch {
return;
}
if (notice.t === "nav") refresh();
window.dispatchEvent(new CustomEvent<LiveNotice>("forum:live", { detail: notice }));
};
socket.onclose = () => {
open.current = false;
if (stopped) return;
timer = window.setTimeout(connect, retry);
retry = Math.min(retry * 2, 60_000);
};
};
connect();
// The page says its member is typing somewhere: passed on while connected.
const typing = (e: Event) => {
const out = (e as CustomEvent<{ kind: string; id: number }>).detail;
if (open.current && socket?.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify({ typing: out.kind, id: out.id }));
}
};
window.addEventListener("forum:typing-out", typing);
// Polling while there is no connection; and when the page comes back to the front.
const poll = window.setInterval(() => {
if (!open.current && document.visibilityState === "visible") refresh();
}, POLL_MS);
const visible = () => {
if (document.visibilityState === "visible") refresh();
};
document.addEventListener("visibilitychange", visible);
return () => {
stopped = true;
window.clearTimeout(timer);
window.clearInterval(poll);
document.removeEventListener("visibilitychange", visible);
window.removeEventListener("forum:typing-out", typing);
socket?.close();
};
}, [member, wsUrl, refresh]);
}
function Icon({ name }: { name: "forum" | "replies" | "new" | "messages" | "profile" }) {
return (
<svg viewBox="0 0 24 24" aria-hidden="true" className="fn-icon">
{name === "forum" && (
<>
<path d="M4 5h12a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H9l-4 3v-3H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2z" />
<path d="M20 9h1a1 1 0 0 1 1 1v8l-3-2h-6" />
</>
)}
{name === "replies" && (
<>
<path d="M10 8L5 12.5l5 4.5" />
<path d="M5 12.5h9a5 5 0 0 1 5 5V19" />
<path d="M14 4.5h5.5" />
</>
)}
{name === "new" && (
<>
<circle cx="12" cy="12" r="9" />
<path d="M12 8v8M8 12h8" />
</>
)}
{name === "messages" && (
<>
<rect x="3" y="5.5" width="18" height="13" rx="2" />
<path d="M3.5 7l8.5 6 8.5-6" />
</>
)}
{name === "profile" && (
<>
<circle cx="12" cy="8" r="4" />
<path d="M4.5 20.5c0-3.8 3.4-6 7.5-6s7.5 2.2 7.5 6" />
</>
)}
</svg>
);
}
/**
* The forum's own menu: a bar at the bottom of the screen on phones, tabs
* above the content on wider screens. The "Válaszok" tab counts the unread
* answers to the member (a reply to them, in their thread, or naming them).
*/
export function ForumNav({
member,
loggedIn,
initial,
wsUrl,
}: {
member: string | null;
loggedIn: boolean;
initial: NavCounts;
wsUrl: string;
}) {
const path = usePathname();
const [{ replies, messages, reports }, setCounts] = useState(initial);
const refresh = useCallback(() => {
api<ForumNavData>("/forum/nav")
.then((data) => setCounts(counts(data)))
.catch(() => {});
}, []);
useLive(member !== null, wsUrl, refresh);
// A page that changed what counts (read a thread, "Mind olvasott") asks for fresh counts.
useEffect(() => {
window.addEventListener("forum:nav", refresh);
return () => window.removeEventListener("forum:nav", refresh);
}, [refresh]);
// The menu stays on screen between pages: fresh counts on every page.
const first = useRef(true);
useEffect(() => {
if (first.current) {
first.current = false;
return;
}
if (loggedIn) refresh();
}, [path, loggedIn, refresh]);
const items = [
{
href: "/forum",
label: "Fórum",
icon: "forum" as const,
current: path === "/forum" || path.startsWith("/forum/szal"),
},
{
href: loggedIn ? "/forum/valaszok" : "/belepes?vissza=/forum/valaszok",
label: "Válaszok",
icon: "replies" as const,
current: path.startsWith("/forum/valaszok") || path.startsWith("/forum/kovetett"),
badge: replies,
},
{
href: loggedIn ? "/forum/uj" : "/belepes?vissza=/forum/uj",
label: "Új szál",
icon: "new" as const,
current: path.startsWith("/forum/uj"),
},
{
href: member
? "/forum/uzenetek"
: loggedIn
? "/forum/beallitasok?vissza=/forum/uzenetek"
: "/belepes?vissza=/forum/uzenetek",
label: "Üzenetek",
icon: "messages" as const,
current: path.startsWith("/forum/uzenetek"),
badge: messages,
},
{
href: member
? `/forum/tag/${encodeURIComponent(member)}`
: loggedIn
? "/forum/beallitasok"
: "/belepes?vissza=/forum",
label: member ? "Profilom" : loggedIn ? "Álnév" : "Belépés",
icon: "profile" as const,
current: path.startsWith("/forum/tag/") || path.startsWith("/forum/beallitasok"),
},
];
return (
<>
{reports > 0 && (
<Link href="/forum/moderalas" className="forum-modchip">
Moderálás: {reports}
</Link>
)}
<nav className="forum-nav" aria-label="Fórum menü">
{items.map((item) => (
<Link key={item.label} href={item.href} aria-current={item.current ? "page" : undefined} className="fn-item">
<span className="fn-icon-wrap">
<Icon name={item.icon} />
{item.badge ? (
<span className="fn-badge" aria-label={`${item.badge} új`}>
{item.badge > 99 ? "99+" : item.badge}
</span>
) : null}
</span>
<span className="fn-label">{item.label}</span>
</Link>
))}
</nav>
</>
);
}
@@ -0,0 +1,70 @@
"use client";
import { useRouter } from "next/navigation";
import { useState } from "react";
import { api, errorText } from "@/lib/api";
/** A restricted topic: asking to join it (a moderator decides), or the request waiting. */
export function JoinTopic({ slug, pending }: { slug: string; pending: boolean }) {
const router = useRouter();
const [open, setOpen] = useState(false);
const [note, setNote] = useState("");
const [busy, setBusy] = useState(false);
const [sent, setSent] = useState(pending);
const [error, setError] = useState<string | null>(null);
if (sent) return <span className="hint">Jelentkezésed elküldve, egy moderátor dönt róla.</span>;
async function send(e: React.FormEvent) {
e.preventDefault();
setBusy(true);
setError(null);
try {
await api(`/forum/topics/${slug}/join`, { body: { note } });
setSent(true);
router.refresh();
} catch (err) {
setError(errorText(err));
} finally {
setBusy(false);
}
}
if (!open) {
return (
<button type="button" className="btn btn-sm" onClick={() => setOpen(true)}>
Csatlakozás kérése
</button>
);
}
return (
<form className="fjoin" onSubmit={send}>
<label htmlFor={`join-${slug}`} className="hint">
Pár szó, miért szeretnél csatlakozni (nem kötelező)
</label>
<textarea
id={`join-${slug}`}
className="fc-text"
rows={2}
maxLength={300}
value={note}
onChange={(e) => setNote(e.target.value)}
/>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
<div className="fc-actions">
<span className="fc-spacer" />
<button type="button" className="btn btn-ghost btn-sm" onClick={() => setOpen(false)}>
Mégse
</button>
<button type="submit" className="btn btn-primary btn-sm" disabled={busy}>
Jelentkezem
</button>
</div>
</form>
);
}
@@ -0,0 +1,111 @@
"use client";
import { useEffect, useState } from "react";
import type { LinkPreview } from "@/lib/forum";
type Device = "android" | "ios" | "desktop";
function detect(): Device {
const ua = navigator.userAgent;
if (/Android/i.test(ua)) return "android";
// iPadOS reports itself as a Mac with touch.
if (/iPhone|iPad|iPod/i.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1)) return "ios";
return "desktop";
}
/**
* A YouTube link under a post: our own copy of the thumbnail (nothing is
* loaded from YouTube until someone plays it). On a computer a click plays
* it here; on a phone it opens the YouTube app (Android: an intent with the
* web page as fallback; iOS: the link, which the app takes over), and
* "Lejátszás itt" plays it here.
*/
function YouTubeCard({ link }: { link: LinkPreview }) {
const [playing, setPlaying] = useState(false);
const [device, setDevice] = useState<Device>("desktop");
useEffect(() => setDevice(detect()), []);
const at = link.start ? `&t=${link.start}s` : "";
const watch = `https://www.youtube.com/watch?v=${link.id}${at}`;
const app =
device === "android"
? `intent://www.youtube.com/watch?v=${link.id}${at}#Intent;scheme=https;package=com.google.android.youtube;` +
`S.browser_fallback_url=${encodeURIComponent(watch)};end`
: watch;
const mobile = device !== "desktop";
if (playing) {
const start = link.start ? `&start=${link.start}` : "";
return (
<div className="flink flink-playing">
<div className="flink-frame">
<iframe
src={`https://www.youtube-nocookie.com/embed/${link.id}?autoplay=1&rel=0&playsinline=1${start}`}
title={link.title}
allow="autoplay; encrypted-media; picture-in-picture; fullscreen"
allowFullScreen
referrerPolicy="strict-origin-when-cross-origin"
/>
</div>
<div className="flink-meta">
<span className="flink-title">{link.title}</span>
<a href={watch} target="_blank" rel="noopener noreferrer" className="fp-link">
Megnyitás a YouTube-on
</a>
</div>
</div>
);
}
return (
<div className="flink">
<a
className="flink-thumb"
href={mobile ? app : watch}
onClick={(e) => {
if (!mobile) {
e.preventDefault();
setPlaying(true);
}
}}
aria-label={mobile ? `Megnyitás a YouTube alkalmazásban: ${link.title}` : `Lejátszás: ${link.title}`}
>
{link.thumbnail ? (
// Our own copy of the thumbnail (already small).
<img src={link.thumbnail} alt="" width={480} height={270} loading="lazy" />
) : (
<span className="flink-noimg" />
)}
<span className="flink-play" aria-hidden="true">
<svg viewBox="0 0 24 24">
<path d="M8 5.5v13l11-6.5z" />
</svg>
</span>
</a>
<div className="flink-meta">
<span className="flink-title">{link.title}</span>
<span className="hint">
YouTube{link.author ? ` · ${link.author}` : ""}
{link.start ? ` · ${Math.floor(link.start / 60)}:${String(link.start % 60).padStart(2, "0")}-tól` : ""}
</span>
{mobile ? (
<button type="button" className="fp-link flink-here" onClick={() => setPlaying(true)}>
Lejátszás itt
</button>
) : (
<a href={watch} target="_blank" rel="noopener noreferrer" className="fp-link flink-here">
Megnyitás a YouTube-on
</a>
)}
</div>
</div>
);
}
/** The previews of the links in a post (the link module: YouTube for now). */
export function LinkPreviews({ links }: { links: LinkPreview[] }) {
return (
<div className="flinks">
{links.map((link) => (link.provider === "youtube" ? <YouTubeCard key={link.id} link={link} /> : null))}
</div>
);
}
@@ -0,0 +1,59 @@
import Link from "next/link";
import { memberHref } from "@/lib/forum";
/** "@Holdfény" as a link to the profile, for the nicknames the post names. */
function withMentions(line: string, mentions: string[]): React.ReactNode[] {
if (mentions.length === 0) return [line];
const escaped = [...mentions]
.sort((a, b) => b.length - a.length)
.map((n) => n.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
const pattern = new RegExp(`@(${escaped.join("|")})`, "gi");
const out: React.ReactNode[] = [];
let last = 0;
for (const match of line.matchAll(pattern)) {
const at = match.index ?? 0;
if (at > last) out.push(line.slice(last, at));
const nickname = mentions.find((n) => n.toLowerCase() === match[1].toLowerCase()) ?? match[1];
out.push(
<Link key={at} href={memberHref(nickname)} className="fp-mention">
@{match[1]}
</Link>,
);
last = at + match[0].length;
}
if (last < line.length) out.push(line.slice(last));
return out;
}
/**
* A post's text: paragraphs and line breaks as typed; links stay plain text;
* mentions link to profiles. `hide`: links shown as a preview below, left
* out where they stand on a line of their own.
*/
export function PostBody({ text, mentions = [], hide = [] }: { text: string; mentions?: string[]; hide?: string[] }) {
const shown = hide.length
? text
.split("\n")
.filter((line) => !hide.includes(line.trim()))
.join("\n")
.trim()
: text;
return (
<div className="fp-body">
{shown
.split(/\n{2,}/)
.filter((para) => para.trim() !== "")
.map((para, i) => (
<p key={i}>
{para.split("\n").map((line, j) => (
<span key={j}>
{j > 0 && <br />}
{withMentions(line, mentions)}
</span>
))}
</p>
))}
</div>
);
}
@@ -0,0 +1,49 @@
// The forum's own reaction marks (no emoji): a heart, a lotus, two circles
// meeting, a star. Each has its colour (forum.css: .ri-<kind>); the viewer's
// own reaction is drawn filled.
import type { ReactionKind } from "@/lib/forum";
export function ReactionIcon({
kind,
size = 16,
filled = false,
}: {
kind: ReactionKind;
size?: number;
filled?: boolean;
}) {
return (
<svg
viewBox="0 0 24 24"
width={size}
height={size}
aria-hidden="true"
className={filled ? `ri ri-${kind} ri-filled` : `ri ri-${kind}`}
>
{kind === "with_you" && (
<path d="M12 20s-7.5-4.6-7.5-10.2A4.2 4.2 0 0 1 12 7.3a4.2 4.2 0 0 1 7.5 2.5C19.5 15.4 12 20 12 20z" />
)}
{kind === "thanks" && (
<>
<path d="M12 4.5c2.3 2.7 2.3 6.6 0 9.3c-2.3-2.7-2.3-6.6 0-9.3z" />
<path d="M12 13.8c-3.2-.5-5.9-2.6-6.8-6.1c3.2.2 5.6 2.4 6.8 6.1z" />
<path d="M12 13.8c3.2-.5 5.9-2.6 6.8-6.1c-3.2.2-5.6 2.4-6.8 6.1z" />
<path d="M5.5 17.5h13" className="ri-line" />
<path d="M8.5 20.2h7" className="ri-line" />
</>
)}
{kind === "me_too" && (
<>
<circle cx="9.3" cy="12" r="5.3" />
<circle cx="14.7" cy="12" r="5.3" />
</>
)}
{kind === "insight" && (
<>
<path d="M11 4l1.7 5.1 5.1 1.7-5.1 1.7L11 17.6l-1.7-5.1-5.1-1.7 5.1-1.7z" />
<path d="M18 15.5l.6 1.6 1.6.6-1.6.6-.6 1.6-.6-1.6-1.6-.6 1.6-.6z" />
</>
)}
</svg>
);
}
@@ -0,0 +1,15 @@
import Link from "next/link";
/** The two views of the "Válaszok" tab: answers to me, and the threads I follow. */
export function RepliesTabs({ current }: { current: "replies" | "followed" }) {
return (
<nav className="fmod-tabs" aria-label="Válaszok">
<Link href="/forum/valaszok" aria-current={current === "replies" ? "page" : undefined}>
Nekem
</Link>
<Link href="/forum/kovetett" aria-current={current === "followed" ? "page" : undefined}>
Követett szálak
</Link>
</nav>
);
}
@@ -0,0 +1,106 @@
"use client";
import { useState } from "react";
import { api, errorText } from "@/lib/api";
import { REPORT_KINDS, type ReportKind } from "@/lib/forum";
/** What to do when someone may be in danger: shown right after a crisis report. */
export function CrisisHelp() {
return (
<p className="frep-crisis" role="note">
Ha azonnali veszélyt látsz, hívd a <strong>112</strong>-t. A lelki elsősegély-szolgálat ingyenes, éjjel-nappal
hívható száma: <strong>116-123</strong>.
</p>
);
}
/**
* The report form: what the problem is, an optional note, and a thank-you
* (with the helpline for a crisis report). `onClose`: the form was cancelled.
*/
export function ReportForm({ path, onClose }: { path: string; onClose: () => void }) {
const [kind, setKind] = useState<ReportKind | "">("");
const [note, setNote] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const [done, setDone] = useState<{ crisis: boolean } | null>(null);
async function submit(e: React.FormEvent) {
e.preventDefault();
if (!kind) return;
setBusy(true);
setError(null);
try {
const res = await api<{ crisis: boolean }>(path, { body: { kind, note } });
setDone(res);
} catch (err) {
setError(errorText(err));
} finally {
setBusy(false);
}
}
if (done) {
return (
<div className="frep" role="status">
<p>Köszönjük, a moderátorok megnézik. A döntésről e-mailben értesítünk.</p>
{done.crisis && <CrisisHelp />}
<button type="button" className="btn btn-ghost btn-sm frep-close" onClick={onClose}>
Bezárás
</button>
</div>
);
}
return (
<form className="frep" onSubmit={submit}>
<fieldset className="fnew-set">
<legend>Mi a gond?</legend>
{REPORT_KINDS.map((k) => (
<label key={k.kind} className="frep-kind">
<input type="radio" name={`${path}-kind`} checked={kind === k.kind} onChange={() => setKind(k.kind)} />
<span>{k.label}</span>
</label>
))}
</fieldset>
{kind === "crisis" && <CrisisHelp />}
<label className="sr-only" htmlFor={`${path}-note`}>
Megjegyzés
</label>
<textarea
id={`${path}-note`}
className="fc-text"
rows={2}
maxLength={500}
value={note}
onChange={(e) => setNote(e.target.value)}
placeholder={kind === "other" ? "Írd le röviden, mi a gond." : "Megjegyzés (nem kötelező)"}
/>
{error && (
<p className="msg msg-error" role="alert">
{error}
</p>
)}
<div className="fc-actions">
<span className="fc-spacer" />
<button type="button" className="btn btn-ghost btn-sm" onClick={onClose}>
Mégse
</button>
<button type="submit" className="btn btn-primary btn-sm" disabled={busy || !kind}>
{busy ? "Küldés…" : "Jelentés küldése"}
</button>
</div>
</form>
);
}
/** "Jelentés" as a small button that opens the form in place (private messages). */
export function ReportButton({ path, className = "fp-reply" }: { path: string; className?: string }) {
const [open, setOpen] = useState(false);
if (open) return <ReportForm path={path} onClose={() => setOpen(false)} />;
return (
<button type="button" className={className} onClick={() => setOpen(true)}>
Jelentés
</button>
);
}
@@ -0,0 +1,79 @@
import Link from "next/link";
import { POINTS, SIGNS, signName } from "@/lib/astro";
import type { ShareCardData } from "@/lib/forum";
const EYEBROW: Record<ShareCardData["kind"], string> = {
chart: "Csatolt képlet",
synastry: "Csatolt összevetés",
forecast: "Csatolt előrejelzés",
};
const POINT_LABEL: Record<string, string> = { sun: "Nap", moon: "Hold", ascendant: "Aszcendens" };
/**
* The chart, forecast or synastry a question came with: the big three with
* degrees and houses, the summary's title, and the shared page. Members only;
* a visitor sees that there is one.
*/
export function ShareCard({ share, onRemove }: { share: ShareCardData; onRemove?: () => void }) {
if (share.locked) {
return (
<div className="fshare fshare-quiet">
<span className="eyebrow">{EYEBROW[share.kind]}</span>
<span className="hint">
A kérdéshez csatolt képlet <Link href="/belepes">belépés</Link> után látható.
</span>
</div>
);
}
if (share.revoked) {
return (
<div className="fshare fshare-quiet">
<span className="eyebrow">{EYEBROW[share.kind]}</span>
<span className="hint">A szerző levette a csatolt képletet.</span>
</div>
);
}
const points = share.points ?? [];
return (
<div className="fshare">
<div className="fshare-head">
<span className="eyebrow">{EYEBROW[share.kind]}</span>
{onRemove && (
<button type="button" className="fp-link" onClick={onRemove} aria-label="Képlet levétele">
×
</button>
)}
</div>
<strong className="fshare-title">{share.title}</strong>
{share.summary && <span className="fshare-summary">„{share.summary}”</span>}
{points.length > 0 && (
<ul className="fshare-points">
{points.map((p) => (
<li key={p.id}>
<span className="sym" aria-hidden="true">
{POINTS[p.id]?.glyph ?? ""}
</span>{" "}
{POINT_LABEL[p.id] ?? p.id}{" "}
<span className="sym" aria-hidden="true">
{SIGNS[p.sign]?.glyph ?? ""}
</span>{" "}
{signName(p.sign)}
{p.degree !== null && ` ${p.degree}°`}
{p.house !== null && <span className="hint"> · {p.house}. ház</span>}
</li>
))}
</ul>
)}
{share.kind !== "synastry" && share.time_known === false && (
<span className="hint">A születési idő ismeretlen, ezért házak és Aszcendens nincsenek.</span>
)}
{share.slug && (
<Link href={`/s/${share.slug}`} className="btn btn-sm fshare-open" target="_blank" rel="noopener">
Megnyitom ›
</Link>
)}
</div>
);
}
@@ -0,0 +1,42 @@
"use client";
import { useState } from "react";
import { FORUM_THEME_COOKIE, type ForumTheme } from "@/lib/forum";
/**
* Light (the forum's default) or dark. Remembered in a cookie, so the server
* renders the chosen one and nothing flashes on load.
*/
export function ThemeToggle({ initial }: { initial: ForumTheme }) {
const [theme, setTheme] = useState<ForumTheme>(initial);
const next: ForumTheme = theme === "light" ? "dark" : "light";
function toggle() {
document.cookie = `${FORUM_THEME_COOKIE}=${next}; path=/; max-age=${60 * 60 * 24 * 365}; samesite=lax`;
document.querySelector<HTMLElement>(".forum")?.setAttribute("data-theme", next);
setTheme(next);
}
return (
<button
type="button"
className="forum-theme"
onClick={toggle}
aria-label={next === "dark" ? "Sötét téma" : "Világos téma"}
title={next === "dark" ? "Sötét téma" : "Világos téma"}
>
<svg viewBox="0 0 24 24" aria-hidden="true">
{next === "dark" ? (
<path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z" />
) : (
<>
<circle cx="12" cy="12" r="4" />
<path d="M12 2.5v2M12 19.5v2M2.5 12h2M19.5 12h2M5.3 5.3l1.4 1.4M17.3 17.3l1.4 1.4M5.3 18.7l1.4-1.4M17.3 6.7l1.4-1.4" />
</>
)}
</svg>
<span className="forum-theme-label">{next === "dark" ? "Sötét" : "Világos"}</span>
</button>
);
}
@@ -0,0 +1,86 @@
import Link from "next/link";
import { INTENTS, type ThreadCard, ago, threadHref } from "@/lib/forum";
import { Avatar } from "./Avatar";
export function IntentTag({ intent, long = false }: { intent: ThreadCard["intent"]; long?: boolean }) {
if (!intent) return null;
const text = long ? INTENTS[intent].label : INTENTS[intent].short;
return <span className={`ft-intent ft-intent-${intent}`}>{text}</span>;
}
function UnreadPill({ n }: { n: number | null }) {
if (n === null) return null;
if (n === 0) return <span className="ft-read">olvasva</span>;
return <span className="ft-new">{n > 99 ? "99+" : n} új</span>;
}
/** Threads in a list: title, topic, replies, the starter, what is new. */
export function ThreadList({ threads, showTopic = true }: { threads: ThreadCard[]; showTopic?: boolean }) {
return (
<ul className="ft-list">
{threads.map((t) => (
<li key={t.id}>
<Link href={threadHref(t)} className="ft-row">
<span className="ft-main">
<span className="ft-title">
{t.pinned && <span className="ft-pin">Kitűzve</span>}
{t.locked && <span className="ft-pin">Lezárva</span>}
{t.title}
</span>
<span className="ft-meta">
{t.author && <Avatar avatar={t.author.avatar} size={20} online={t.author.online} />}
<span>
{t.system ? "Sorsfonalak" : (t.author?.nickname ?? "Törölt tag")}
{showTopic && ` · ${t.topic.name}`}
<span className="ft-m-narrow">
{" "}
· {t.reply_count} válasz ·{" "}
<time suppressHydrationWarning dateTime={t.last_post_at}>
{ago(t.last_post_at)}
</time>
</span>
</span>
</span>
</span>
<span className="ft-col ft-col-replies">
<strong>{t.reply_count}</strong> válasz
{t.participants > 1 && <span className="hint">{t.participants} résztvevő</span>}
</span>
<span className="ft-col ft-col-last">
<time suppressHydrationWarning dateTime={t.last_post_at}>
{ago(t.last_post_at)}
</time>
</span>
<UnreadPill n={t.unread} />
</Link>
</li>
))}
</ul>
);
}
/** "Várják a válaszod": a thread without replies, with the starter's wish and a reply button. */
export function WaitingCard({ thread }: { thread: ThreadCard }) {
return (
<article className="ft-waiting">
<IntentTag intent={thread.intent} long />
<Link href={threadHref(thread)} className="ft-waiting-title">
{thread.title}
</Link>
<span className="ft-meta">
{thread.author && <Avatar avatar={thread.author.avatar} size={24} online={thread.author.online} />}
<span>
{thread.author?.nickname ?? "Törölt tag"} · {thread.topic.name} ·{" "}
<time suppressHydrationWarning dateTime={thread.created_at}>
{ago(thread.created_at)}
</time>
</span>
</span>
<Link href={`${threadHref(thread)}#valasz`} className="btn btn-sm ft-answer">
Válaszolok
</Link>
</article>
);
}
@@ -0,0 +1,816 @@
"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 { LinkPreviews } from "./LinkPreviews";
import { ShareCard } from "./ShareCard";
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<boolean>;
remove: (post: ForumPost) => void;
restore: (post: ForumPost) => void;
helped: (post: ForumPost) => void;
/** The author takes the shared chart off their question. */
detachShare: (post: ForumPost) => void;
/** Mute or unmute the post's author. */
mute: (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 (
<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]}${post.mine === r.kind ? ", a tiéd" : ""}`}
title={r.label}
disabled={!enabled}
onClick={() => onReact(post, r.kind)}
>
<ReactionIcon kind={r.kind} filled={post.mine === r.kind} />
{post.reactions[r.kind]}
</button>
))}
{enabled && (
<Popover
open={open}
onClose={() => setOpen(false)}
button={
<button
type="button"
className="fr-chip fr-add"
aria-label="Reakció hozzáadása"
aria-expanded={open}
onClick={() => setOpen((o) => !o)}
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M12 6v12M6 12h12" />
</svg>
</button>
}
>
{REACTIONS.map((r) => (
<button
key={r.kind}
type="button"
role="menuitem"
className="fpop-item"
aria-pressed={post.mine === r.kind}
onClick={() => {
setOpen(false);
onReact(post, r.kind);
}}
>
<ReactionIcon kind={r.kind} size={18} filled={post.mine === r.kind} />
{r.label}
</button>
))}
</Popover>
)}
{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")}
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M7 10l5 5 5-5" />
</svg>
</button>
)}
</div>
);
}
/** 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<HTMLSpanElement>(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 (
<span className="fpop-wrap" ref={box}>
{button}
{open && (
<span className={align === "right" ? "fpop fpop-right" : "fpop"} role="menu">
{children}
</span>
)}
</span>
);
}
/** The site's own mark as an avatar (the daily sky thread). */
function SiteMark({ size }: { size: number }) {
return (
<span className="av av-site" style={{ width: size, height: size }}>
<svg viewBox="0 0 64 64" width={size} height={size} aria-hidden="true">
<circle cx="32" cy="32" r="32" className="av-bg" />
<g fill="none" strokeWidth="4.5" strokeLinecap="round" className="av-site-mark">
<circle cx="32" cy="32" r="18" />
<path d="M15 43 C 26 42, 30 25, 42 21" />
</g>
</svg>
</span>
);
}
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 [showMuted, setShowMuted] = 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 (
<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>
);
}
// A muted member's post folds up; one click shows it.
if (post.muted && !showMuted) {
return (
<article className={nested ? "fp fp-muted fp-nested" : "fp fp-muted"} id={`h${post.id}`}>
<button type="button" className="fp-collapsed" onClick={() => setShowMuted(true)}>
{author?.nickname ?? "Egy tag"} hozzászólása · elnémítottad · Megjelenítés
</button>
</article>
);
}
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 && post.share && !post.share.revoked)
menuItems.push({ label: "Képlet levétele", run: () => actions.detachShare(post) });
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.member && !post.own && author && !post.system)
menuItems.push({
label: post.muted ? `${author.nickname} némításának feloldása` : `${author.nickname} némítása`,
run: () => actions.mute(post),
});
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 (
<article className={classes} id={`h${post.id}`}>
<span className="fp-av">
{post.system ? (
<SiteMark size={size} />
) : author ? (
<Link href={memberHref(author.nickname)} tabIndex={-1} aria-hidden="true">
<Avatar avatar={author.avatar} size={size} online={author.online} />
</Link>
) : (
<Avatar avatar={null} size={size} />
)}
</span>
<div className="fp-head">
<span className="fp-names">
{post.system ? (
<span className="fa-name">Sorsfonalak</span>
) : author ? (
<Link href={memberHref(author.nickname)} className="fa-name">
{author.nickname}
</Link>
) : (
<span className="fa-name muted">Törölt tag</span>
)}
{post.reply_to?.nickname && nested && (
<span className="fp-replyto" title={`Válasz neki: ${post.reply_to.nickname}`}>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M9 14L4 9l5-5" />
<path d="M4 9h10a6 6 0 0 1 6 6v4" />
</svg>
<span className="sr-only">válasz neki:</span>
{post.reply_to.nickname}
</span>
)}
{author?.online && <span className="sr-only">(online)</span>}
{author && <RankBadge rank={author.rank} name={author.rank_name} />}
{post.system && <Badge kind="sky" />}
{author?.moderator && <Badge kind="mod" />}
{author?.founder && !nested && <Badge kind="founder" />}
{author?.listener && <Badge kind="listener" />}
{author?.supporter && <Badge kind="supporter" />}
{starter && !post.is_opening && <Badge kind="starter" />}
{isNew && <span className="fa-badge fa-badge-new">új</span>}
{glyphs && !nested && (
<span className="fp-signs sym" title={glyphs.title}>
{glyphs.text}
</span>
)}
</span>
<time
className="fp-time"
suppressHydrationWarning
dateTime={post.created_at}
title={new Date(post.created_at).toLocaleString("hu-HU", { timeZone: "Europe/Budapest" })}
>
{ago(post.created_at)}
{post.edited_at && " · szerkesztve"}
</time>
</div>
<div className="fp-content">
{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
mentions
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} mentions={post.mentions} hide={post.links?.map((l) => l.url) ?? []} />
{post.links && post.links.length > 0 && <LinkPreviews links={post.links} />}
{post.share && <ShareCard share={post.share} />}
</>
)
)}
</div>
{!editing && (!post.deleted || menuItems.length > 0) && (
<div className="fp-actions">
{post.helped && (
<span className="fp-helped" title={`${thread.author?.nickname ?? "A szál indítója"} szerint ez segített`}>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M5 12.5l4.5 4.5L19 7.5" />
</svg>
Segített
</span>
)}
{!post.deleted && (
<ReactionRow
post={post}
enabled={canReact}
canDownvote={access?.can_downvote ?? false}
onReact={actions.react}
/>
)}
<span className="fp-spacer" />
{viewer.moderator && typeof post.down === "number" && post.down > 0 && (
<span className="hint" title="Nem visz előre jelzések (csak moderátoroknak)">
⌄ {post.down}
</span>
)}
{!post.deleted && access?.can_reply && writer && !post.is_opening && (
<button type="button" className="fp-reply" onClick={() => actions.replyTo(post)}>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M9 14L4 9l5-5" />
<path d="M4 9h10a6 6 0 0 1 6 6v4" />
</svg>
Válasz
</button>
)}
{menuItems.length > 0 && (
<Popover
open={menu}
onClose={() => setMenu(false)}
align="right"
button={
<button
type="button"
className="fp-more"
aria-label="Továbbiak"
aria-expanded={menu}
onClick={() => setMenu((m) => !m)}
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<circle cx="5.5" cy="12" r="1.6" />
<circle cx="12" cy="12" r="1.6" />
<circle cx="18.5" cy="12" r="1.6" />
</svg>
</button>
}
>
{menuItems.map((item) => (
<button
key={item.label}
type="button"
role="menuitem"
className={item.danger ? "fpop-item fpop-danger" : "fpop-item"}
onClick={() => {
setMenu(false);
item.run();
}}
>
{item.label}
</button>
))}
</Popover>
)}
</div>
)}
{reporting && (
<div className="fp-report">
<ReportForm path={`/forum/posts/${post.id}/report`} onClose={() => setReporting(false)} />
</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 typingNow = useTypingWatch("thread", initial.thread.id);
const imTyping = useTypingSender("thread", initial.thread.id);
const composer = useRef<HTMLDivElement>(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<HTMLDivElement>(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<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);
// The live connection rings for this thread: look at once.
const live = (e: Event) => {
const notice = (e as CustomEvent<LiveNotice>).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<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),
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();
}),
detachShare: (post) => {
if (!window.confirm("Leveszed a csatolt képletet? A kártya eltűnik, és a link sem működik többé.")) return;
void run(async () => {
await api(`/forum/posts/${post.id}/share`, { method: "DELETE" });
await reload();
});
},
mute: (post) => {
const nickname = post.author?.nickname;
if (!nickname) return;
if (
!post.muted &&
!window.confirm(
`Elnémítod ${nickname} tagot? A szálai eltűnnek a listáidból, a hozzászólásai összecsukva látszanak, és nem kapsz értesítést tőle. Ő erről nem tud. A beállításoknál bármikor feloldhatod.`,
)
)
return;
void run(async () => {
await api(`/forum/members/${encodeURIComponent(nickname)}/mute`, { method: post.muted ? "DELETE" : "PUT" });
await reload();
});
},
helped: (post) =>
void run(async () => {
const updated = await api<ForumPost>(`/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<boolean> {
const post = await run(() => api<ForumPost>(`${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 (
<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>
{thread.topic.visibility !== "public" && (
<span
className="ftv-private"
title={
thread.topic.visibility === "members"
? "Csak belépett tagok látják, a keresők sem"
: "Zárt kör: csak a jóváhagyott tagok látják"
}
>
<svg viewBox="0 0 24 24" aria-hidden="true">
<rect x="5" y="11" width="14" height="9" rx="2" />
<path d="M8 11V8a4 4 0 0 1 8 0v3" />
</svg>
{thread.topic.visibility === "members" ? "csak tagoknak" : "zárt kör"}
</span>
)}
</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}
<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>
{intent && (
<p className="ftv-intent-line">
<span className={`ft-intent ft-intent-${thread.intent}`}>{intent.label}</span>
{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`}
</p>
)}
{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}
nested
post={child}
page={page}
actions={actions}
isNew={firstUnread !== null && child.id >= firstUnread && !child.own}
/>
))}
</div>
)}
{replyTo && replyBranch === top.id && (
<div className="ftv-inline" ref={inline}>
<p className="ftv-replyto">
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M9 14L4 9l5-5" />
<path d="M4 9h10a6 6 0 0 1 6 6v4" />
</svg>
Válasz neki: <strong>{replyTo.author?.nickname ?? "Törölt tag"}</strong>
</p>
<Composer
key={top.id}
mentions
onTyping={imTyping}
id={`valasz-${top.id}`}
label={`Válasz neki: ${replyTo.author?.nickname ?? "Törölt tag"}`}
placeholder="Írd meg a válaszod…"
initial={draft.current}
onChange={(text) => {
draft.current = text;
}}
busy={busy}
onSubmit={(text) => sendReply(text, replyTo)}
onCancel={() => {
draft.current = "";
setReplyTo(null);
}}
/>
</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>
)}
<TypingLine text={typingNow} />
<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">
{thread.topic.archived
? "Ez a téma archivált: olvasható, de új hozzászólás nem írható."
: "Ez a szál le van zárva, új hozzászólás nem írható."}
</p>
) : (
<>
<Composer
mentions
onTyping={imTyping}
id="valasz-szoveg"
label="Válaszod"
placeholder={thread.topic.listening ? "Írd le, ami benned van…" : "Írd meg a válaszod…"}
busy={busy}
onSubmit={(text) => sendReply(text, null)}
/>
</>
)}
</div>
</div>
);
}
@@ -0,0 +1,79 @@
"use client";
import { useCallback, useEffect, useRef, useState } from "react";
import type { LiveNotice } from "./ForumNav";
/** The live connection's outgoing "I am typing" (ForumNav sends it). */
export interface TypingOut {
kind: "thread" | "conversation";
id: number;
}
/** A typing notice is sent at most this often while typing. */
const SEND_EVERY_MS = 3000;
/** "X gépel…" disappears this long after the last notice. */
const SHOW_MS = 6000;
/** Call on every keystroke: tells the others (now and then) that the member is typing here. */
export function useTypingSender(kind: TypingOut["kind"], id: number) {
const last = useRef(0);
return useCallback(() => {
const now = Date.now();
if (now - last.current < SEND_EVERY_MS) return;
last.current = now;
window.dispatchEvent(new CustomEvent<TypingOut>("forum:typing-out", { detail: { kind, id } }));
}, [kind, id]);
}
/** Who is typing here now: "Holdfény gépel…", "Holdfény és Zöldág gépel…", or null. */
export function useTypingWatch(kind: TypingOut["kind"], id: number): string | null {
const [who, setWho] = useState<Record<string, number>>({});
useEffect(() => {
const live = (e: Event) => {
const n = (e as CustomEvent<LiveNotice & { kind?: string; who?: string }>).detail;
if (n.t === "typing" && n.kind === kind && n.id === id && n.who) {
setWho((w) => ({ ...w, [n.who as string]: Date.now() }));
}
// Their post or message arrived: they are done.
if ((n.t === "thread" && kind === "thread" && n.id === id) || (n.t === "conversation" && n.id === id)) {
setWho({});
}
};
window.addEventListener("forum:live", live);
const timer = window.setInterval(() => {
setWho((w) => {
const now = Date.now();
const kept = Object.fromEntries(Object.entries(w).filter(([, at]) => now - at < SHOW_MS));
return Object.keys(kept).length === Object.keys(w).length ? w : kept;
});
}, 1000);
return () => {
window.removeEventListener("forum:live", live);
window.clearInterval(timer);
};
}, [kind, id]);
const names = Object.keys(who);
if (names.length === 0) return null;
if (names.length === 1) return `${names[0]} gépel…`;
if (names.length === 2) return `${names[0]} és ${names[1]} gépel…`;
return `${names.length} tag gépel…`;
}
/** The "… gépel" line with three soft dots. */
export function TypingLine({ text }: { text: string | null }) {
return (
<p className="ftyping" aria-live="polite">
{text && (
<>
<span className="ftyping-dots" aria-hidden="true">
<span />
<span />
<span />
</span>
{text}
</>
)}
</p>
);
}