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

46 lines
1.5 KiB
TypeScript
Raw Normal View History

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. */
export function PostBody({ text, mentions = [] }: { text: string; mentions?: string[] }) {
return (
<div className="fp-body">
{text.split(/\n{2,}/).map((para, i) => (
<p key={i}>
{para.split("\n").map((line, j) => (
<span key={j}>
{j > 0 && <br />}
{withMentions(line, mentions)}
</span>
))}
</p>
))}
</div>
);
}