From ef0e3fad7d7aa0bba7c5c15725bb16e1d1682a12 Mon Sep 17 00:00:00 2001 From: Moepchi Date: Sun, 4 Oct 2026 11:09:05 +0000 Subject: [PATCH] feat: more BBCode tags, basic Markdown and an opt-in for chat images Chat now renders [size], [left]/[center]/[right], [list]/[*], [hr] and [noparse] plus the Markdown TS6 sends (emphasis, code, links, images, quotes, lists, headings, rules, escapes). [img] stays a link unless "Load images in chat" is enabled in Options -> Application (off by default, since loading reveals the reader's IP to the image host). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU --- web/src/App.css | 44 ++++++ web/src/App.tsx | 38 +++++- web/src/lib/bbcode.tsx | 265 ++++++++++++++++++++++++++++++------- web/src/locales/de.json | 2 + web/src/locales/en.json | 2 + web/src/locales/fa.json | 2 + web/src/locales/zh-CN.json | 2 + 7 files changed, 305 insertions(+), 50 deletions(-) diff --git a/web/src/App.css b/web/src/App.css index ff9262e..0ff9f5c 100644 --- a/web/src/App.css +++ b/web/src/App.css @@ -2457,6 +2457,50 @@ text-decoration: underline; } +.ts-chat-bubble code { + font-family: ui-monospace, monospace; + font-size: 0.95em; + padding: 0 0.25em; + border: 1px solid var(--border-soft); + border-radius: 3px; +} + +.ts-bb-list { + margin: 0.15em 0; + padding-left: 1.6em; +} + +.ts-bb-quote { + margin: 0.15em 0; + padding-left: 0.6em; + border-left: 3px solid var(--border-soft); +} + +.ts-bb-hr { + border: 0; + border-top: 1px solid var(--border-soft); + margin: 0.3em 0; +} + +.ts-bb-h { + font-weight: bold; + font-size: 1.1em; +} + +.ts-bb-h1 { + font-size: 1.4em; +} + +.ts-bb-h2 { + font-size: 1.2em; +} + +.ts-bb-img { + max-width: 100%; + max-height: 240px; + vertical-align: middle; +} + .ts-chat-from { font-weight: 600; color: var(--accent); diff --git a/web/src/App.tsx b/web/src/App.tsx index 3798cc4..9b628f9 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -556,6 +556,8 @@ const AWAY_PRESETS_KEY = "webspeak3:away-presets"; /** "off" hides the server banner: it loads from whatever host the server * admin picked, which then sees the viewer's IP (review S12). */ const SERVER_BANNER_KEY = "webspeak3:server-banner"; +// Off by default: an inline chat image loads from whatever host the sender picked. +const CHAT_IMAGES_KEY = "webspeak3:chat-images"; const DISCONNECT_MESSAGE_KEY = "webspeak3:disconnect-message"; const COLLECTED_URLS_KEY = "webspeak3:collected-urls"; @@ -5425,9 +5427,13 @@ function AufnahmePanel({ audio }: { audio: AudioSettings }) { function AnwendungPanel({ showServerBanner, onShowServerBannerChange, + chatImages, + onChatImagesChange, }: { showServerBanner: boolean; onShowServerBannerChange: (on: boolean) => void; + chatImages: boolean; + onChatImagesChange: (on: boolean) => void; }) { const t = useT(); const { langPref, setLangPref } = useLanguage(); @@ -5455,6 +5461,11 @@ function AnwendungPanel({ {t("app.serverBanner")}

{t("app.serverBanner.hint")}

+ +

{t("app.chatImages.hint")}

); } @@ -6246,6 +6257,8 @@ function OptionsDialog({ onDeleteCustomTheme, showServerBanner, onShowServerBannerChange, + chatImages, + onChatImagesChange, }: { section: string; onSectionChange: (id: string) => void; @@ -6258,6 +6271,8 @@ function OptionsDialog({ onDeleteCustomTheme: (id: string) => void; showServerBanner: boolean; onShowServerBannerChange: (on: boolean) => void; + chatImages: boolean; + onChatImagesChange: (on: boolean) => void; }) { const t = useT(); const active = OPTIONS_SECTIONS.find((s) => s.id === section) ?? OPTIONS_SECTIONS[0]; @@ -6286,7 +6301,12 @@ function OptionsDialog({
{active.id === "anwendung" ? ( - + ) : active.id === "wiedergabe" ? ( ) : active.id === "aufnahme" ? ( @@ -6637,6 +6657,7 @@ function AppInner() { const [serverLicenseId, setServerLicenseId] = useState(0); const [serverBannerUrl, setServerBannerUrl] = useState(""); const [showServerBanner, setShowServerBanner] = useState(() => localStorage.getItem(SERVER_BANNER_KEY) !== "off"); + const [chatImages, setChatImages] = useState(() => localStorage.getItem(CHAT_IMAGES_KEY) === "on"); const [serverWelcomeMessage, setServerWelcomeMessage] = useState(""); const [serverEditOpen, setServerEditOpen] = useState(false); const [serverProtocolLogOpen, setServerProtocolLogOpen] = useState(false); @@ -10929,6 +10950,15 @@ function AppInner() { /* private mode: setting just doesn't persist */ } }} + chatImages={chatImages} + onChatImagesChange={(on) => { + setChatImages(on); + try { + localStorage.setItem(CHAT_IMAGES_KEY, on ? "on" : "off"); + } catch { + /* private mode: setting just doesn't persist */ + } + }} audio={{ outputDevices, outputDeviceId, @@ -11645,7 +11675,7 @@ function AppInner() { className={`ts-chat-line${entry.from === ownClient?.name ? " ts-chat-line-self" : ""}`} > {entry.from}:{" "} - {renderBbcode(entry.message)} + {renderBbcode(entry.message, { images: chatImages })}
)) : activeTab === "server" @@ -11660,7 +11690,7 @@ function AppInner() { className={`ts-chat-line${entry.from === ownClient?.name ? " ts-chat-line-self" : ""}`} > {entry.from}:{" "} - {renderBbcode(entry.message)} + {renderBbcode(entry.message, { images: chatImages })} ) ) @@ -11669,7 +11699,7 @@ function AppInner() { {entry.fromSelf ? t("chat.you") : pmThreads[activeTab].partnerName}: {" "} - {renderBbcode(entry.message)} + {renderBbcode(entry.message, { images: chatImages })} ))}
diff --git a/web/src/lib/bbcode.tsx b/web/src/lib/bbcode.tsx index 79bc701..9fb0cfe 100644 --- a/web/src/lib/bbcode.tsx +++ b/web/src/lib/bbcode.tsx @@ -1,16 +1,39 @@ import { Fragment, type ReactNode } from "react"; -// TeamSpeak chat BBCode -> React elements (never HTML strings, so message text -// can't inject markup). Unknown tags stay as literal text, unclosed tags close -// at the end of the message, and bare URLs are linked too. -// ponytail: only the inline tags people actually send; [list]/[table]/[img] -// render as plain text ([img] as a link, so it never loads a remote image). +// TeamSpeak chat text -> React elements (never HTML strings, so message text +// can't inject markup). Understands the TS3/TS6 BBCode tags plus the basic +// Markdown TS6 sends: Markdown is first rewritten into BBCode, then a single +// parser renders both. Unknown tags stay literal, unclosed tags close at the end. +// ponytail: no [table], nested Markdown lists/quotes, ==highlight==, ||spoiler||, +// math or mermaid - add them once people actually send them. -const TAG_REGEX = /\[(\/?)(b|i|u|s|url|img|color)(?:=([^\]]*))?\]/gi; +const TAG_REGEX = + /\[(\/?)(b|i|u|s|url|img|color|size|left|center|right|list|\*|hr|noparse|md-code|md-quote|md-h)(?:=([^\]]*))?\]/gi; +const BLOCK_TAGS = new Set(["left", "center", "right", "list", "*", "hr", "md-quote", "md-h"]); export const BARE_URL_REGEX = /https?:\/\/[^\s<>"\[\]]+/g; -// An already-tagged link (left alone) or a bare URL (wrapped). -const WRAP_REGEX = new RegExp(`(\\[(url|img)(?:=[^\\]]*)?\\][\\s\\S]*?\\[\\/\\2\\])|${BARE_URL_REGEX.source}`, "gi"); const COLOR_REGEX = /^(#[0-9a-f]{3}|#[0-9a-f]{6}|[a-z]+)$/i; +const LIST_STYLES: Record = { "1": "decimal", a: "lower-alpha", A: "upper-alpha", i: "lower-roman", I: "upper-roman" }; + +// Spans Markdown must not touch: noparse, tagged links, inline code, Markdown +// links/images, , bare URLs and backslash escapes. +const MD_SPANS = new RegExp( + [ + String.raw`\[noparse\][\s\S]*?\[\/noparse\]`, + String.raw`\[(url|img)(?:=[^\]]*)?\][\s\S]*?\[\/\1\]`, + String.raw`\x60([^\x60\n]+)\x60`, + String.raw`(!?)\[([^\]\n]*)\]\(]+)>?(?:\s[^)\n]*)?\)`, + String.raw`<(https?:\/\/[^\s>]+)>`, + BARE_URL_REGEX.source, + String.raw`\\([\\\x60*_{}\[\]()#+\-.!~>|=])`, + ].join("|"), + "gi", +); +// Outgoing: an already-tagged link or Markdown span (left alone) or a bare URL (wrapped). +const WRAP_REGEX = new RegExp( + String.raw`(\[(url|img)(?:=[^\]]*)?\][\s\S]*?\[\/\2\]|!?\[[^\]\n]*\]\([^)\n]*\)|\x60[^\x60\n]*\x60|]+>)|` + + BARE_URL_REGEX.source, + "gi", +); interface Node { tag: string; @@ -18,6 +41,108 @@ interface Node { children: (Node | string)[]; } +export interface RenderOptions { + /** Load [img] / ![](...) inline. Off: they render as links, so no remote host sees the reader's IP. */ + images?: boolean; +} + +function emphasis(s: string): string { + return s + .replace(/\*\*(?=\S)([^\n]*?\S)\*\*/g, "[b]$1[/b]") + .replace(/~~(?=\S)([^\n]*?\S)~~/g, "[s]$1[/s]") + .replace(/\+\+(?=\S)([^\n]*?\S)\+\+/g, "[u]$1[/u]") + .replace(/(^|[^\w*[])\*(?=[^\s\]])([^*\n]*?\S)\*(?![\w*])/g, "$1[i]$2[/i]") + .replace(/(^|[^\w_[])_(?=[^\s\]])([^_\n]*?\S)_(?![\w_])/g, "$1[i]$2[/i]"); +} + +function markdownInline(text: string): string { + let out = ""; + let last = 0; + for (const m of text.matchAll(MD_SPANS)) { + out += emphasis(text.slice(last, m.index)); + last = m.index + m[0].length; + if (m[2] !== undefined) out += `[md-code][noparse]${m[2]}[/noparse][/md-code]`; + else if (m[5] !== undefined) out += m[3] ? `[img]${m[5]}[/img]` : `[url=${m[5]}]${m[4] || m[5]}[/url]`; + else if (m[6] !== undefined) out += m[6]; + else if (m[7] !== undefined) out += `[noparse]${m[7]}[/noparse]`; + else out += m[0]; + } + return out + emphasis(text.slice(last)); +} + +// Line-based Markdown blocks (TS6: one line is one paragraph): lists, quotes, +// headings and rules. Consecutive list/quote lines are grouped. +function markdownBlocks(text: string): string { + const out: { block: boolean; s: string }[] = []; + let group = null as { kind: string; items: string[] } | null; + const flush = () => { + if (!group) return; + const s = + group.kind === "quote" + ? `[md-quote]${group.items.join("\n")}[/md-quote]` + : `[list${group.kind === "ol" ? "=1" : ""}]${group.items.map((i) => `[*]${i}`).join("")}[/list]`; + out.push({ block: true, s }); + group = null; + }; + for (const line of text.split("\n")) { + const item = /^\s*([-*+]|\d+[.)])\s+(.*)$/.exec(line); + const quote = /^>(?:\s(.*))?$/.exec(line); + const kind = item ? (/\d/.test(item[1]) ? "ol" : "ul") : quote ? "quote" : null; + if (kind) { + if (group?.kind !== kind) flush(); + group ??= { kind, items: [] }; + group.items.push(item ? item[2] : (quote![1] ?? "")); + continue; + } + flush(); + const heading = /^(#{1,3})\s+(.+)$/.exec(line); + if (/^\s*(-{3,}|\*{3,}|_{3,})\s*$/.test(line)) out.push({ block: true, s: "[hr]" }); + else if (heading) out.push({ block: true, s: `[md-h=${heading[1].length}]${heading[2]}[/md-h]` }); + else out.push({ block: false, s: line }); + } + flush(); + return out.map((e, i) => (i > 0 && !e.block && !out[i - 1].block ? "\n" : "") + e.s).join(""); +} + +function parse(text: string): Node { + const root: Node = { tag: "", children: [] }; + const stack = [root]; + const re = new RegExp(TAG_REGEX.source, "gi"); + let last = 0; + for (let m; (m = re.exec(text)); ) { + const top = stack[stack.length - 1]; + if (m.index > last) top.children.push(text.slice(last, m.index)); + last = re.lastIndex; + const tag = m[2].toLowerCase(); + if (m[1]) { + const at = stack.findLastIndex((n) => n.tag === tag); + if (at > 0) stack.length = at; + else top.children.push(m[0]); + } else if (tag === "noparse") { + const end = text.toLowerCase().indexOf("[/noparse]", last); + const stop = end < 0 ? text.length : end; + top.children.push({ tag, children: [text.slice(last, stop)] }); + last = re.lastIndex = end < 0 ? stop : end + "[/noparse]".length; + } else if (tag === "hr") { + top.children.push({ tag, children: [] }); + } else if (tag === "*") { + const at = stack.findLastIndex((n) => n.tag === "list"); + if (at > 0) { + stack.length = at + 1; + const li: Node = { tag, children: [] }; + stack[at].children.push(li); + stack.push(li); + } else top.children.push(m[0]); + } else { + const node: Node = { tag, arg: m[3], children: [] }; + top.children.push(node); + stack.push(node); + } + } + if (last < text.length) stack[stack.length - 1].children.push(text.slice(last)); + return root; +} + function safeHref(raw: string): string | null { const url = raw.trim(); return /^https?:\/\//i.test(url) ? url : /^www\./i.test(url) ? `https://${url}` : null; @@ -31,25 +156,45 @@ function link(href: string, children: ReactNode, key: number) { ); } -function linkify(text: string, key: number): ReactNode { +function textNode(text: string, key: number, linkUrls = true): ReactNode { const parts: ReactNode[] = []; - let last = 0; - for (const m of text.matchAll(BARE_URL_REGEX)) { - if (m.index > last) parts.push(text.slice(last, m.index)); - parts.push(link(m[0], m[0], m.index)); - last = m.index + m[0].length; - } - if (last === 0) return text; - if (last < text.length) parts.push(text.slice(last)); - return {parts}; + text.split("\n").forEach((line, li) => { + if (li > 0) parts.push(
); + let last = 0; + if (linkUrls) { + for (const m of line.matchAll(BARE_URL_REGEX)) { + if (m.index > last) parts.push(line.slice(last, m.index)); + parts.push(link(m[0], m[0], li * 10000 + m.index)); + last = m.index + m[0].length; + } + } + if (last < line.length) parts.push(line.slice(last)); + }); + return parts.length === 1 && typeof parts[0] === "string" ? parts[0] : {parts}; } function textOf(node: Node): string { return node.children.map((c) => (typeof c === "string" ? c : textOf(c))).join(""); } -function render(node: Node, key: number): ReactNode { - const kids = () => node.children.map((c, i) => (typeof c === "string" ? linkify(c, i) : render(c, i))); +function fontSize(arg: string | undefined): string | undefined { + const rel = /^([+-])(\d)$/.exec(arg ?? ""); + if (rel) return `${Math.min(2, Math.max(0.6, 1 + (rel[1] === "+" ? 1 : -1) * Number(rel[2]) * 0.2))}em`; + return /^\d{1,3}$/.test(arg ?? "") ? `${Math.min(28, Math.max(6, Number(arg)))}pt` : undefined; +} + +function render(node: Node, key: number, opts: RenderOptions): ReactNode { + const isBlock = (c: Node | string | undefined) => typeof c === "object" && BLOCK_TAGS.has(c.tag); + const kids = () => + node.children.map((c, i, all) => { + if (typeof c !== "string") return render(c, i, opts); + // Line breaks around block elements are already breaks; drop them. + let s = c; + if (i === 0 ? isBlock(node) : isBlock(all[i - 1])) s = s.replace(/^\n/, ""); + if (i === all.length - 1 ? isBlock(node) : isBlock(all[i + 1])) s = s.replace(/\n$/, ""); + if (node.tag === "list" && !s.trim()) return null; + return textNode(s, i); + }); switch (node.tag) { case "b": return {kids()}; @@ -60,49 +205,77 @@ function render(node: Node, key: number): ReactNode { case "s": return {kids()}; case "color": - return node.arg && COLOR_REGEX.test(node.arg) ? ( - + return ( + {kids()} + ); + case "size": + return ( + + {kids()} + + ); + case "left": + case "center": + case "right": + return ( +
+ {kids()} +
+ ); + case "list": { + const style = node.arg ? LIST_STYLES[node.arg] : undefined; + return style ? ( +
    + {kids()} +
) : ( - {kids()} +
    + {kids()} +
+ ); + } + case "*": + return
  • {kids()}
  • ; + case "hr": + return
    ; + case "noparse": + return textNode(textOf(node), key, false); + case "md-code": + return {kids()}; + case "md-quote": + return ( +
    + {kids()} +
    + ); + case "md-h": + return ( +
    + {kids()} +
    ); case "url": case "img": { const href = safeHref(node.arg ?? textOf(node)); // Plain-text label: a linkified URL or nested tag inside would nest links. const label = textOf(node); - return href ? link(href, label, key) : {label}; + if (!href) return {label}; + if (node.tag === "img" && opts.images) + return link(href, , key); + return link(href, label, key); } default: return {kids()}; } } -export function renderBbcode(text: string): ReactNode { - const root: Node = { tag: "", children: [] }; - const stack = [root]; - let last = 0; - for (const m of text.matchAll(TAG_REGEX)) { - const top = stack[stack.length - 1]; - if (m.index > last) top.children.push(text.slice(last, m.index)); - last = m.index + m[0].length; - const tag = m[2].toLowerCase(); - if (m[1]) { - const at = stack.findLastIndex((n) => n.tag === tag); - if (at > 0) stack.length = at; - else top.children.push(m[0]); - } else { - const node: Node = { tag, arg: m[3], children: [] }; - top.children.push(node); - stack.push(node); - } - } - if (last < text.length) stack[stack.length - 1].children.push(text.slice(last)); - return render(root, 0); +export function renderBbcode(text: string, opts: RenderOptions = {}): ReactNode { + return render(parse(markdownInline(markdownBlocks(text.replace(/\r\n?/g, "\n")))), 0, opts); } // Outgoing: native clients send links as [URL]...[/URL] and only link those. export function wrapUrls(text: string): string { - return text.replace(WRAP_REGEX, (m, tagged) => (tagged ? m : `[URL]${m}[/URL]`)); + return text.replace(WRAP_REGEX, (m, kept) => (kept ? m : `[URL]${m}[/URL]`)); } diff --git a/web/src/locales/de.json b/web/src/locales/de.json index 5768e61..4fd2a46 100644 --- a/web/src/locales/de.json +++ b/web/src/locales/de.json @@ -341,6 +341,8 @@ "app.language.helpTranslate": "Fehlt deine Sprache oder eine Übersetzung ist ungenau? Hilf mit auf Weblate →", "app.serverBanner": "Server-Banner anzeigen", "app.serverBanner.hint": "Das Banner lädt direkt von der Adresse, die der Serverbetreiber eingetragen hat. Dieser Host sieht dabei deine IP-Adresse.", + "app.chatImages": "Bilder im Chat laden", + "app.chatImages.hint": "Bilder aus [img]-Tags und Markdown laden direkt von der Adresse, die der Absender gewählt hat, und dieser Host sieht deine IP-Adresse. Ausgeschaltet erscheinen sie als Link.", "playback.title": "Wiedergabe", "playback.subtitle": "Ändern der Wiedergabeeinstellungen", "playback.profile": "Profile", diff --git a/web/src/locales/en.json b/web/src/locales/en.json index e2b47db..e98cce5 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -341,6 +341,8 @@ "app.language.helpTranslate": "Missing your language or spotted a wrong translation? Help out on Weblate →", "app.serverBanner": "Show server banners", "app.serverBanner.hint": "The banner loads straight from the address the server admin set, and that host sees your IP address.", + "app.chatImages": "Load images in chat", + "app.chatImages.hint": "Images from [img] tags and Markdown load straight from the address the sender picked, and that host sees your IP address. When off, they show as links.", "playback.title": "Playback", "playback.subtitle": "Change your playback settings", "playback.profile": "Profile", diff --git a/web/src/locales/fa.json b/web/src/locales/fa.json index 0510613..4dff003 100644 --- a/web/src/locales/fa.json +++ b/web/src/locales/fa.json @@ -341,6 +341,8 @@ "app.language.helpTranslate": "زبان شما موجود نیست یا ترجمه‌ای اشتباه دیدید؟ در Weblate کمک کنید →", "app.serverBanner": "نمایش بنر سرور", "app.serverBanner.hint": "بنر مستقیماً از نشانی‌ای بارگیری می‌شود که مدیر سرور تعیین کرده است و آن میزبان نشانی IP شما را می‌بیند.", + "app.chatImages": "بارگیری تصاویر در گفتگو", + "app.chatImages.hint": "تصاویر برچسب‌های [img] و مارک‌داون مستقیماً از نشانی‌ای که فرستنده انتخاب کرده بارگیری می‌شوند و آن میزبان نشانی IP شما را می‌بیند. در حالت خاموش به‌صورت پیوند نمایش داده می‌شوند.", "playback.title": "پخش", "playback.subtitle": "تنظیمات پخش را تغییر بده", "playback.profile": "پروفایل", diff --git a/web/src/locales/zh-CN.json b/web/src/locales/zh-CN.json index 47bb10e..e12fbc6 100644 --- a/web/src/locales/zh-CN.json +++ b/web/src/locales/zh-CN.json @@ -244,6 +244,8 @@ "app.language.helpTranslate": "没有你的语言,或发现翻译有误?欢迎到 Weblate 参与改进 →", "app.serverBanner": "显示服务器横幅", "app.serverBanner.hint": "横幅直接从服务器管理员设置的地址加载,该主机会看到你的 IP 地址。", + "app.chatImages": "在聊天中加载图片", + "app.chatImages.hint": "[img] 标签和 Markdown 中的图片直接从发送者指定的地址加载,该主机会看到你的 IP 地址。关闭时显示为链接。", "playback.title": "播放", "playback.subtitle": "更改播放设置", "playback.profile": "配置",